From 733fe8c290269495834ee519c680eb7b0f3977c1 Mon Sep 17 00:00:00 2001 From: Meik Hellmund Date: Thu, 5 Mar 2026 20:09:16 +0100 Subject: [PATCH] english improved --- AGENTS.md | 193 +++++++++---------------- Manifest.toml | 76 +++++----- _quarto.yml | 1 + chapters/10_Strings.qmd | 104 +++++++------- chapters/11_LinAlg.qmd | 57 ++++---- chapters/13_IO.qmd | 193 ++++++++++++------------- chapters/14_Plot.qmd | 99 +++++++------ chapters/5_TricksHelp.qmd | 58 ++++---- chapters/6_ArraysEtcP1.qmd | 152 ++++++++++---------- chapters/7_ArraysP2.qmd | 209 +++++++++++++++------------- chapters/9_functs.qmd | 113 ++++++++------- chapters/Erste_Bsp.qmd | 34 ++--- chapters/Pi2.qmd | 32 +++-- chapters/entwicklungsumgebungen.qmd | 50 +++---- chapters/first_contact.qmd | 57 ++++---- chapters/numerictypes.qmd | 127 +++++++++-------- chapters/pcomplex.qmd | 115 ++++++++------- chapters/syntax.qmd | 89 ++++++------ chapters/types.qmd | 193 +++++++++++++------------ index.qmd | 38 ++--- opencode.json | 6 +- 21 files changed, 954 insertions(+), 1042 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2760fa4..319d644 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,23 +1,51 @@ -# AGENTS.md - Guidelines for Agentic Coding in JuliaKurs23 +# AGENTS.md - Guidelines for JuliaKurs23 -This is a **Quarto-based Julia programming course book** in English. The book teaches scientific computing with Julia using interactive Jupyter notebooks rendered with Quarto. +This is a **Quarto-based Julia programming course book**. The book teaches scientific computing with Julia using interactive Jupyter notebooks rendered with Quarto. -**Translation Note:** The book was originally written in German and has been translated to professional, concise English suitable for mathematicians. All code, LaTeX equations, and formatting have been preserved during translation. Only text descriptions and code comments were translated to English. +**Translation Note:** The book was originally written in German and translated to English. The English needs improvement—focus on making the prose professional, concise, and suitable for mathematicians. ## Project Overview -- **Type**: Educational book website/PDF generated from Quarto (.qmd) files +- **Type**: Educational book (HTML website + PDF) generated from Quarto (.qmd) files - **Language**: English (all content) - **Build System**: Quarto with Julia Jupyter kernel - **Julia Version**: 1.10 -- **Output**: HTML website and PDF - **License**: CC BY-NC-SA 4.0 --- -## Build Commands +## Current Task: English Translation Improvement -### Build the Book +The English text in this book was translated from German and needs refinement for quality. + +### Workflow (one change at a time) + +For each chapter file in `chapters/`: + +1. I read the file and identify English improvements +2. I present ONE improvement at a time showing: + - The current text + - The proposed improvement + - Explanation of why the change is needed +3. You reply **yes** or **no** +4. If yes, I apply the change; if no, I skip it +5. Repeat until all improvements for that file are done +6. Move to the next chapter file + +### What to improve: +- English prose, grammar, word choice +- Clarity and flow for mathematical audience +- Professional tone suitable for mathematicians/scientists + +### What NOT to change: +- Julia code +- LaTeX equations +- Markdown formatting +- Quarto cell options (`#| eval:`, etc.) + +--- + +## Build Commands ```bash # Build HTML website @@ -31,17 +59,10 @@ quarto render --to julia-color-pdf # Preview locally quarto preview -``` -### Development Commands - -```bash # Render a specific chapter quarto render chapters/first_contact.qmd -# Build with specific output directory -quarto render --output-dir _book - # Run in daemon mode (faster rebuilds) quarto render --execute-daemon 3600 ``` @@ -49,135 +70,55 @@ quarto render --execute-daemon 3600 ### Deployment ```bash -# Deploy to web server (rsync _book/) ./deploy.sh ``` -### Testing Individual Code Blocks - -Quarto executes Julia code in Jupyter notebooks. To test individual code blocks: - -1. Open the `.qmd` file in VS Code with Julia extension -2. Use Julia REPL to execute code blocks interactively -3. Or use IJulia/Jupyter to run specific cells - -```julia -# In Julia REPL, test code from a cell: -include("path/to/notebook.jl") -``` - -### Julia Package Management - -```bash -# Install dependencies (from Project.toml) -julia -e 'using Pkg; Pkg.instantiate()' - -# Add a new package -julia -e 'using Pkg; Pkg.add("PackageName")' -``` - --- ## Code Style Guidelines -### General Structure (.qmd files) +### Quarto Structure (.qmd files) -- All `.qmd` files start with YAML front matter specifying `engine: julia` -- Code blocks use triple backticks with `julia` language identifier -- Use Quarto cell options in comments like `#| option: value` -- Common options: `eval:`, `echo:`, `output:`, `error:`, `hide_line:` - -Example: -```markdown ---- -engine: julia ---- - -```{julia} -#| eval: true -#| echo: true -#| output: true -using Statistics -mean([1, 2, 3]) -``` -``` +- All `.qmd` files start with YAML front matter: `engine: julia` +- Code blocks use triple backticks with `julia` identifier +- Cell options in comments: `#| option: value` ### Julia Code Conventions -#### Imports - +**Imports:** ```julia -# Prefer using for packages with many exports -using Statistics, LinearAlgebra, Plots - -# Use import when you need specific exports or module name -import Base: convert, show +using Statistics, LinearAlgebra, Plots # many exports +import Base: convert, show # specific exports ``` -#### Naming Conventions +**Naming:** +- Variables/functions: lowercase with underscores (`my_variable`) +- Types: CamelCase (`MyType`, `AbstractMatrix`) +- Constants: ALL_UPPERCASE (`MAX_ITER`) +- Modules: PascalCase (`Statistics`) -- **Variables/functions**: lowercase with underscores (`my_variable`, `calculate_mean`) -- **Types**: CamelCase (`MyType`, `AbstractMatrix`) -- **Constants**: ALL_UPPERCASE (`MAX_ITER`, `PI`) -- **Modules**: PascalCase (`Statistics`, `LinearAlgebra`) +**Formatting:** +- 4 spaces indentation +- ~92 character line limit +- Spaces around operators: `a + b` +- No spaces before commas: `f(a, b)` -#### Formatting - -- Use 4 spaces for indentation (Julia default) -- Limit lines to ~92 characters when practical -- Use spaces around operators: `a + b`, not `a+b` -- No spaces before commas: `f(a, b)`, not `f(a , b)` - -#### Types - -- Use explicit types when needed for performance or clarity -- Parameterize types when useful: `Vector{Float64}`, `Dict{Symbol, Int}` -- Prefer concrete types for fields in structs - -#### Error Handling +**Types:** +- Explicit types for performance/clarity +- Parameterize: `Vector{Float64}`, `Dict{Symbol, Int}` +- Concrete types for struct fields +**Error Handling:** ```julia -# Use try-catch for expected errors try parse(Int, user_input) catch e println("Invalid input: $e") end -# Use assertions for internal checks @assert x >= 0 "x must be non-negative" ``` -### Quarto-Specific Guidelines - -#### Cell Options - -Use these in code block comments: -- `#| eval: true/false` - whether to execute -- `#| echo: true/false` - show source code -- `#| output: true/false` - show output -- `#| error: true/false` - show errors -- `#| hide_line: true` - hide this line from output -- `#| fig-cap: "Caption"` - figure caption - -#### Embedding Notebooks - -```markdown -{{< embed notebooks/nb-types.ipynb#nb1 >}} -``` - -#### Conditional Content - -```markdown -::: {.content-visible when-format="html"} -... HTML only content -::: - -::: {.content-visible when-format="pdf"} -... PDF only content -::: -``` - --- ## File Organization @@ -197,20 +138,10 @@ Use these in code block comments: --- -## VS Code Settings - -The project uses VS Code with: -- Julia environment: `/home/hellmund/Julia/23` - - LTEx for spell checking (disabled for code blocks) -- Auto-exclude: `.ipynb`, `.md`, `.quarto_ipynb` files - ---- - ## Important Notes -1. **All content is in English** - Comments, documentation, variable names in examples should be English (professional, concise, suitable for mathematicians) -2. **Code comments were translated** - German text and code comments were translated to English; all Julia code, LaTeX equations, and Quarto formatting were preserved -3. **Code execution is cached** - Use `#| eval: true` to execute cells -4. **ansi color codes** - The `julia-color` extension handles ANSI escape sequences in output -5. **Freeze mode** - Set to `auto` in _quarto.yml; use `freeze: false` to re-run all code -6. **Keep intermediate files** - `keep-ipynb`, `keep-tex`, `keep-md` are all true +1. **All content is in English** — professional, concise, suitable for mathematicians +2. **Code, LaTeX, formatting preserved** — only improve English prose +3. **Code execution cached** — use `#| eval: true` to execute cells +4. **Freeze mode** — set to `auto` in _quarto.yml; use `freeze: false` to re-run all code +5. **Keep intermediates** — `keep-ipynb`, `keep-tex`, `keep-md` are all true diff --git a/Manifest.toml b/Manifest.toml index 4958940..4107e4d 100644 --- a/Manifest.toml +++ b/Manifest.toml @@ -22,9 +22,9 @@ version = "0.4.5" [[deps.Adapt]] deps = ["LinearAlgebra", "Requires"] -git-tree-sha1 = "7e35fca2bdfba44d797c53dfe63a51fabf39bfc0" +git-tree-sha1 = "35ea197a51ce46fcd01c4a44befce0578a1aaeca" uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" -version = "4.4.0" +version = "4.5.0" weakdeps = ["SparseArrays", "StaticArrays"] [deps.Adapt.extensions] @@ -165,9 +165,9 @@ version = "1.1.1" [[deps.CairoMakie]] deps = ["CRC32c", "Cairo", "Cairo_jll", "Colors", "FileIO", "FreeType", "GeometryBasics", "LinearAlgebra", "Makie", "PrecompileTools"] -git-tree-sha1 = "5017d6849aff775febd36049f7d926a5fb6677ec" +git-tree-sha1 = "fa072933899aae6dc61dde934febed8254e66c6a" uuid = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0" -version = "0.15.8" +version = "0.15.9" [[deps.Cairo_jll]] deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"] @@ -286,9 +286,9 @@ version = "1.3.0+1" [[deps.ComputePipeline]] deps = ["Observables", "Preferences"] -git-tree-sha1 = "76dab592fa553e378f9dd8adea16fe2591aa3daa" +git-tree-sha1 = "3b4be73db165146d8a88e47924f464e55ab053cd" uuid = "95dc2771-c249-4cd0-9c9f-1f3b4330693c" -version = "0.1.6" +version = "0.1.7" [[deps.ConcurrentUtilities]] deps = ["Serialization", "Sockets"] @@ -423,9 +423,9 @@ uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5" version = "2.2.4+0" [[deps.EnumX]] -git-tree-sha1 = "7bebc8aad6ee6217c78c5ddcf7ed289d65d0263e" +git-tree-sha1 = "c49898e8438c828577f04b92fc9368c388ac783c" uuid = "4e289a0a-7415-4d19-859d-a7e5c4648b56" -version = "1.0.6" +version = "1.0.7" [[deps.EpollShim_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl"] @@ -603,9 +603,9 @@ version = "3.4.1+0" [[deps.GR]] deps = ["Artifacts", "Base64", "DelimitedFiles", "Downloads", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Preferences", "Printf", "Qt6Wayland_jll", "Random", "Serialization", "Sockets", "TOML", "Tar", "Test", "p7zip_jll"] -git-tree-sha1 = "ee0585b62671ce88e48d3409733230b401c9775c" +git-tree-sha1 = "44716a1a667cb867ee0e9ec8edc31c3e4aa5afdc" uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71" -version = "0.73.22" +version = "0.73.24" [deps.GR.extensions] IJuliaExt = "IJulia" @@ -615,9 +615,9 @@ version = "0.73.22" [[deps.GR_jll]] deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "FreeType2_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Qt6Base_jll", "Zlib_jll", "libpng_jll"] -git-tree-sha1 = "7dd7173f7129a1b6f84e0f03e0890cd1189b0659" +git-tree-sha1 = "be8a1b8065959e24fdc1b51402f39f3b6f0f6653" uuid = "d2c73de3-f751-5644-a686-071e5b155ba9" -version = "0.73.22+0" +version = "0.73.24+0" [[deps.GeometryBasics]] deps = ["EarCut_jll", "Extents", "IterTools", "LinearAlgebra", "PrecompileTools", "Random", "StaticArrays"] @@ -669,9 +669,9 @@ version = "1.3.15+0" [[deps.Graphs]] deps = ["ArnoldiMethod", "DataStructures", "Inflate", "LinearAlgebra", "Random", "SimpleTraits", "SparseArrays", "Statistics"] -git-tree-sha1 = "031d63d09bd3e6e319df66bb466f5c3e8d147bee" +git-tree-sha1 = "7eb45fe833a5b7c51cf6d89c5a841d5967e44be3" uuid = "86223c79-3864-5bf0-83f7-82e725a168b6" -version = "1.13.4" +version = "1.14.0" weakdeps = ["Distributed", "SharedArrays"] [deps.Graphs.extensions] @@ -1101,9 +1101,9 @@ version = "0.5.16" [[deps.Makie]] deps = ["Animations", "Base64", "CRC32c", "ColorBrewer", "ColorSchemes", "ColorTypes", "Colors", "ComputePipeline", "Contour", "Dates", "DelaunayTriangulation", "Distributions", "DocStringExtensions", "Downloads", "FFMPEG_jll", "FileIO", "FilePaths", "FixedPointNumbers", "Format", "FreeType", "FreeTypeAbstraction", "GeometryBasics", "GridLayoutBase", "ImageBase", "ImageIO", "InteractiveUtils", "Interpolations", "IntervalSets", "InverseFunctions", "Isoband", "KernelDensity", "LaTeXStrings", "LinearAlgebra", "MacroTools", "Markdown", "MathTeXEngine", "Observables", "OffsetArrays", "PNGFiles", "Packing", "Pkg", "PlotUtils", "PolygonOps", "PrecompileTools", "Printf", "REPL", "Random", "RelocatableFolders", "Scratch", "ShaderAbstractions", "Showoff", "SignedDistanceFields", "SparseArrays", "Statistics", "StatsBase", "StatsFuns", "StructArrays", "TriplotBase", "UnicodeFun", "Unitful"] -git-tree-sha1 = "d1b974f376c24dad02c873e951c5cd4e351cd7c2" +git-tree-sha1 = "68af66ec16af8b152309310251ecb4fbfe39869f" uuid = "ee78f7c6-11fb-53f2-987a-cfe4a2b5a57a" -version = "0.24.8" +version = "0.24.9" [deps.Makie.extensions] MakieDynamicQuantitiesExt = "DynamicQuantities" @@ -1129,9 +1129,9 @@ version = "0.6.7" [[deps.MbedTLS]] deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "NetworkOptions", "Random", "Sockets"] -git-tree-sha1 = "c067a280ddc25f196b5e7df3877c6b226d390aaf" +git-tree-sha1 = "8785729fa736197687541f7053f6d8ab7fc44f92" uuid = "739be429-bea8-5141-9913-cc70e7f3736d" -version = "1.1.9" +version = "1.1.10" [[deps.MbedTLS_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl"] @@ -1496,9 +1496,9 @@ version = "1.3.3" [[deps.Preferences]] deps = ["TOML"] -git-tree-sha1 = "522f093a29b31a93e34eaea17ba055d850edea28" +git-tree-sha1 = "8b770b60760d4451834fe79dd483e318eee709c4" uuid = "21216c6a-2e73-6563-6e65-726566657250" -version = "1.5.1" +version = "1.5.2" [[deps.PrettyTables]] deps = ["Crayons", "LaTeXStrings", "Markdown", "PrecompileTools", "Printf", "REPL", "Reexport", "StringManipulation", "Tables"] @@ -1535,9 +1535,9 @@ uuid = "92933f4c-e287-5a05-a399-4b506db050ca" version = "1.11.0" [[deps.PtrArrays]] -git-tree-sha1 = "1d36ef11a9aaf1e8b74dacc6a731dd1de8fd493d" +git-tree-sha1 = "4fbbafbc6251b883f4d2705356f3641f3652a7fe" uuid = "43287f4e-b6f4-7ad1-bb20-aadabca52c3d" -version = "1.3.0" +version = "1.4.0" [[deps.QOI]] deps = ["ColorTypes", "FileIO", "FixedPointNumbers"] @@ -1547,27 +1547,33 @@ version = "1.0.2" [[deps.Qt6Base_jll]] deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Vulkan_Loader_jll", "Xorg_libSM_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_cursor_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "libinput_jll", "xkbcommon_jll"] -git-tree-sha1 = "34f7e5d2861083ec7596af8b8c092531facf2192" +git-tree-sha1 = "d7a4bff94f42208ce3cf6bc8e4e7d1d663e7ee8b" uuid = "c0090381-4147-56d7-9ebc-da0b1113ec56" -version = "6.8.2+2" +version = "6.10.2+1" [[deps.Qt6Declarative_jll]] -deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll", "Qt6ShaderTools_jll"] -git-tree-sha1 = "da7adf145cce0d44e892626e647f9dcbe9cb3e10" +deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll", "Qt6ShaderTools_jll", "Qt6Svg_jll"] +git-tree-sha1 = "d5b7dd0e226774cbd87e2790e34def09245c7eab" uuid = "629bc702-f1f5-5709-abd5-49b8460ea067" -version = "6.8.2+1" +version = "6.10.2+1" [[deps.Qt6ShaderTools_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll"] -git-tree-sha1 = "9eca9fc3fe515d619ce004c83c31ffd3f85c7ccf" +git-tree-sha1 = "4d85eedf69d875982c46643f6b4f66919d7e157b" uuid = "ce943373-25bb-56aa-8eca-768745ed7b5a" -version = "6.8.2+1" +version = "6.10.2+1" + +[[deps.Qt6Svg_jll]] +deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll"] +git-tree-sha1 = "81587ff5ff25a4e1115ce191e36285ede0334c9d" +uuid = "6de9746b-f93d-5813-b365-ba18ad4a9cf3" +version = "6.10.2+0" [[deps.Qt6Wayland_jll]] deps = ["Artifacts", "JLLWrappers", "Libdl", "Qt6Base_jll", "Qt6Declarative_jll"] -git-tree-sha1 = "8f528b0851b5b7025032818eb5abbeb8a736f853" +git-tree-sha1 = "672c938b4b4e3e0169a07a5f227029d4905456f2" uuid = "e99dba38-086e-5de3-a5b1-6e4c66e897c3" -version = "6.8.2+2" +version = "6.10.2+1" [[deps.QuadGK]] deps = ["DataStructures", "LinearAlgebra"] @@ -1824,9 +1830,9 @@ version = "0.15.8" [[deps.StringManipulation]] deps = ["PrecompileTools"] -git-tree-sha1 = "a3c1536470bf8c5e02096ad4853606d7c8f62721" +git-tree-sha1 = "d05693d339e37d6ab134c5ab53c29fce5ee5d7d5" uuid = "892a3eda-7b42-436c-8928-eab12a02cf0e" -version = "0.4.2" +version = "0.4.4" [[deps.StructArrays]] deps = ["ConstructionBase", "DataAPI", "Tables"] @@ -1909,9 +1915,9 @@ version = "1.11.0" [[deps.TiffImages]] deps = ["ColorTypes", "DataStructures", "DocStringExtensions", "FileIO", "FixedPointNumbers", "IndirectArrays", "Inflate", "Mmap", "OffsetArrays", "PkgVersion", "PrecompileTools", "ProgressMeter", "SIMD", "UUIDs"] -git-tree-sha1 = "98b9352a24cb6a2066f9ababcc6802de9aed8ad8" +git-tree-sha1 = "08c10bc34f4e7743f530793d0985bf3c254e193d" uuid = "731e570b-9d59-4bfa-96dc-6df516fadf69" -version = "0.11.6" +version = "0.11.8" [[deps.TikzGraphs]] deps = ["Graphs", "LaTeXStrings", "TikzPictures"] diff --git a/_quarto.yml b/_quarto.yml index d87205c..084adaa 100644 --- a/_quarto.yml +++ b/_quarto.yml @@ -108,6 +108,7 @@ format: julia-color-typst: papersize: a4 toc: true + toc-depth: 2 number-depth: 2 fig-cap-location: bottom fig-pos: H diff --git a/chapters/10_Strings.qmd b/chapters/10_Strings.qmd index f6acd1e..85664c6 100644 --- a/chapters/10_Strings.qmd +++ b/chapters/10_Strings.qmd @@ -17,11 +17,11 @@ Base.stdout = QuartoNotebookWorker.with_context(stdout) There were - depending on manufacturer, country, programming language, operating system, etc. - a large variety of encodings. -Still relevant today: +Still relevant today are: ### ASCII -The _American Standard Code for Information Interchange_ was published as a standard in the USA in 1963. +The American Standard Code for Information Interchange (ASCII) was published as a standard in the USA in 1963. - It defines $2^7=128$ characters, namely: - 33 control characters, such as `newline`, `escape`, `end of transmission/file`, `delete` @@ -40,7 +40,7 @@ The _American Standard Code for Information Interchange_ was published as a stan ### ISO 8859 Character Sets - ASCII uses only 7 bits. -- In a byte, one can fit another 128 characters by setting the 8th bit. +- In a byte, you can fit another 128 characters by setting the 8th bit. - In 1987/88, various 1-byte encodings were standardized in ISO 8859, all ASCII-compatible, including: :::{.narrow} @@ -61,11 +61,11 @@ The _American Standard Code for Information Interchange_ was published as a stan ## Unicode -The goal of the Unicode Consortium is a uniform encoding for all scripts of the world. +The goal of the Unicode Consortium is a uniform encoding for all scripts worldwide. - Unicode version 1 was published in 1991 -- Unicode version 15.1 was published in 2023 with 149,813 characters, including: - - 161 scripts +- Unicode version 17 was published in 2025 with 159,801 characters, including: + - 172 scripts - mathematical and technical symbols - Emojis and other symbols, control and formatting characters - Over 90,000 characters are assigned to the CJK scripts (Chinese/Japanese/Korean) @@ -73,21 +73,19 @@ The goal of the Unicode Consortium is a uniform encoding for all scripts of the ### Technical Details -- Each character is assigned a `codepoint`. This is simply a sequential number. -- This number is written hexadecimally - - either 4-digit as `U+XXXX` (0th plane) - - or 6-digit as `U+XXXXXX` (further planes) -- Each plane ranges from `U+XY0000` to `U+XYFFFF`, thus can contain $2^{16}=65\;534$ characters. -- 17 planes `XY=00` to `XY=10` are provided so far, thus the value range from `U+0000` to `U+10FFFF`. +- Each character is assigned a `codepoint`, which is simply a sequential number written hexadecimally + - either with 4 digit as `U+XXXX` (zeroth plane) + - or with 6 digit as `U+XXXXXX` (further planes) +- Each plane ranges from `U+XY0000` to `U+XYFFFF`, thus containing $2^{16}=65\;534$ characters. +- 17 planes `XY=00` to `XY=10` are provided, giving a value range from `U+0000` to `U+10FFFF`. - Thus, a maximum of 21 bits per character are needed. - The total number of possible codepoints is slightly less than 0x10FFFF, as certain areas are not used for technical reasons. It is about 1.1 million, so there is still much room. -- So far, codepoints from the planes have been assigned only from - - Plane 0 = BMP _Basic Multilingual Plane_ `U+0000 - U+FFFF`, - - Plane 1 = SMP _Supplementary Multilingual Plane_ `U+010000 - U+01FFFF`, - - Plane 2 = SIP _Supplementary Ideographic Plane_ `U+020000 - U+02FFFF`, - - Plane 3 = TIP _Tertiary Ideographic Plane_ `U+030000 - U+03FFFF` and - - Plane 14 = SSP _Supplementary Special-purpose Plane_ `U+0E0000 - U+0EFFFF` - have been assigned. +- So far, codepoints have been assigned only from these planes: + - Plane 0 = BMP (Basic Multilingual Plane) `U+0000 - U+FFFF`, + - Plane 1 = SMP (Supplementary Multilingual Plane) `U+010000 - U+01FFFF`, + - Plane 2 = SIP (Supplementary Ideographic Plane) `U+020000 - U+02FFFF`, + - Plane 3 = TIP (Tertiary Ideographic Plane) `U+030000 - U+03FFFF`, and + - Plane 14 = SSP (Supplementary Special-purpose Plane) `U+0E0000 - U+0EFFFF`. - `U+0000` to `U+007F` is identical to ASCII - `U+0000` to `U+00FF` is identical to ISO 8859-1 (Latin-1) @@ -101,7 +99,7 @@ In the standard, each character is described by - script direction - category: uppercase letter, lowercase letter, modifier letter, digit, punctuation, symbol, separator,.... -In the Unicode standard, this looks like this (simplified, only codepoint and name): +In the Unicode standard, this looks like (simplified, only codepoint and name): ``` ... U+0041 LATIN CAPITAL LETTER A @@ -144,8 +142,9 @@ Alternatively, you can use the PDF version of this page. There, all fonts are em A small helper function: ```{julia} function printuc(c, n) - for i in 0:n-1 - print(c + i) + for i in 1:n + print(c + i -1) + if i%70 == 0 print("\n") end end end ``` @@ -205,8 +204,8 @@ printuc('\U16a0', 40) __Phaistos Disc__ - This script is not deciphered. -- It is unclear what language is represented. -- There is only one single document in this script: the Phaistos Disc from the Bronze Age +- It is unclear what language it represents. +- There is only one single document in this script: the Phaistos Disc from the Bronze Age. ```{julia} @@ -231,7 +230,7 @@ printuc('\U101D0', 46 ) _Unicode transformation formats_ define how a sequence of codepoints is represented as a sequence of bytes. -Since the codepoints are of different lengths, they cannot simply be written down one after the other. Where does one end and the next begin? +Since codepoints are of different lengths, they cannot simply be written down one after the other. Where does one end and the next begin? - __UTF-32__: The simplest but also most memory-intensive is to make them all the same length. Each codepoint is encoded in 4 bytes = 32 bits. - In __UTF-16__, a codepoint is represented either with 2 bytes or with 4 bytes. @@ -243,14 +242,14 @@ Since the codepoints are of different lengths, they cannot simply be written dow - For each codepoint, 1, 2, 3, or 4 full bytes are used. -- With variable-length encoding, one must be able to recognize which byte sequences belong together: +- With variable-length encoding, you must be able to recognize which byte sequences belong together: - A byte of the form 0xxxxxxx represents an ASCII codepoint of length 1. - A byte of the form 110xxxxx starts a 2-byte code. - A byte of the form 1110xxxx starts a 3-byte code. - A byte of the form 11110xxx starts a 4-byte code. - All further bytes of a 2-, 3-, or 4-byte code have the form 10xxxxxx. -- Thus, the space available for the codepoint (number of x): +- Thus, the space available for the codepoint (number of x) is: - One-byte code: 7 bits - Two-byte code: 5 + 6 = 11 bits - Three-byte code: 4 + 6 + 6 = 16 bits @@ -258,24 +257,22 @@ Since the codepoints are of different lengths, they cannot simply be written dow - Thus, every ASCII text is automatically also a correctly encoded UTF-8 text. -- If the 17 planes (= 21 bits = 1.1 million possible characters) defined for Unicode so far are ever expanded, UTF-8 will be expanded to 5- and 6-byte codes. +- If the 17 planes (equivalent to 21 bits, resulting in approximately 1.1 million possible characters) currently defined in Unicode are ever depleted, UTF-8 can be extended to include 5- and 6-byte code sequences. +## Characters and Strings in Julia -## Characters and Character Strings in Julia - -### Characters: `Char` +### Characters The `Char` type encodes a single Unicode character. -- Julia uses single quotes for this: `'a'`. +- Julia uses single quotes for characters: `'a'`. - A `Char` occupies 4 bytes of memory and - represents a Unicode codepoint. - `Char`s can be converted to/from `UInt`s and - the integer value is equal to the Unicode codepoint. -`Char`s can be converted to/from `UInt`s. - +`Char`s can be converted to/from `UInt`s: ```{julia} UInt('a') ``` @@ -285,10 +282,10 @@ UInt('a') b = Char(0x2656) ``` -### Character Strings: `String` +### Strings -- For strings, Julia uses double quotes: `"a"`. -- They are UTF-8 encoded, i.e., one character can be between 1 and 4 bytes long. +- In Julia, strings are denoted with double quotes: `"a"`. +- These strings are encoded in UTF-8, where a single character may consist of 1 to 4 bytes. ```{julia} @@ -305,7 +302,6 @@ __For a non-ASCII string, the number of bytes and the number of characters diffe asciistr = "Hello World!" @show length(asciistr) ncodeunits(asciistr); ``` -(The space, of course, also counts.) ```{julia} str = "😄 Hellö 🎶" @@ -323,7 +319,7 @@ end ### Concatenation of Strings -"Strings with concatenation form a non-commutative monoid." +Strings with concatenation form a non-commutative monoid. Therefore, Julia writes concatenation multiplicatively. ```{julia} @@ -338,9 +334,7 @@ str^3, str^0 ### String Interpolation -The dollar sign has a special function in strings, which we have often used in -`print()` statements. One can interpolate a variable or expression with it: - +The dollar sign serves a special purpose in strings, frequently utilized within `print()` statements. It enables the interpolation of variables or expressions. ```{julia} a = 33.4 @@ -351,8 +345,8 @@ s = "The result for $b is equal to $a and the doubled square root of it is $(2sq ### Backslash Escape Sequences -The _backslash_ `\` also has a special function in string constants. -Julia uses the backslash codings known from C and other languages for special characters and for dollar signs and backslashes themselves: +The backslash `\` also has a special function in string constants. +Julia uses the backslash codings known from C and other languages for special characters, dollar signs, and backslashes themselves: ```{julia} @@ -364,9 +358,7 @@ print(s) ### Triple Quotes -Strings can also be delimited with triple quotes. -In this form, line breaks and quotes are preserved: - +Strings may also be enclosed in triple quotes, preserving line breaks and embedded quotes: ```{julia} s = """ @@ -380,8 +372,7 @@ print(s) ### Raw Strings -In a `raw string`, all backslash codings except `\"` are disabled: - +In a `raw string`, all backslash escape sequences except for `\"` are disabled: ```{julia} s = raw"A $ and a \ and two \\ and a 'bla'..." @@ -400,7 +391,7 @@ print(s) ### Application to Strings -These tests can e.g. be used with `all()`, `any()`, or `count()` on strings: +These tests can be used on strings with `all()`, `any()`, or `count()`: ```{julia} @@ -449,11 +440,10 @@ replace("π is irrational.", "is" => "is allegedly") ## Indexing of Strings -Strings are immutable but indexable. There are a few special features here. +Strings are immutable but indexable, with a few special features: - The index numbers the bytes of the string. -- For a non-ASCII string, not all indices are valid, because -- a valid index always addresses a Unicode character. +- For a non-ASCII string, not all indices are valid because a valid index always addresses a Unicode character. Our example string: ```{julia} @@ -476,7 +466,7 @@ Only the 5th byte is a new character: str[5] ``` -Even when addressing substrings, start and end must always be valid indices, i.e., the end index must also index the first byte of a character, and that character is the last of the substring. +Even when addressing substrings, start and end must always be valid indices; i.e., the end index must also index the first byte of a character, and that character is the last of the substring. ```{julia} str[1:7] @@ -504,8 +494,8 @@ The function `nextind()` returns the next valid index. Why does Julia use a byte index instead of a character index? The main reason is the efficiency of indexing. -- In a long string, e.g., a book text, the position `s[123455]` can be found quickly with a byte index. -- A character index would have to traverse the entire string in UTF-8 encoding to find the n-th character, since the characters can be 1, 2, 3, or 4 bytes long. +- In a long string (e.g., book text), the position `s[123455]` can be found quickly with a byte index. +- A character index would have to traverse the entire string in UTF-8 encoding to find the n-th character, since characters can be 1, 2, 3, or 4 bytes long. Some functions return indices or ranges as results. They always return valid indices: @@ -530,7 +520,7 @@ str2 = "αβγδϵ"^3 n = findfirst('γ', str2) ``` -So one can continue searching from the next valid index after `n=5`: +So you can continue searching from the next valid index after `n=5`: ```{julia} findnext('γ', str2, nextind(str2, n)) diff --git a/chapters/11_LinAlg.qmd b/chapters/11_LinAlg.qmd index d7a9943..2b77c6e 100644 --- a/chapters/11_LinAlg.qmd +++ b/chapters/11_LinAlg.qmd @@ -15,9 +15,9 @@ using InteractiveUtils using LinearAlgebra ``` -The `LinearAlgebra` package provides among other things: +The `LinearAlgebra` package provides, among other things: -- additional subtypes of `AbstractMatrix`: usable like other matrices, e.g., +- additional subtypes of `AbstractMatrix` which are usable like other matrices, among them: - `Tridiagonal` - `SymTridiagonal` @@ -44,7 +44,7 @@ The `LinearAlgebra` package provides among other things: - Access to BLAS/LAPACK functions -## Matrix Types +## Special Matrix Types @@ -68,20 +68,20 @@ Read-only index access is possible, A[1,4] ``` -write operations not necessarily: +Write operations are not necessarily possible: ```{julia} #| error: true A[1,3] = 17 ``` -Conversion to a 'normal' matrix is possible, for example, with `collect()`: +Conversion to a 'normal' matrix is possible using `collect()`: ```{julia} A2 = collect(A) ``` ### The Identity Matrix `I` -`I` denotes an identity matrix (square, diagonal elements = 1, all others = 0) of the respective required size +`I` denotes an identity matrix (square, diagonal elements = 1, all others = 0) of the required size ```{julia} @@ -91,7 +91,7 @@ A + 4I ## Norms -To be able to study questions such as conditioning or convergence of an algorithm, we need a metric. For linear spaces, it is appropriate to define the metric via a norm: +To study questions such as conditioning or convergence of an algorithm, we need a metric. For linear spaces, it is appropriate to define the metric via a norm: $$ d(x,y) := \lVert x-y\rVert $$ @@ -109,12 +109,12 @@ which generalize the Euclidean norm $p=2$. ## The Max-Norm $p=\infty$ -Let $x_{\text{max}}$ be the _largest in absolute value_ component of $\mathbf{x}\in ℝ^n$. Then always +Let $x_{\text{max}}$ be the component of $\mathbf{x}\in ℝ^n$ with the largest absolute value. Then always $$ \lvert x_{\text{max}}\rvert \le \lVert\mathbf{x}\rVert_p \le n^\frac{1}{p} \lvert x_{\text{max}}\rvert $$ (Consider a vector whose components are all equal to $x_{\text{max}}$ respectively a vector whose components are all equal to zero except $x_{\text{max}}$.) -Thus follows +It follows that $$ \lim_{p \rightarrow \infty} \lVert\mathbf{x}\rVert_p = \lvert x_{\text{max}}\rvert =: \lVert\mathbf{x}\rVert_\infty. $$ @@ -132,7 +132,7 @@ w = [-1, 2, 33.2] - If the 2nd argument `p` is missing, `p=2` is set. - The 2nd argument can also be `Inf` (i.e., $+\infty$). -- The 1st argument can be any container full of numbers. The sum $\sum \lvert x_i\rvert^p$ extends over *all* elements of the container. +- The 1st argument can be any numerical container. The sum $\sum \lvert x_i\rvert^p$ extends over *all* elements of the container. - Thus, for a matrix `norm(A)` is equal to the _Frobenius norm_ of the matrix `A`. ```{julia} @@ -163,9 +163,9 @@ for p ∈ (0.8, 1, 1.5, 2, 3.001, 1000) end fig1 ``` -As one can see, $p\ge 1$ must hold so that the unit ball is convex and $\lVert.\rVert_p$ is a norm. +We see that, $p\ge 1$ must hold so that the unit ball is convex and $\lVert.\rVert_p$ is a norm. -However, the Julia function `norm(v, p)` returns a result for arbitrary parameters `p`. +However, the Julia function `norm(v, p)` also works for parameters `p<1`. ### Induced Norms (Operator Norms) @@ -185,7 +185,7 @@ $$ $$ ::: -Induced norms can only be calculated with difficulty for general $p$. Exceptions are the cases +Induced norms are difficult to calculate for general $p$. Exceptions are the cases - $p=1$: column sum norm - $p=2$: spectral norm and @@ -260,7 +260,7 @@ $$ ## Matrix Factorizations -Basic tasks of numerical linear algebra: +The basic tasks of numerical linear algebra: - Solve a system of linear equations $A\mathbf{x} = \mathbf{b}$. - If no solution exists, find the best approximation, i.e., the vector $\mathbf{x}$ that minimizes $\lVert A\mathbf{x} - \mathbf{b}\rVert$. @@ -270,12 +270,11 @@ These tasks can be solved using matrix factorizations. Some fundamental matrix f - **LU decomposition** $A=L\cdot U$ - factorizes a matrix as a product of a _lower_ and an _upper_ triangular matrix - - in German also called LR decomposition (but the Julia function is called `lu()`) - always works (possibly after row exchanges - pivoting) - **Cholesky decomposition** $A=L\cdot L^*$ - the upper triangular matrix is the conjugate of the lower, - half the effort compared to LU - - only works if $A$ is Hermitian and positive definite + - only works if $A$ is Hermitian and positive definite - **QR decomposition** $A=Q\cdot R$ - decomposes $A$ as a product of an orthogonal (or unitary in the complex case) matrix and an upper triangular matrix - $Q$ is length-preserving (rotations and/or reflections); the scalings are described by $R$ @@ -287,8 +286,7 @@ These tasks can be solved using matrix factorizations. Some fundamental matrix f ### LU Factorization -LU factorization is Gaussian elimination. The result of Gaussian elimination is the upper triangular matrix $U$. The lower triangular matrix $L$ contains ones on the diagonal and the non-diagonal entries $l_{ij}$ are equal to minus the coefficients by which row $Z_j$ is multiplied and added to row $Z_i$ in the Gaussian algorithm. -An example: +LU factorization is Gaussian elimination. The result of Gaussian elimination is the upper triangular matrix $U$. The lower triangular matrix $L$ contains ones on the diagonal and the non-diagonal entries $l_{ij}$ are equal to minus the coefficients by which row $Z_j$ is multiplied and added to row $Z_i$ in Gaussian elimination: :::{.content-visible unless-format="typst"} $$ @@ -394,9 +392,9 @@ $ ::: -- Often in practice: $A\mathbf{x}=\mathbf{b}$ must be solved for one $A$ and many right-hand sides $\mathbf{b}$. -- The factorization, whose effort grows cubically $\sim n^3$ with the matrix size $n$, only needs to be done once. -- The subsequent effort of forward/backward substitution for each $\mathbf{b}$ is only quadratically $\sim n^2$. +- In practice, it is often necessary to solve $A\mathbf{x}=\mathbf{b}$ for a fixed matrix $A$ and multiple right-hand sides $\mathbf{b}$. +- The factorization of $A$, which has a cubic complexity $\sim n^3$ relative to the size $n$ of the matrix, needs to be performed only once. +- For each subsequent right-hand side $\mathbf{b}$, the forward and backward substitution steps have quadratic complexity $\sim n^2$. The `LinearAlgebra` package of Julia contains the function `lu(A, options)` for calculating an LU decomposition: ```{julia} @@ -447,9 +445,9 @@ $ ``` ::: -The goal is to make the entry $a_{i+1,j}$ disappear by adding an appropriate multiple of row $Z_i$ to row $Z_{i+1}$. This only works if the _pivot element_ ${\color{red}a_{ij}}$ is not zero. If ${\color{red}a_{ij}}=0$, we must exchange rows to fix this. +The goal is to make the entry $a_{i+1,j}$ disappear by adding an appropriate multiple of row $Z_i$ to row $Z_{i+1}$. This only works if the *pivot element* ${\color{red}a_{ij}}$ is not zero. If ${\color{red}a_{ij}}=0$, we must exchange rows to fix this. -Furthermore, the conditioning of the algorithm is best if we arrange the matrix at each step so that the pivot element is the largest in absolute value in the corresponding column of the remaining submatrix. In (row) pivoting, rows are exchanged at each step to ensure that +Furthermore, the conditioning of the algorithm is best if we arrange the matrix at each step so that the pivot element is the largest in absolute value in the corresponding column of the remaining submatrix. In (row) pivoting, rows are exchanged to ensure that :::{.content-visible unless-format="typst"} $$ @@ -485,7 +483,8 @@ L, U, p = lu(A); p ``` -The permutation vector indicates how the rows of the matrix have been permuted. It holds: $$ L\cdot U = PA$$. The syntax of indirect indexing allows applying the row permutation with the notation `A[p,:]`: +The permutation vector indicates how the rows of the matrix have been permuted. It holds: $$ L\cdot U = P A$$ + Julia's syntax of indirect indexing allows applying the row permutation with the notation `A[p,:]`: ```{julia} display(A) display(A[p,:]) @@ -503,18 +502,17 @@ Verification: A * x - b ``` -In Julia, the `\` operator hides a quite universal "matrix solver", and it can also be applied directly: +In Julia, the `\` operator hides a quite universal "matrix solver" which perfoms implicitely an appropriate matrix factorization: ```{julia} A \ b ``` -An appropriate factorization is performed implicitly, but its result is not saved. ### QR Decomposition The function `qr()` returns a special QR object that contains the components $Q$ and $R$. The orthogonal (or unitary) matrix $Q$ is -[in an optimized form](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#man-linalg-abstractq) stored. Conversion to a "normal" matrix is, as always, possible with `collect()` if needed. +[in an optimized form](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#man-linalg-abstractq). Conversion to a "normal" matrix is, as always, possible with `collect()` if needed. ```{julia} F = qr(A) @show typeof(F) typeof(F.Q) @@ -525,10 +523,7 @@ display(F.R) ### Appropriate Factorization -The function `factorize()` returns a factorization form adapted to the matrix type, see [documentation](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.factorize) for details. -If solutions for several right-hand sides $\mathbf{b_1}, \mathbf{b_2},...$ are needed, the factorization should only be performed once: - - +The function `factorize()` returns a factorization appropriate for the given matrix type; see [documentation](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.factorize) for details. This factorization can subsequently be utilized for multiple right-hand sides $\mathbf{b_1}, \mathbf{b_2},\ldots$. ```{julia} Af = factorize(A) ``` diff --git a/chapters/13_IO.qmd b/chapters/13_IO.qmd index c7dfd83..164afca 100644 --- a/chapters/13_IO.qmd +++ b/chapters/13_IO.qmd @@ -40,28 +40,27 @@ Base.active_module() = myactive_module() ## Console -The operating system normally provides 3 channels (_streams_) for a program: +The operating system typically provides three channels (_streams_) for a program: -- Standard input channel `stdin` -- Standard output channel `stdout` and -- Standard error output channel `stderr`. +- Standard input (`stdin`) +- Standard output (`stdout`) +- Standard error (`stderr`) -When the program is started in a terminal (or console or shell), the program can read keyboard input via `stdin` and output appears in the terminal via `stdout` and `stdout`. +When executed in a terminal, console, or shell, the program reads keyboard input through `stdin` and outputs to the terminal via `stdout` and `stderr`. -- Writing to `stdout`: `print()`,`println()`,`printstyled()` -- Writing to `stderr`: `print(strerr,...)`, `println(stderr,...)`, `printstyled(stderr,...)` +- Writing to `stdout`: `print()`, `println()`, `printstyled()` +- Writing to `stderr`: `print(stderr,...)`, `println(stderr,...)`, `printstyled(stderr,...)` - Reading from `stdin`: `readline()` ### Input -The language _Python_ provides a function `input()`: +The _Python_ language provides an `input()` function: ```{.python} ans = input("Please enter a positive number!") ``` -The function prints the prompt, waits for input, and returns the -input as a `string`. +It prints the prompt, waits for input, and returns a `string`. In Julia, you can implement this function as follows: @@ -76,12 +75,12 @@ end **Comments** -- Write instructions are buffered by modern operating systems. With `flush(stdout)`, the buffer is emptied and the write operation is forced to complete immediately. -- `readline()` returns a string ending with a newline `\n`. The function `chomp()` removes a possible line break from the end of a string. +- Write operations are buffered by modern operating systems. `flush(stdout)` empties the buffer and forces the write operation to complete immediately. +- `readline()` returns a string ending with a newline (`\n`). The function `chomp()` removes a trailing line break from the string. ```{julia} #| eval: false -a = input("Please enter 2 numbers!") +a = input("Please enter two numbers!") ``` ```{julia} #| echo: false @@ -91,7 +90,7 @@ a = "34 56" ### Processing the Input -> `split(str)` splits a string into "words" and returns an _(array of strings)_: +> `split(str)` splits a string into "words", returning a string array: ```{julia} av = split(a) @@ -105,46 +104,33 @@ av = split(a) v = parse.(Int, av) ``` -`parse()` generates an error if the string cannot be parsed as a value of type `T`. You can catch the error with -`try/catch` or use the function `tryparse(T, str)`, which returns `nothing` in such a case - on which you can then -e.g. test with `isnothing()`. - - - - -### Reading Individual Keystrokes - -- `readline()` and similar functions wait for the input to be completed by pressing the `Enter` key. -- Techniques for reading individual _keystrokes_ can be found here: - - - [https://stackoverflow.com/questions/56888266/how-to-read-keyboard-inputs-at-every-keystroke-in-julia](https://stackoverflow.com/questions/56888266/how-to-read-keyboard-inputs-at-every-keystroke-in-julia) - - [https://stackoverflow.com/questions/60954235/how-can-i-test-whether-stdin-has-input-available-in-julia](https://stackoverflow.com/questions/60954235/how-can-i-test-whether-stdin-has-input-available-in-julia) - +`parse()` throws an error if the string cannot be parsed as type `T`. You can catch the error with +`try/catch`, or use `tryparse(T, str)`, which returns `nothing` in such cases. Test the result with `isnothing()`. ## Formatted Output with the `Printf` Macro -Often you want to output numbers or strings with a strict format specification - total length, decimal places, right/left-aligned, etc. +You often need to output numbers or strings with strict formatting: total length, decimal places, alignment, etc. -To this end, the `Printf` package defines the macros `@sprintf` and `@printf`, which work very similarly to the corresponding C functions. +For this purpose, the `Printf` package defines the macros `@sprintf` and `@printf`, which work similarly to the corresponding C functions. ```{julia} using Printf x = 123.7876355638734 -@printf("Output right-aligned with max. 10 character width and 3 decimal places: x= %10.3f", x) +@printf("Output right-aligned with max. 10 character width and 3 decimal places: x = %10.3f", x) ``` -The first argument is a string containing placeholders (here: `%10.3`) for variables to be output; followed by these variables as further arguments. +The first argument is a string containing placeholders (here: `%10.3f`) for the variables, followed by the variables themselves. -Placeholders have the form +Placeholders have the form: ``` -%[flags][width][.precision]type + %[flags][width][.precision]type ``` -where the entries in square brackets are all optional. +where entries in square brackets are optional. **Type specifications in placeholders** @@ -152,11 +138,11 @@ where the entries in square brackets are all optional. |:--|:------------| |`%s`| `string`| |`%i`| `integer`| -|`%o`| `integer octal (base=8)`| -|`%x, %X`| `integer hexadecimal (base=16) with digits 0-9abcdef or 0-9ABCDEF, resp.`| -|`%f`| `floating point number`| -|`%e`| `floating point number, scientific representation`| -|`%g`| `floating point, uses %f or %e depending on value`| +|`%o`| `integer, octal (base 8)`| +|`%x, %X`| `integer, hexadecimal (base 16), digits 0-9a-f or 0-9A-F`| +|`%f`| `floating point`| +|`%e`| `floating point, scientific notation`| +|`%g`| `floating point, %f or %e as appropriate`| : {.striped .hover} @@ -165,9 +151,9 @@ where the entries in square brackets are all optional. | | | |:----|:-----| -|Plus sign| right-aligned (default)| -|Minus sign| left-aligned| -|Zero| with leading zeros| +|Plus sign| right-aligned (default) | +|Minus sign| left-aligned | +|Zero| adds leading zeros | : {.striped .hover} @@ -175,26 +161,26 @@ where the entries in square brackets are all optional. **Width** ``` -Number of minimum characters used (more will be taken if necessary) +Minimum number of characters used (more will be taken if necessary) ``` -### Examples: +### Examples ```{julia} -using Printf # Don't forget to load the package! +using Printf # Load the package first ``` ```{julia} @printf("|%s|", "Hello") # string with placeholder for string ``` -The vertical bars are not part of the placeholder. They are intended to indicate the boundaries of the output field. +The vertical bars are not part of the placeholder; they indicate the output field boundaries. ```{julia} -@printf("|%10s|", "Hello") # Minimum length, right-aligned +@printf("|%10s|", "Hello") # Minimum length, right-aligned ``` @@ -204,8 +190,8 @@ The vertical bars are not part of the placeholder. They are intended to indicate ```{julia} -@printf("|%3s|", "Hello") # Length specification can be exceeded - # Better a 'badly formatted' table than incorrect values! +@printf("|%3s|", "Hello") # Length specification can be exceeded + # Better a badly formatted table than wrong values! ``` @@ -214,36 +200,34 @@ j = 123 k = 90019001 l = 3342678 -@printf("j= %012i, k= %-12i, l = %12i", j, k, l) # 0-flag for leading zeros +@printf("j = %012i, k = %-12i, l = %12i", j, k, l) # 0-flag for leading zeros ``` -`@printf` and `@sprintf` can be called like functions or as macros: +`@printf` and `@sprintf` can be called like functions: ```{julia} @printf("%i %i", 22, j) ``` --- or as macros, i.e., without function parentheses and without comma: +or as macros, i.e., without parentheses or commas: ```{julia} @printf "%i %i" 22 j ``` -`@printf` can take a stream as its first argument. - -Otherwise, the argument list consists of +`@printf` can take a stream as its first argument; otherwise, the argument list consists of: - format string with placeholders -- variables in the order of the placeholders, matching in number and type to the placeholders +- variables matching the placeholders in number and type ```{julia} @printf(stderr, "First result: %i %s\nSecond result %i", - j, "(estimated)" ,k) + j, "(estimated)", k) ``` -The macro `@sprintf` does not print anything but returns the filled formatted string: +The macro `@sprintf` does not print; it returns the formatted string: ```{julia} @@ -255,12 +239,12 @@ str = @sprintf("x = %10.6f", π ); str ``` -### Formatting Floating Point Numbers: +### Formatting Floating-Point Numbers -Meaning of the _precision_ value: +The _precision_ value specifies: -- `%f` and `%e` format: maximum number of decimal places -- `%g` format: maximum number of digits output (integer + decimal places) +- `%f` and `%e` formats: maximum decimal places +- `%g` format: maximum total digits (integer part + decimal places) ```{julia} @@ -276,34 +260,33 @@ x = 123456.7890123456 ```{julia} -@printf("%20.7g %20.4g", x, x) # total 7 and 4 digits respectively +@printf("%20.7g %20.4g", x, x) # 7 and 4 digits total, respectively ``` ## File Operations -Files are +Files are handled by: - - opened $\Longrightarrow$ a new _stream_-object is created (in addition to `stdin, stdout, stderr`) - - then this _stream_ can be read from and written to - - closed $\Longrightarrow$ _stream_-object is detached from file - - ```{.julia} - stream = open(path, mode) - ``` +- Opening $\Longrightarrow$ creation of a new _stream_ object (in addition to `stdin`, `stdout`, `stderr`) +- Reading from and writing to this _stream_ +- Closing $\Longrightarrow$ detachment of the _stream_ object from the file + +``` +stream = open(path, mode) +``` - - path: filename/path - - mode: - - ``` - "r" read, opens at file beginning - "w" write, opens at file beginning (file is created or overwritten) - "a" append, opens to continue writing at file end - ``` +- path: filename or path +- mode: + ``` + "r" read, opens at file beginning + "w" write, opens at file beginning (file is created or overwritten) + "a" append, opens to continue writing at file end + ``` Let's write a file: ```{julia} -file = open("datei.txt", "w") +file = open("myfile.txt", "w") ``` @@ -324,18 +307,18 @@ close(file) Let's look at the file: ```{julia} -;cat datei.txt +;cat myfile.txt ``` ...and now we open it again for reading: ```{julia} -stream = open("datei.txt", "r") +stream = open("myfile.txt", "r") ``` -`readlines(stream)` returns all lines of a text file as a vector of strings. +`readlines(stream)` returns all lines of a text file as a string vector. -`eachline(stream)` returns an iterator over the lines of the file. +`eachline(stream)` returns an iterator over the file lines. ```{julia} @@ -349,30 +332,30 @@ close(stream) ## Packages for File Formats -For input and output in various file formats, there are Julia packages, e.g., +Julia packages for various file formats include: -- [PrettyTables.jl](https://ronisbr.github.io/PrettyTables.jl/stable/) Output of formatted tables -- [DelimitedFiles.jl](https://docs.julialang.org/en/v1/stdlib/DelimitedFiles/) Input and output of matrices, etc. -- [CSV.jl](https://csv.juliadata.org/stable/) Input and output of "comma-separated values" files, etc. -- [XLSX.jl](https://felipenoris.github.io/XLSX.jl/stable/tutorial/) Input and output of Excel files +- [PrettyTables.jl](https://ronisbr.github.io/PrettyTables.jl/stable/) Output formatted tables +- [DelimitedFiles.jl](https://docs.julialang.org/en/v1/stdlib/DelimitedFiles/) Read and write matrices +- [CSV.jl](https://csv.juliadata.org/stable/) Read and write CSV files +- [XLSX.jl](https://felipenoris.github.io/XLSX.jl/stable/tutorial/) Read and write Excel files and many more... ### DelimitedFiles.jl -This package enables convenient saving/reading of matrices. It provides the functions `writedlm()` and `readdlm()`. +This package offers convenient functions for saving and reading matrices using `writedlm()` and `readdlm()`. ```{julia} using DelimitedFiles ``` -We generate a 200×3 matrix of random numbers +Generate a 200×3 matrix of random numbers: ```{julia} A = rand(200,3) ``` -and save it +and save it: ```{julia} f = open("data2.txt", "w") writedlm(f, A) @@ -387,33 +370,30 @@ The written file starts like this: ``` -Reading it back is even simpler: +Reading it back is simple: ```{julia} B = readdlm("data2.txt") ``` -One more point: In Julia, the `do` notation is often used for file handling, see @sec-do. -This uses the fact that `open()` also has methods where the 1st argument is a `function(iostream)`. -This function is then applied to the _stream_ and the stream is automatically closed at the end. The `do` notation allows you to -define this function anonymously after the `do`: + +In Julia, the `do` notation is frequently utilized for file handling (see @sec-do). The `open()` function includes methods where the first argument is a `function(iostream)`. This function is applied to the stream, which is automatically closed afterward. The `do` notation allows to define this function anonymously: ```{julia} -open("data2.txt", "w") do io writedlm(io, A) end ``` ### CSV and DataFrames -- The CSV format is often used to provide tables in a form that can be read not only by MS Excel. -- An example is the weather and climate database _Meteostat_. -- The [DataFrames.jl](https://dataframes.juliadata.org/stable/) package provides functions for convenient handling of tabular data. +- The CSV format provides tables readable by MS Excel and other applications. +- Example: the weather and climate database _Meteostat_. +- The [DataFrames.jl](https://dataframes.juliadata.org/stable/) package handles tabular data conveniently. ```{julia} using CSV, DataFrames, Downloads -# Weather data from Westerland, see https://dev.meteostat.net/bulk/hourly.html +# Weather data from Westerland (see https://dev.meteostat.net/bulk/hourly.html) url = "https://bulk.meteostat.net/v2/hourly/10018.csv.gz" http_response = Downloads.download(url) @@ -452,8 +432,7 @@ describe(df) -For convenient plotting and handling of date and time formats in the weather table, -we load two helper packages: +For convenient plotting and date/time handling, we load two packages: ```{julia} using StatsPlots, Dates @@ -480,7 +459,7 @@ df[!, :datetime] = DateTime.(df.Column1) .+ Hour.(df.Column2); @df df plot(:datetime, :Column3) ``` -And now to the plot: +The resulting plot: ```{julia} @df df plot(:datetime, [:Column9, :Column6, :Column3], diff --git a/chapters/14_Plot.qmd b/chapters/14_Plot.qmd index eb7ffd6..a92b749 100644 --- a/chapters/14_Plot.qmd +++ b/chapters/14_Plot.qmd @@ -12,25 +12,25 @@ using InteractiveUtils # Plots and Data Visualization in Julia: _Plots.jl_ -There are numerous graphics packages for Julia. Two frequently used ones are [Makie.jl](https://docs.makie.org/stable/) and -[Plots.jl](https://docs.juliaplots.org/latest/). Before presenting these in more detail, some other packages are listed. +Julia has numerous graphics packages. Two frequently used ones are [Makie.jl](https://docs.makie.org/stable/) and +[Plots.jl](https://docs.juliaplots.org/latest/). Before presenting `Plots.jl` in detail, we list some others. ## Brief Overview: Some Graphics Packages | Package/Documentation | Tutorial | Examples | Remarks | |:----|:--|:--|:--------| -|[Plots.jl](https://docs.juliaplots.org/latest/) | [Tutorial](https://docs.juliaplots.org/latest/tutorial/) | [Gallery](https://goropikari.github.io/PlotsGallery.jl/) | designed as a unified interface to various _backends_ (graphics libraries) | +|[Plots.jl](https://docs.juliaplots.org/latest/) | [Tutorial](https://docs.juliaplots.org/latest/tutorial/) | [Gallery](https://docs.juliaplots.org/latest/gallery/gr/) | designed as a unified interface to various _backends_ (graphics libraries) | | [Makie.jl](https://docs.makie.org/stable/) | [Basic tutorial](https://docs.makie.org/v0.21/tutorials/basic-tutorial) | [Beautiful Makie](https://beautiful.makie.org/) | "data visualization ecosystem for Julia", backends: Cairo (vector graphics), OpenGL, WebGL | |[PlotlyJS.jl](http://juliaplots.org/PlotlyJS.jl/stable/) | [Getting started](https://plotly.com/julia/getting-started/)| [Examples](https://plotly.com/julia/plotly-fundamentals/)| Interface to the [Plotly](https://plotly.com/graphing-libraries/) JavaScript graphics library | | [Gadfly.jl](https://gadflyjl.org/stable/)| [Tutorial](https://gadflyjl.org/stable/tutorial/) | [Gallery](https://github.com/GiovineItalia/Gadfly.jl?tab=readme-ov-file#gallery)| "a plotting and data visualization system written in Julia, influenced by R's [ggplot2](https://ggplot2.tidyverse.org/)" | | [Bokeh.jl](https://cjdoris.github.io/Bokeh.jl/stable/) | | [Gallery](https://cjdoris.github.io/Bokeh.jl/stable/gallery/)| Julia frontend for [Bokeh](https://bokeh.org/) | |[VegaLite.jl](https://www.queryverse.org/VegaLite.jl/stable/) | [Tutorial](https://www.queryverse.org/VegaLite.jl/stable/gettingstarted/tutorial/)| [Examples](https://www.queryverse.org/VegaLite.jl/stable/examples/examples_barcharts/)| Julia frontend for [Vega-Lite](https://vega.github.io/vega-lite/)| -| [Luxor.jl](http://juliagraphics.github.io/Luxor.jl/stable/) |[Tutorial](https://juliagraphics.github.io/Luxor.jl/stable/tutorial/helloworld/)|[Examples](https://juliagraphics.github.io/Luxor.jl/stable/example/moreexamples/)| General vector graphics/illustrations | +| [Luxor.jl](https://juliagraphics.github.io/LuxorManual/stable/) |[Tutorial](https://juliagraphics.github.io/LuxorManual/stable/tutorial/helloworld/)|[Examples](https://juliagraphics.github.io/LuxorManual/stable/example/moreexamples/)| General vector graphics/illustrations | | [Javis.jl](https://juliaanimators.github.io/Javis.jl/stable/) |[Tutorials](https://juliaanimators.github.io/Javis.jl/stable/tutorials/)| [Examples](https://juliaanimators.github.io/Javis.jl/stable/examples/)| *Animated* vector graphics | [TidierPlots.jl](https://github.com/TidierOrg/TidierPlots.jl)| [Reference](https://tidierorg.github.io/TidierPlots.jl/latest/) || "is a 100% Julia implementation of the R package ggplot2 powered by Makie.jl"| |[PythonPlot.jl](https://github.com/JuliaPy/PythonPlot.jl)| |[Examples (in Python)](https://matplotlib.org/stable/gallery/index.html)| Interface to Matplotlib (Python), 1:1 transfer of the Python API, therefore see [Matplotlib documentation](https://matplotlib.org/stable/api/pyplot_summary.html) -{: .striped .hover} +: {.striped .hover}