Symbolic Computations (SyCo) / Cálculos simbólicos
FU:TFNPF0001 – akad. navazující Mgr SP TFYZNM Teoretická fyzika (st. plán TFYPOFYNM Počítačová fyzika): 2/2/0, 6 kreditů, Zko
FU:ETFNPF0001 – acad. follow-up Master SP TFYZNM Theoretical Physics (plan TFYPOFYNM Computational Physics): 2/2/0, 6 crds, Exam
Garance, přednášky & cvičení / Guaranteed by, lectures and exercises: doc. RNDr. Stanislav Hledík, Ph.D.
Informace o kursu ● Výuka ● Hodnocení a zkoušení ● Literatura ● Odkazy a zdroje ● Často kladené dotazy
About the course ● Tuition ● Evaluation and testing ● References ● Links and resources ● FAQ
Informace o kursu / About the course
Anotace / Annotation
This course introduces the principles of the Wolfram Language – a symbolic language, based on “pattern-matching and replacement rule-based programming” and functional programming paradigms, and its tools for solving tasks and problems in physics, mathematics, and related fields. It allows ideas to be cast into a computer representation that is efficient, elegant, fast, scalable and bug-free.
Sylabus / Content
★ separates different topics within a lecture, ★★ separates further reading on the topic(s) covered (“See also …”).
1. Hands-on introduction to Mathematica and the Wolfram Language
References and resources. Getting started and basic usage, Wolfram Mathematica environment, notebook, cell, basic syntax, setting preferences. Procedure for “manual” calculations. Symbolic mathematics. Numerical mathematics. Programming paradigms: procedural, pattern matching and replacement (also substitution , transformation) rules, functional. Multimedia. Dynamic expressions. Files and external operations. ★★ See also An Elementary Introduction to the Wolfram Language, 3rd Ed. by Stephen Wolfram, The Wolfram Language: Fast Introduction for Programmers, Mathematica & Wolfram Language: Fast Introduction for Math Students, Resources for Software Developers.
2. Principles of the Wolfram Language, programming based on pattern matching and replacement rules
Expressions, patterns, rules, evaluation. First Principle: Everything is an expression. Normal and atomic expressions, different meanings of expressions, special ways of entering expressions. Head of expression: Head, atomicity check: AtomQ, internal form: FullForm, InputForm, tree structure: TreeForm. Disassembling expressions: Part ([[…]]); levels in expressions: Level. Second Principle: Pattern-matching and Rule substitution (or replacement, transformation). Basic patterns: Blank (_), BlankSequence (__), BlankNullSequence (___) and replacement rules: Rule (->), RuleDelayed (:>), Set (=), SetDelayed (:=), optimization of list of rules: Dispatch. Test pattern matching with MatchQ, FreeQ, MemberQ. Searching and selecting expressions with Cases, FirstCase, DeleteCases, Count, Pick, Position, FirstPosition. Transforming expressions with Replace, ReplaceAll (/.), ReplacePart, ReplaceAt, ReplaceList, ReplaceRepeated (//.). Naming patterns: Pattern (:). Restricting patterns: restriction by head (argument to Blank (_) etc.), restriction by test (predicate): PatternTest (?), restriction by Condition (/;). Variable number of arguments: BlankSequence (__), BlankNullSequence (___). Default values: Optional (:), Default. Alternative and repeated patterns: Alternatives (|), Repeated (..), RepeatedNull (...). Exception: Except. Longest and shortest sequence: Longest, Shortest. Sequence of patterns: PatternSequence, OrderlessPatternSequence, SequenceCases. Third Principle: Expression evaluation standard and nonstandard: Evaluate, Unevaluated, Hold, ReleaseHold, HoldFirst, HoldRest, HoldAll. ★ Functions are actually rules: OwnValues, DownValues, SubValues; non-commutativity and automatic reordering of replacement rules. Multiple definition of a single function (function overloading). Side effects. ★★ See also Wolfram Language Syntax and tutorials Operator Input Forms, Textual Input and Output, Everything Is an Expression, Parts of Expressions, Patterns and Transformation Rules, Applying Transformation Rules, The Meaning of Expressions.
3. Lists, pure functions, and some minutiae
Lists (List, {…}). Generating lists manually, using menu, programmatically: Range, PowerRange, Table, Array, ConstantArray, SparseArray, UnitVector, DiagonalMatrix, IdentityMatrix, KroneckerDelta. Measuring lists: Length, Dimensions, Depth, ArrayDepth, VectorQ, MatrixQ, Array. Parts of lists and their manipulation: Part ([[…]]), Span (;;), Extract, First, Last, Most, Rest, Take, Drop, TakeDrop, TakeWhile, LengthWhile, Pick. Mapping list elements: Map (/@), Scan, MapAt, MapIndexed, MapAll (//@). Mapping two or more lists: Thread, MapThread, Through, Inner, Outer. Changing the head: Apply (@@), MapApply (@@@). Inserting and deleting elements: Prepend, Append, PrependTo, AppendTo, Insert, ReplacePart, Delete, Riffle, PadLeft, PadRight, ArrayPad, Nothing. Deleting duplicate elements: DeleteDuplicates, DeleteDuplicatesBy, Union. Sorting: Sort, ReverseSort, SortBy, ReverseSortBy, Ordering, OrderingBy. Searching for positions of elements: Position, Extract, Ordering. Sequences: Sequence, Splice. Grouping and splitting: Flatten, FlattenAt, Partition, Split, SplitBy, Tally, Gather, GatherBy. Rearranging and transmogrifying elements: Transpose, ConjugateTranspose, Union, Reverse, RotateLeft, RotateRight. Combinatorial operations: Permutations, Subsets, Tuples. Searching for elements: Select, SelectFirst, Cases, Count, DeleteCases. Operations with multiple lists: Join, Catenate, Union, Intersection, Complement, SymmetricDifference. ★ Pure functions (also anonymous functions, λ-functions): Function (&, |->), Slot (#), SlotSequence (##), Compile, CompiledFunction. ★ Logical operators: And (&&), Or (||), Not (!), Nand, Nor, Xor, True, False, BooleanQ, … ★ Other ‘=’-related operators: AddTo (+=), Increment (++), PreIncrement (++), SubtractFrom (-=), Decrement (--), PreDecrement (--), TimesBy (*=), DivideBy (/=), ApplyTo (//=). ★ Equality and non-equality checks: Equal (==), Unequal (!=), Less (<), LessEqual (<=), Greater (>), GreaterEqual (>=), SameQ (===), UnsameQ (=!=), TrueQ. ★ Conditionals: If, Which, Switch, Piecewise, Boole. ★ Loops and flow control: CompoundExpression (;), Do, For, While. ★★ See also tutorial Variables in Pure Functions and Rules, guide Rules & Patterns, and chapters Lists, Function Definitions, Pure Functions in online tutorial The Wolfram Language: Fast Introduction for Programmers.
4. Functional programming, scoping constructs, and function attributes
The basic paradigm of functional programming: applying functions to data and other functions (which are taken as data and can be arguments to other functions). How it compares to procedural programming. A family of mapping functions (revision and generalization): Map (/@), Scan, MapAt, MapIndexed, MapAll (//@), Apply (@@), MapApply (@@@), SubsetMap. A family of “threading” functions (revision and generalization): Thread, MapThread, Threaded, Through, Comap, Operate, Inner, Outer, Distribute, Transpose. A family of iterative functions: Nest, NestList, NestWhile, NestWhileList, Fold, FoldList, FixedPoint, FixedPointList. Some other handy functions: TakeWhile, LengthWhile, Accumulate, Differences, Ratios, FoldPair, FoldPairList, SequenceFold, SequenceFoldList. Composition of functions: Composition (@*), RightComposition (/*), ComposeList. ★ The “sow-reap” pair: Sow, Reap. ★ Localization of variables, scoping constructs Module, Block, With. ★ Setting and clearing attributes and definitions: Attributes, SetAttributes, ClearAttributes, Clear, Unset, ClearAll, Remove, Definition, Information, SyntaxInformation. ★ Function attributes, part 1: Listable, Flat, Orderless, OneIdentity, NumericFunction, Constant, Protected, ReadProtected, Locked, Protect, Unprotect. ★ Termination of calculation: Throw, Catch, Return, Break, Continue, Abort. ★ Development of user functions. ★★ See also guide Functional Programming and tutorial Functional Operations.
5. Review of Lectures 1 through 4
This lecture completes the learning of the general principles of the Wolfram Language through their fusion and revision; henceforth, we will focus primarily on their applications in combination with higher-level functions for both everyday and specialized tasks. We will solve various model problems using programming based on pattern matching and replacement rules, functional programming, but also procedural programming, and compare them in terms of speed, memory requirements, code length, and readability. Students are encouraged to suggest their preferred areas of interest or particular problems that could be solved directly in the lecture or that could be included in subsequent lectures.
6. Symbolic equation solving, calculus, graphics and visualization
Solving equations and inequalities: Solve, SolveValues, Root, Reduce, RootReduce, FindInstance, AsymptoticSolve, Eliminate, SolveAlways, LinearSolve. ★ Differential calculus: D, Dt, Derivative, DifferenceQuotient, Minimize, Maximize, Grad, Div, Curl, Laplacian, Asymptotic, Series, InverseSeries, Limit, FractionalD, Piecewise, PiecewiseExpand. ★ Integral calculus: Integrate, AsymptoticIntegrate, LaplaceTransform, FourierTransform, Convolve, ArcLength, Area, Volume, MomentOfInertia. ★ Ordinary differential equations: DSolve, DSolveValue, AsymptoticDSolveValue, WhenEvent, DEigensystem, DEigenvalues, GreenFunction. ★ Variational methods: package VariationalMethods, EulerEquations, VariationalD. ★ 2D graphics and visualization: Graphics, Point, Line, Polygon, Text, Arrow, Disk, Circle, Rectangle, Raster, Show. 2D charts: Plot, LogPlot, LogLinearPlot, LogLogPlot, ParametricPlot, ContourPlot. ★ 3D graphics and visualization: Graphics3D, Sphere, Cuboid, Cylinder, Cone, Tube. 3D charts: Plot3D, ParametricPlot3D, DensityPlot, SliceContourPlot3D, SliceDensityPlot3D, ComplexPlot3D. ★★ See also guide Equation Solving, Calculus, Mathematical Functions, Matrices and Linear Algebra, Function Visualization.
7. Representation of numbers and computer arithmetic
General prerequisites: Binary, octal and hexadecimal systems, data representation; exact numbers – integers and rationals; simulation of real numbers with imprecise “floating-point” numbers with fixed (relative) precision, their properties and parameters; IEEE arithmetic of FP numbers; numerical computations and their pitfalls and traps.
How Wolfram Language implements numbers: Precise numbers (integers and rationals): EvenQ, OddQ, Prime, PrimePi, NextPrime, PrimeQ, RandomPrime, PrimePower, CoprimeQ, PrimeOmega, PrimeNu, FactorInteger, Divisors, DivisorSigma, DivisorSum, Divisible, IntegerExponent, GCD, LCM, Quotient, Mod, PowerMod, QuotientRemainder, IntegerLength, IntegerDigits, FromDigits, DigitCount, IntegerPartitions, PartitionsP, … ★ Real and complex numbers: N, Round, Floor, Ceiling, IntegerPart, FractionalPart, Chop, Rationalize, RealAbs, I, Re, Im,Conjugate, Abs, Arg, AbsArg, Infinity, ComplexInfinity, DirectedInfinity, Indeterminate, … ★ Arithmetic of real numbers: Precision, Accuracy, “fixed-precision” arithmetic with “machine-precision” numbers vs. “variable-precision” arithmetic with “arbitrary-precision” numbers, MachinePrecision, $MachinePrecision, $MachineEpsilon, $MaxMachineNumber, $MinMachineNumber, $MaxNumber, $MinNumber, SetPrecision, SetAccuracy, … ★ Precision and accuracy related options numerical functions: WorkingPrecision, PrecisionGoal, AccuracyGoal. ★ Formatting numbers: NumberForm, DecimalForm, ScientificForm, EngineeringForm, AccountingForm, PaddedForm, … ★★ See also guide Numerical Evaluation & Precision and tutorials Numerical Operations on Functions, Numbers.
8. Numerical equation solving, calculus, graphics, and visualization
Solving equations and inequalities: NSolve, NSolveValues, NSum, FindRoot, FindMinimum, FindMaximum, NMinimize, NMaximize, Interpolation, InterpolatingFunction, … ★ Differential calculus: DifferenceQuotient, DifferenceDelta, ListConvolve, … ★ Integral calculus: NIntegrate, Fourier, … ★ Ordinary differential equations: NDSolve, NDSolveValue, ParametricNDSolve, NDEigensystem, NDEigenvalues, … ★ Partial differential equations: see PDEModels Overview. ★ Computation monitoring: StepMonitor, EvaluationMonitor, Sow, Reap. ★ 2D graphics and visualization: ArrayPlot, ReliefPlot, MatrixPlot, ListVectorPlot, ListStreamPlot, … 2D charts: ListPlot, ListLogPlot, ListLogLinearPlot, ListLogLogPlot, ListPolarPlot, ListLinePlot, ListStepPlot, ListDensityPlot, ListContourPlot, ListCurvePathPlot, … ★ 3D graphics and visualization: ArrayPlot3D, ListVectorPlot3D, ListStreamPlot3D, ListSliceVectorPlot3D, … 3D charts: ListPlot3D, ListPointPlot3D, ListLinePlot3D, ListDensityPlot3D, ListContourPlot3D, ListSurfacePlot3D, … ★★ See also tutorials Numerical Calculations, Numerical Equation Solving, Numerical Root Finding, Numerical Solution of Differential Equations.
9. Recurrences and computational tricks, function options, attributes, messages, and error handling
Indexed recurrences: f[expr1_]:=f[expr2] (f repeatedly calls itself), expr//.pattern:>value (a rule repeatedly applied), dynamic programming, RSolve, RSolveValue, AsymptoticRSolveValue, RecurrenceTable, FindLinearRecurrence; some explicit functions like Fibonacci, LucasL. Setting $RecursionLimit and $IterationLimit. ★ Non-indexed recurrences: functional equations, iterative procedures, root finding, Fold, FoldList. ★ Tracking using Trace, TracePrint, TraceDialog. ★ Stability of numerical recurrences. ★ Function options: Options, OptionsPattern, SetOptions, OptionValue, FilterRules. ★ Function attributes, part 2: HoldFirst, HoldRest, HoldAll, Unevaluated. ★ Messages and usage statements: On, Off, Quiet, Check, MessageName (::), Message. ★ Error handling using both left- and right-hand side pattern restrictions; how to make functions bulletproof. ★★ See also guide Recurrence and Sum Functions and tutorial Solving Recurrence Equations.
10. External operations, dynamic expressions, WL code optimization, and more distant topics of interest
File and directory operations local and remote, persistent files: see guide File Operations. ★ Import and export: see guide Importing and Exporting. ★ Web: see guide Web Operations. ★ Interaction with external programs: see guide Calling External Programs. ★ Dynamic expressions and interactivity: see tutorials Introduction to Dynamic, Advanced Dynamic Functionality and guide Dynamic Interactivity Language. ★ Optimizing the Wolfram Language code: see guide Parallel Computing, GPU Computing. ★ Application, package and Paclet Development: see guide Package Development, tutorials Contexts and Packages, Setting Up Wolfram Language Packages and Paclets Overview. ★ Geometry: see guide Geometric Computation. ★ Working with strings and text: see guide String Manipulation. ★ Signal processing and analysis: see guide Signal Processing. ★ Image processing and analysis: see guide Image Processing & Analysis. ★ Scientific and medical data and computations: see guide Physics & Chemistry: Data and Computation, Astronomical Computation & Data, Scientific Data Analysis, Units & Quantities. ★★ For a comprehensive overview of the areas covered by the Wolfram Language, see Wolfram Language & System Documentation Center.
11. Review of Lectures 6 through 10
This lecture completes the learning of applications of the Wolfram Language in Physics and related fields of Science. Using all the methods explained during the course, we will discuss and solve a variety of problems. Again, students are encouraged to suggest their preferred areas of interest or particular problems that could be solved directly in the class. Preparation for the defense of the exam project.
Přednášky / Lectures
Standard class times: as per the current schedule.
Lectures do not necessarily follow the topic structure of the content.
The online materials used in the lecture can be found in my Dropbox cloud via a shortened link
in the SyCo directory (alternatively, you can use a direct link to it).
If you do not understand something or need clarification, consultations are available.
In case of extraordinary circumstances, I will provide a link to the organization of online classes.
Cvičení / Exercises
The exercises will be held according to the current schedule with the instructor, immediately following the lecture.
A maximum of 3 unexcused absences per semester (except for students with an approved Individual Study Plan, with whom I will make individual arrangements).
The assignment, preparation, and submission of homework assignments will be as follows:
After each topic is covered in the lecture, you will find the corresponding Assignment<N>.nb notebook, N = 01, 02, … in SyCo/Assignments, which can be downloaded, saved, and opened in Wolfram Mathematica. (The same is true for the Lecture<N>.nb notebooks, which contain the topics explained and practiced in the lectures.)
Once you open it, read and follow the instructions at the top of the file.
Select one of the problems assigned by the instructor and evaluate the appropriate command problem[“<ProblemName>”] . An untitled new Mathematica notebook with the downloaded problem assignment will appear, along with a standard “Save As” dialog box prompting you to save the notebook with a pre-filled name <ProblemName> and path (subdirectory SyCo of the directory containing Assignment<N>. nb ); it is highly recommended to accept the pre-filled name; failure to follow this convention may cause the solution to be rejected. From now on, you will have the file <ProblemName>.nb on your hard disk.
Solve the problem.
When you’re done, go to the “Submit” section at the bottom of the <ProblemName>.nb notebook and read the instructions for submitting your solution (or whatever you want to discuss). The solution will be emailed directly from a Mathematica session using the submit[] command, so please have your CRO identity credentials ready.
Repeat for all problems assigned by the instructor.
Notes:
If the command problem[“<ProblemName>”] is not in an Assignment<N>.nb notebook, e.g. in a <ProblemName>.nb or Lecture<N>.nb notebook, N = 01, 02, …, the “Save As” dialog box prompts you to save the downloaded notebook directly to the directory containing the <ProblemName>.nb or the Lecture<N>.nb notebook, etc., not to the SyCo subdirectory, to avoid stacking the SyCo subdirectories. This can be overridden by editing the path that is filled in by default in the “Save As” dialog.
The reason the action of the problem[“<ProblemName>”] command avoids saving the file directly is for safety: you don’t want to overwrite a solution in progress if you accidentally run this command again.
When you initialize an Assignment<N>.nb notebook for the first time, the SyCo extensions consisting of the SyCo.wl package (defining the problem[“<ProblemName>”] and submit[] commands) and the SyCo_Style.nb stylesheet (which defines the visual appearance of all SyCo related notebooks) are downloaded and installed in your personal Wolfram System extensions location (subdirectories of the $UserBaseDirectory). Once installed, they will no longer be downloaded and reinstalled (unless you delete them yourself, of course); during all subsequent sessions and initializations, these files will only be loaded. The initialization code is in the grayed-out cell at the very end of each Assignment<N>.nb notebook.
Softwarové vybavení / Software equipment
All participants who do not have their own license or are not equipped with a license from another institution will receive a legal university license for Wolfram Mathematica for the duration of the course, at least until the exam is completed (allocation and installation will be arranged after registration and before the first lecture).
Hodnocení a zkoušení / Evaluation and testing
Throughout the semester, the student will complete 10 homework assignments on topics related to the topic just discussed. Each homework assignment will be worth a maximum of 1 point; this makes a maximum of 10 points for homework assignments. I will gradually publish the assignments on the above mentioned cloud in the SyCo/Assignments directory. The handling of the homework exercises will be covered in the first exercise.
By the end of October (or thereabouts), the student will receive an assignment of the exam project to be solved using the discussed methods in the Wolfram Mathematica system. The exam consists of a project defense (max. 10 points). The resulting grade will be given according to a 20-point grading scale.
Materials for some topics can be found on the above cloud in the SyCo/Projects directory. A selection of topics for term projects (you can propose your own topic after consultation with the teacher):
1. Epidemiologic models based on ODEs (compartmental models): see cloud; additional information and materials will be provided by the instructor.
2. Exploring different forms of the Pursuit Curve and Dog Curve: Wolfram MathWorld, Mathcurve, Mathematical Association of America, Cornell Univ Math Dept., Gotohaggstrom, National Curve Bank, and others.
3. Kepler’s problem for an orbiter with a variable mass (movement of a comet ejecting or accumulating mass, jets on a planet, etc.): information and materials will be provided by the instructor.
4. Magnus effect (aerodynamic effect of the rotation of a ball on its trajectory – tennis, table tennis, soccer, etc.) or aerodynamic force action on a rotating cylinder (helicopter, Flettner rotor): information and materials will be provided by the instructor.
5. Permanent magnet falling through a conductive loop (electromagnetic induction braking illustration): Information and materials will be provided by the instructor.
6. Study the transients of turning on and off an incandescent light bulb (or why a light bulb usually “goes out” when turned on): See cloud; additional information and materials will be provided by the instructor.
7. An application of a general asymmetric 1D Savitzky–Golay convolution filter that avoids the problem of edge effects: Information and materials will be provided by the instructor.
8. The finite numeric interval {a, b} is to be sampled with n samples (i.e., n equidistant values are to be distributed in it), so that the sequence of samples generated in this way is immediately (after mapping some function onto it) prepared as input for the system Fourier and InverseFourier functions (we want to have the first sample implicitly at t = 0). Write a function circularlySample[{a, b}, n] that handles this in all directions.
9. Study the motion of a charged particle in the Earth’s gravitomagnetic field. Information and materials will be provided by the instructor.
10. Design and implement a method based on the ChebyshevT polynomials to compute a time derivative of an unevenly sampled time series. Information and materials will be provided by the instructor.
See Wolfram & Mathematica – Site Licenses, Section References & Resources
Odkazy a zdroje / Links and resources
Books, manuals, and online resources can be found in the Literature section above and on the Wolfram Language and Mathematica page; they will not be duplicated here.
Fans of the Big Bang Theory know that Leonard refers to 73 as the “Chuck Norris of Numbers” after Sheldon points out that : 73 is the 21st prime, and it’s mirror image 37 is the 12th prime. This enigma is the only known such combination. In binary 73 is a palindrome 1001001: see Chuck Norris of Numbers is the 73. Sheldon failed to mention that 73 is also the 37th odd number: see Pat's Blog, Tuesday, 14 March 2023.
Q: How can I be sure that the SyCo package and stylesheet are free of malware?
A: The best way to check them is to read their source code. It can be displayed directly in the notebook with
Import["https://is.slu.cz/www/hle0002/vyuka/syco/resources/SyCo.wl", "Text"]
and
Import["https://is.slu.cz/www/hle0002/vyuka/syco/resources/SyCo_Style.nb", "Text"]
Alternatively, both the package and stylesheet files can be copied to a non-system location within the home directory, such as $WolframDocumentsDirectory,
With[{p = "SyCo", x = {".wl", "_Style.nb"}},
MapThread[CopyFile, {
URL["https://is.slu.cz/www/hle0002/vyuka/syco/resources/" <> p <> #] & /@ x,
FileNameJoin[{$WolframDocumentsDirectory, p}] <> # & /@ x
}
]]
and then opened in Mathematica.