diff --git a/ATTRIBUTIONS.md b/ATTRIBUTIONS.md index 3dd6ec1..906e70b 100644 --- a/ATTRIBUTIONS.md +++ b/ATTRIBUTIONS.md @@ -143,6 +143,14 @@ Vendored WordPerfect-family test files. Per-file provenance (upstream path, revi - **Embedded fonts:** a PDF carries subsetted glyph outlines of whatever fonts the renderer reached for, so the fixtures under `diagrams/pdf/` do redistribute font data. Each family was checked against the OS/2 `fsType` bit of the system font it came from, which is where a font states its own embedding terms: Helvetica and Liberation Sans report 0 (installable, no restriction), Times New Roman and Trebuchet MS report 8 (editable embedding). All four permit it. `scripts/build_diagram_pdfs.py` holds that allowlist and fails a build that reaches for anything outside it. That check is why `graphviz_cjk` ships as SVG only: macOS's Songti reports `fsType` 2, restricted, which forbids embedding without the owner's permission, so no CJK PDF is published until an open-licensed CJK face is available to render one. - **Modifications:** every fixture whose producer states its own graph also ships as a `*_geometry.svg` variant with that metadata removed by `scripts/strip_svg_graph_metadata.py` — Graphviz writes the node ids and the full edge list into `` elements and again into XML comments; Mermaid into `id="L_start_auth_0"`, again into `data-id`, and the edge's waypoints into `data-points`; PlantUML into `id="Read config-to-Open input"`, again into a comment, again into a `data-entity-1`/`data-entity-2` pair, and once more into a `<?plantuml-src?>` processing instruction carrying its whole deflated source; and LibreOffice by tagging each group with its shape kind, which across a whole file is the node/edge partition. A fixture that names its own answer cannot measure geometry recovery. Stripping removes no geometry: each variant renders to a byte-identical PNG. `nested_transforms.svg`, `icon_nodes.svg`, `mixed_page.svg`, `two_diagrams.svg` and the three `negative_*.svg` files are hand-written. Ground truth is the source graph restated by node label, so it is independent of any recogniser's numbering. +## xberg math corpus + +- **Citation:** assembled for xberg from published documents that carry mathematics, one per notation and container the extractor supports. +- **Source:** 123 upstream projects and publishers. Each document's source URL is in `MATH_PROVENANCE.md`. +- **License:** per document. 136 are vendored under permissive terms, chiefly MIT (36), CC-BY-4.0 (25), Apache-2.0 (21), US public domain (13), BSD-3-Clause (12) and MPL-2.0 (5). Four state a dual `CC-BY OR GPL-3.0-or-later` licence and are taken under the CC-BY arm. 12 carry ShareAlike, GPL or GFDL terms and are reference only, recorded without their bytes. +- **Used here:** 136 documents vendored, 12 reference. +- **Modifications:** none. Each document is byte-identical to what its publisher serves, so a fixture measures the real file rather than a rewritten one. No ground truth is derived from them here. + ## PubMed Central open access - **Citation:** Europe PMC RESTful Web Service, Europe PMC Consortium. diff --git a/LICENSES.md b/LICENSES.md index 7103004..4fa346a 100644 --- a/LICENSES.md +++ b/LICENSES.md @@ -44,7 +44,10 @@ non-commercial benchmark use non-commercial data. | [ds4sd/DocLayNet](https://huggingface.co/datasets/ds4sd/DocLayNet-v1.1) | CDLA-Permissive-1.0 | vendor | | [google-research-datasets/hiertext](https://github.com/google-research-datasets/hiertext) | CC-BY-SA-4.0 | reference (ShareAlike — not committed) | +Vendored sources: 7. Reference-only sources: 2. WordPerfect corpus provenance: `wordperfect/PROVENANCE.md`. Math corpus provenance, per document: `MATH_PROVENANCE.md`. | regression corpus: [PubMed Central OA](https://europepmc.org), [Project Gutenberg](https://www.gutenberg.org), [govdocs1](https://digitalcorpora.org), [arXiv](https://arxiv.org) | CC-BY-4.0 / CC0 / US-PD, per document | vendor (1,816) | | regression corpus, restricted subset | CC-BY-SA, CC-BY-NC*, arXiv nonexclusive-distrib | reference (1,459, not committed) | +| math corpus (136 documents, ~70 upstream projects) | MIT / Apache-2.0 / CC-BY / CC0 / US-PD / MPL-2.0 | vendor | +| math corpus, copyleft subset (12 documents) | CC-BY-SA / GPL / GFDL | reference (not committed) | Vendored sources: 7. Reference-only sources: 2. WordPerfect corpus provenance: `wordperfect/PROVENANCE.md`. diff --git a/MATH_PROVENANCE.md b/MATH_PROVENANCE.md new file mode 100644 index 0000000..8519b45 --- /dev/null +++ b/MATH_PROVENANCE.md @@ -0,0 +1,184 @@ +# Math corpus provenance + +Documents that carry mathematics, added to exercise formula extraction across every format that can hold it. Each one was fetched from the source below, and its licence read from the source repository, the document itself, or the publisher's stated terms. + +## No ground truth, and why + +These documents ship without `ground_truth/` files. + +The corpus takes ground truth from upstream and normalizes it, then gates each document against an independent oracle. These documents bring none: they are raw published files. Deriving it by running the extractor over them would record today's output as the definition of correct, so a later regression would match the golden file and pass. The corpus is better served by an honest gap than by a golden file that cannot fail. + +There is one seam worth noting for later. Four of the documents carry 1,046 LaTeX strings written by their own authors, in MathML `annotation-tex`: + +| document | annotations | +|---|---| +| `html/math/mathematics_mathml_pandoc_b65cef.html` | 577 | +| `html/math/2212_09410_f9ff0c.html` | 339 | +| `html/math/2608_12173v1_cf6425.html` | 117 | +| `html/math/2608_11028v2_419bae.html` | 13 | + +That is real formula-level ground truth, independent of any extractor. `README.md` places targets of that kind in `ground_truth/structured/`, which the repository does not yet contain, so this change does not invent the format. The material is here when that directory arrives. + +## Committed + +| path | source | licence | notation | +|---|---|---|---| +| `epub/math/IS4E_fbdd3c.epub` | [Introductory Statistics for Economics](https://bookdown.org/bkrauth/IS4E/IS4E.epub) | MIT | MathML (Presentation) with embedded LaTeX anno | +| `epub/math/cnt_mathml_support_a20d9b.epub` | [W3C EPUB 3 test suite](https://w3c.github.io/epub-tests/tests/cnt-mathml-support.epub) | W3C Software and Document License | MathML (Presentation) | +| `epub/math/quadratic_functions_4ebefc.epub` | [Connexions / OpenStax CNX collection col11284 "Quadr](https://archive.org/download/cnx-org-col11284/quadratic-functions.epub) | CC-BY-3.0 | MathML (Presentation, wrapped in <semantics>) | +| `epub/math/statistical_learning_theory_d50966.epub` | [Connexions / OpenStax CNX collection col10532 "Stati](https://archive.org/download/cnx-org-col10532/statistical-learning-theory.epub) | CC-BY-2.0 | MathML (Presentation, wrapped in <semantics>) | +| `html/math/2212_09410_f9ff0c.html` | [ar5iv](https://ar5iv.labs.arxiv.org/html/2212.09410) | CC-BY-4.0 | MathML + TeX in the alttext attribute | +| `html/math/2608_11028v2_419bae.html` | [arXiv native HTML](https://arxiv.org/html/2608.11028v2) | CC-BY-4.0 | MathML + TeX in the alttext attribute | +| `html/math/2608_12173v1_cf6425.html` | [arXiv native HTML](https://arxiv.org/html/2608.12173v1) | CC-BY-4.0 | MathML + TeX in the alttext attribute | +| `html/math/index_6de724.html` | [Stanford CS236 "Deep Generative Models" course notes](https://raw.githubusercontent.com/deepgenerativemodels/notes/master/docs/vae/index.html) | MIT | <script type="math/tex"> / "math/tex; mode=dis | +| `html/math/math_8h_079059.html` | [Motion Primitive Library C++ API documentation](https://raw.githubusercontent.com/sikang/motion_primitive_library/master/docs/math_8h.html) | Apache-2.0 | LaTeX carried only in the alt attribute of a P | +| `html/math/math_d0ba73.html` | [PySurvival documentation, "Mathematics" page](https://raw.githubusercontent.com/square/pysurvival/master/docs/math.html) | Apache-2.0 | <script type="math/tex"> and <script type="mat | +| `html/math/math_experiments_mathml_ttm_3b80f9.html` | [Docutils functional-test expected output](https://raw.githubusercontent.com/docutils/docutils/master/docutils/test/functional/expected/math_experiments_mathml_ttm.html) | Public domain | native MathML | +| `html/math/math_output_html_378195.html` | [Docutils functional-test expected output](https://raw.githubusercontent.com/docutils/docutils/master/docutils/test/functional/expected/math_output_html.html) | Public domain | HTML/CSS math (no MathML, no TeX) — worst-case | +| `html/math/math_output_mathjax_f0d3c2.html` | [Docutils functional-test expected output](https://raw.githubusercontent.com/docutils/docutils/master/docutils/test/functional/expected/math_output_mathjax.html) | Public domain | raw LaTeX carried in span/div class="math" for | +| `html/math/math_output_mathml_64e3ae.html` | [Docutils functional-test expected output](https://raw.githubusercontent.com/docutils/docutils/master/docutils/test/functional/expected/math_output_mathml.html) | Public domain | native MathML | +| `html/math/mathematics_mathml_blahtexml_875f65.html` | [Docutils functional-test expected output](https://raw.githubusercontent.com/docutils/docutils/master/docutils/test/functional/expected/mathematics_mathml_blahtexml.html) | Public domain | native MathML | +| `html/math/mathematics_mathml_pandoc_b65cef.html` | [Docutils functional-test expected output](https://raw.githubusercontent.com/docutils/docutils/master/docutils/test/functional/expected/mathematics_mathml_pandoc.html) | Public domain | MathML with an application/x-tex <annotation> | +| `html/math/output_data_badc7e.html` | [Aequitas bias-audit toolkit documentation](https://raw.githubusercontent.com/dssg/aequitas/master/docs/output_data.html) | MIT | LaTeX in the alt attribute of Sphinx-rendered | +| `html/math/reg_783dab.html` | ["Learning Apache Spark with Python" book, regression](https://raw.githubusercontent.com/runawayhorse001/LearningApacheSpark/master/docs/reg.html) | MIT | LaTeX in the alt attribute of Sphinx-rendered | +| `html/math/rmarkdown_4b0a34.html` | ["Introducción a R" bookdown book](https://raw.githubusercontent.com/rubenfcasal/bookdown_intro/master/docs/rmarkdown.html) | CC0-1.0 | raw LaTeX in \[…\] inside span class="math dis | +| `html/math/sample_5da28a.html` | [MathJax v2 test suite](https://raw.githubusercontent.com/mathjax/MathJax/legacy-v2/test/sample.html) | Apache-2.0 | raw LaTeX with $…$, \(…\), \[…\] and AMS envir | +| `html/math/scipy_stats_norm_60d729.html` | [SciPy reference documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html) | BSD-3-Clause | raw LaTeX in \[…\] / \(…\) inside class="math | +| `hwp/math/EC_88_98_EC_8B_9D_2acc8f.hwp` | [neolord0/hwplib](https://raw.githubusercontent.com/neolord0/hwplib/main/sample_hwp/basic/%EC%88%98%EC%8B%9D.hwp) | Apache-2.0 | HWP EQEdit script (EQEDIT record, tag 88) insi | +| `hwp/math/SimpleEquation_4e1760.hwpx` | [neolord0/hwpxlib](https://raw.githubusercontent.com/neolord0/hwpxlib/main/testFile/reader_writer/SimpleEquation.hwpx) | Apache-2.0 | HWP EQEdit script inside OWPML <hp:equation><h | +| `hwp/math/doc_8713v3a8b_3D23v9e_3D4av07_3D85v3e_3Dcfafvbb7dv2ad9_v_a3c2e7.hwp` | [Ahnd6474/jakal-hwpx](https://raw.githubusercontent.com/Ahnd6474/jakal-hwpx/main/hwpx_collection/doc_8713v3a8b%3D23v9e%3D4av07%3D85v3e%3Dcfafvbb7dv2ad9_v4607.hwpx) | MIT for the repository | HWP EQEdit script (EQEDIT record, tag 88) insi | +| `hwp/math/eq_01_71f171.hwp` | [postmelee/alhangeul-macos](https://raw.githubusercontent.com/postmelee/alhangeul-macos/main/samples/eq-01.hwp) | MIT for the repository | HWP EQEdit script (EQEDIT record, tag 88) insi | +| `hwp/math/equation_p0_e63f26.hwpx` | [airmang/python-hwpx](https://raw.githubusercontent.com/airmang/python-hwpx/main/tests/fixtures/equation_preview/equation_p0.hwpx) | Apache-2.0 | HWP EQEdit script inside OWPML <hp:equation><h | +| `hwp/math/from_5d05e0.hwpx` | [neolord0/hwp2hwpx](https://raw.githubusercontent.com/neolord0/hwp2hwpx/main/test/equation/from.hwpx) | Apache-2.0 | HWP EQEdit script inside OWPML <hp:equation><h | +| `hwp/math/from_ecaebf.hwp` | [neolord0/hwp2hwpx](https://raw.githubusercontent.com/neolord0/hwp2hwpx/main/test/equation/from.hwp) | Apache-2.0 | HWP EQEdit script (EQEDIT record, tag 88) insi | +| `hwp/math/hard_20example_3d4d15.hwpx` | [Ahnd6474/jakal-hwpx](https://raw.githubusercontent.com/Ahnd6474/jakal-hwpx/main/hwpx_collection/hard%20example.hwpx) | MIT for the repository | HWP EQEdit script inside OWPML <hp:equation><h | +| `iwork/math/geometric_means_qcmc_revised_7d7c7a.key` | [Zenodo record 'Quantum algorithms for matrix geometr](https://zenodo.org/api/records/14309036/files/geometric-means-qcmc-revised.key/content) | CC-BY-4.0 | LaTeX source held in Keynote's native TSWPEqua | +| `jats/math/10_21105_joss_01816_736f75.jats` | [Journal of Open Source Software](https://raw.githubusercontent.com/openjournals/joss-papers/master/joss.01816/10.21105.joss.01816.jats) | CC-BY-4.0 | LaTeX <tex-math> + MathML under <alternatives> | +| `jats/math/10_21105_joss_06105_a7ce1e.jats` | [Journal of Open Source Software](https://raw.githubusercontent.com/openjournals/joss-papers/master/joss.06105/10.21105.joss.06105.jats) | CC-BY-4.0 | LaTeX in <tex-math> CDATA and MathML in <mml:m | +| `jupyter/math/07_sympy_7d5b08.ipynb` | [maths-with-python](https://raw.githubusercontent.com/IanHawke/maths-with-python/master/07-sympy.ipynb) | MIT | LaTeX — both markdown cells and executed outpu | +| `jupyter/math/Handcalcs_julia_cf3b0c.ipynb` | [Handcalcs.jl official examples](https://raw.githubusercontent.com/co1emi11er2/Handcalcs.jl/master/examples/Handcalcs_julia.ipynb) | MIT | LaTeX (`\begin{align}`) in text/latex output b | +| `jupyter/math/StatesOperators_4e6d54.ipynb` | [QuTiP official guide notebooks](https://raw.githubusercontent.com/qutip/qutip-notebooks/master/docs/guide/StatesOperators.ipynb) | BSD-3-Clause | LaTeX — `\begin{equation*}...\end{array}` matr | +| `jupyter/math/SymPy_9b271e.ipynb` | [JetBrains/intellij-ipnb](https://raw.githubusercontent.com/JetBrains/intellij-ipnb/master/testData/SymPy.ipynb) | Apache-2.0 | LaTeX in nbformat v3 `pyout` outputs (legacy ` | +| `jupyter/math/autodiff_cookbook_a09ead.ipynb` | [JAX official documentation](https://raw.githubusercontent.com/jax-ml/jax/main/docs/notebooks/autodiff_cookbook.ipynb) | Apache-2.0 | LaTeX in markdown cells (inline `$...$` and di | +| `jupyter/math/chapter02_definitions_586622.ipynb` | [noBSLAnotebooks](https://raw.githubusercontent.com/minireference/noBSLAnotebooks/master/chapter02_definitions.ipynb) | MIT | LaTeX in text/latex output bundles (newer SymP | +| `jupyter/math/eseries_37d1f4.ipynb` | [QuTiP example notebooks](https://raw.githubusercontent.com/qutip/qutip-notebooks/master/examples/eseries.ipynb) | BSD-3-Clause | LaTeX in text/latex output bundles and inline | +| `jupyter/math/handcalc_quarto_578f98.ipynb` | [Handcalcs.jl official examples](https://raw.githubusercontent.com/co1emi11er2/Handcalcs.jl/master/examples/handcalc_quarto.ipynb) | MIT | LaTeX (`\begin{aligned}` environments) in text | +| `jupyter/math/latexify_examples_fcaa0e.ipynb` | [latexify_py](https://raw.githubusercontent.com/google/latexify_py/main/examples/latexify_examples.ipynb) | Apache-2.0 | LaTeX in text/latex output bundles | +| `jupyter/math/sympy_expressions_e09585.ipynb` | [Blaze](https://raw.githubusercontent.com/blaze/blaze/master/docs/source/_static/notebooks/sympy-expressions.ipynb) | BSD-3-Clause | LaTeX in nbformat v3 `pyout` outputs (legacy ` | +| `latex/math/36640_t_ab6f06.tex` | [Project Gutenberg / Distributed Proofreaders](https://www.gutenberg.org/files/36640/36640-t/36640-t.tex) | Public domain | LaTeX (amsmath) | +| `latex/math/41568_t_c5dd66.tex` | [Project Gutenberg / Distributed Proofreaders](https://www.gutenberg.org/files/41568/41568-t/41568-t.tex) | Public domain | LaTeX (amsmath, custom \Tag macro) | +| `latex/math/apssamp_456d02.tex` | [REVTeX 4.2](https://mirrors.ctan.org/macros/latex/contrib/revtex/sample/aps/apssamp.tex) | LPPL-1.3c | LaTeX (REVTeX 4.2 + amsmath) | +| `latex/math/mathtools_60dab8.tex` | [brucemiller/LaTeXML](https://raw.githubusercontent.com/brucemiller/LaTeXML/master/t/ams/mathtools.tex) | Public domain / CC0-equivalent | LaTeX (mathtools + amsmath) | +| `latex/math/physics_7344b9.tex` | [brucemiller/LaTeXML](https://raw.githubusercontent.com/brucemiller/LaTeXML/master/t/complex/physics.tex) | Public domain / CC0-equivalent | LaTeX (physics package) | +| `latex/math/sampler_af5d02.tex` | [brucemiller/LaTeXML](https://raw.githubusercontent.com/brucemiller/LaTeXML/master/t/math/sampler.tex) | Public domain / CC0-equivalent | LaTeX (amsmath, amsfonts, mathrsfs, mathtools) | +| `latex/math/testmath_232f5d.tex` | [latex3/latex2e](https://raw.githubusercontent.com/latex3/latex2e/develop/required/amsmath/testmath.tex) | LPPL-1.3c | LaTeX (amsmath) | +| `markdown/math/markdown_features_math_equations_d0952e.mdx` | [Docusaurus documentation site](https://raw.githubusercontent.com/facebook/docusaurus/main/website/docs/guides/markdown-features/markdown-features-math-equations.mdx) | MIT | LaTeX via three MDX notations in one file: `$. | +| `markdown/math/mathjax_49c700.md` | [mdBook user guide](https://raw.githubusercontent.com/rust-lang/mdBook/master/guide/src/format/mathjax.md) | MPL-2.0 | LaTeX in mdBook's doubled-backslash delimiters | +| `markdown/math/neural_networks_case_study_aeb5f4.md` | [Stanford CS231n course notes](https://raw.githubusercontent.com/cs231n/cs231n.github.io/master/neural-networks-case-study.md) | MIT | LaTeX in `$$...$$` display blocks plus `\( ... | +| `markdown/math/spe_67468e.markdown` | [Tapkee](https://raw.githubusercontent.com/lisitsyn/tapkee/main/doc/methods/spe.markdown) | BSD-3-Clause | LaTeX in `$...$` / `$$...$$`, with Markdown-es | +| `markdown/math/supported_b0c613.md` | [KaTeX](https://raw.githubusercontent.com/KaTeX/KaTeX/main/docs/supported.md) | MIT | LaTeX in `$...$` inline math, thousands of ins | +| `markup/math/SimpleFormula_a6349f.odf` | [ODF Toolkit](https://raw.githubusercontent.com/tdf/odftoolkit/master/odfdom/src/test/resources/test-input/SimpleFormula.odf) | Apache-2.0 | MathML, standalone ODF formula document (no dr | +| `markup/math/aGHQ_b16faa.qmd` | [Embrace Uncertainty: Mixed-effects models with Julia](https://raw.githubusercontent.com/JuliaMixedModels/EmbraceUncertainty/main/aGHQ.qmd) | MIT | LaTeX in `$$...$$` with Quarto equation cross- | +| `markup/math/bareboat_math_17fcb0.adoc` | [Bareboat Necessities](https://raw.githubusercontent.com/bareboat-necessities/my-bareboat/master/docs/bareboat-math.adoc) | Apache-2.0 | AsciiMath (via bare `:stem:`) | +| `markup/math/chapter_02_52ac82.rmd` | [esl-solutions](https://raw.githubusercontent.com/AlipayAlgorithms/esl-solutions/master/chapter-02.Rmd) | MIT | LaTeX: `$$` wrapping `\begin{equation}` AMS en | +| `markup/math/component_implementing_streaming_2ffd4c.adoc` | [Talend Component Runtime documentation](https://raw.githubusercontent.com/Talend/component-runtime/master/documentation/src/main/antora/modules/ROOT/pages/component-implementing-streaming.adoc) | Apache-2.0 | AsciiMath | +| `markup/math/formula_0225f1.fodp` | [LibreOffice core, Impress unit-test data](https://raw.githubusercontent.com/LibreOffice/core/master/sd/qa/unit/data/odp/formula.fodp) | MPL-2.0 | MathML inline in a flat ODF presentation (offi | +| `markup/math/from_7b6cac.adoc` | [PartiQL Specification v0.3.0](https://raw.githubusercontent.com/partiql/partiql-lang/main/src/from.adoc) | Custom "PartiQL Specification License" | AsciiMath | +| `markup/math/inline_quoted_5ede1e.adoc` | [asciidoctor-doctest](https://raw.githubusercontent.com/asciidoctor-contrib/asciidoctor-doctest/master/data/examples/asciidoc/inline_quoted.adoc) | MIT | AsciiMath and LaTeXMath (inline macros) | +| `markup/math/licao_6_feba57.qmd` | [stats_modelling](https://raw.githubusercontent.com/maxbiostat/stats_modelling/master/notas/licao_6.qmd) | MIT | LaTeX: raw `\begin{align*}` environments plus | +| `markup/math/paths_32d458.adoc` | [PartiQL Specification v0.3.0](https://raw.githubusercontent.com/partiql/partiql-lang/main/src/paths.adoc) | Custom "PartiQL Specification License" | AsciiMath | +| `markup/math/sensorlib_spec_f243ef.adoc` | [Sony Semiconductor Solutions](https://raw.githubusercontent.com/SonySemiconductorSolutions/mossfw/main/docs/sensorlib_spec.adoc) | Apache-2.0 | AsciiMath | +| `markup/math/var_982761.qmd` | [dass2024](https://raw.githubusercontent.com/tenomoto/dass2024/main/var.qmd) | BSD-3-Clause | LaTeX in `$$...$$`, `\begin{aligned}`, Quarto | +| `office/math/03_Inferential_20statistics2024_2025_bd7449.pptx` | [Zenodo](https://zenodo.org/api/records/14361416/files/03_Inferential%20statistics2024_2025.pptx/content) | CC-BY-4.0 | OMML inside <a14:m> | +| `office/math/Fermat_general_7d3de0.pptx` | [Zenodo](https://zenodo.org/api/records/15252111/files/Fermat_general.pptx/content) | CC-BY-4.0 | OMML inside <a14:m> | +| `office/math/MG35_1_MathGuide_7e950e.odt` | [The Document Foundation, LibreOffice 3.5 Math Guide](https://wiki.documentfoundation.org/images/8/8b/MG35_1-MathGuide.odt) | CC-BY-3.0 OR GPL-3.0-or-later | MathML with PREFIXED math: namespace and the O | +| `office/math/MG44_MathGuide_ed525b.odt` | [The Document Foundation, LibreOffice 4.4 Math Guide](https://wiki.documentfoundation.org/images/b/bc/MG44-MathGuide.odt) | CC-BY-4.0 OR GPL-3.0-or-later | MathML (default namespace) with StarMath 5.0 a | +| `office/math/MG7001_CrearEditarFormulas_de2112.odt` | [The Document Foundation, Guia de Math 7.2, Chapter 1](https://wiki.documentfoundation.org/images/4/44/MG7001-CrearEditarFormulas.odt) | CC-BY-4.0 OR GPL-3.0-or-later | MathML with StarMath 5.0 annotation | +| `office/math/MG7003_FormulasCalcDrawImpress_0129ab.odt` | [The Document Foundation, Guia de Math 7.2, Chapter 3](https://wiki.documentfoundation.org/images/9/93/MG7003-FormulasCalcDrawImpress.odt) | CC-BY-4.0 OR GPL-3.0-or-later | MathML with StarMath 5.0 annotation | +| `office/math/Manju_20Ghalyan_2d1798.docx` | [Zenodo record 822996, journal article "MATHEMATICAL ](https://zenodo.org/api/records/822996/files/Manju%20Ghalyan.docx/content) | CC-BY-4.0 | OMML | +| `office/math/OpenDocument_v1_2_os_part1_0fdaaa.odt` | [OASIS OpenDocument v1.2 specification, Part 1](https://raw.githubusercontent.com/tdf/odftoolkit/master/xslt-runner/src/test/resources/odf12/OpenDocument-v1.2-os-part1.odt) | OASIS IPR Policy | MathML 1.01 (default namespace) with StarMath | +| `office/math/OpenDocument_v1_3_cs01_part3_schema_80057c.odt` | [OASIS OpenDocument v1.3 cs01 Part 3](https://raw.githubusercontent.com/tdf/odftoolkit/master/xslt-runner/src/test/resources/odf13/OpenDocument-v1.3-cs01-part3-schema.odt) | OASIS IPR Policy | MathML with StarMath 5.0 annotation, embedded | +| `office/math/PSAAP_review_presentation_102022_SAND2022_14495_PE_a5d658.pptx` | [Zenodo](https://zenodo.org/api/records/7232101/files/PSAAP_review_presentation_102022-SAND2022-14495-PE.pptx/content) | CC-BY-4.0 | OMML inside <a14:m> | +| `office/math/PejmanJouzdani_f8d8e3.pptx` | [Zenodo](https://zenodo.org/api/records/10407797/files/PejmanJouzdani.pptx/content) | CC-BY-4.0 | OMML inside <a14:m>, with <m:oMathPara> displa | +| `office/math/Single_THz_photon_detector_JuliangLi_ANL_82bc42.pptx` | [Zenodo](https://zenodo.org/api/records/4641119/files/Single_THz_photon_detector_JuliangLi_ANL.pptx/content) | CC-BY-4.0 | OMML inside <a14:m> | +| `office/math/Supplementry_20Material_1e5dc4.docx` | [Zenodo record 19008259, "SUPPLEMENTARY MATERIALS for](https://zenodo.org/api/records/19008259/files/Supplementry%20Material.docx/content) | CC-BY-4.0 | OMML | +| `office/math/Zucker_EAAT_statistics_16c5f9.pptx` | [Zenodo](https://zenodo.org/api/records/7072775/files/Zucker_EAAT_statistics.pptx/content) | CC-BY-4.0 | OMML inside <a14:m> | +| `office/math/editable_04513a.pptx` | [figedit](https://raw.githubusercontent.com/giszzt/figedit/main/assets/examples/ast-reveal/editable.pptx) | MIT | OMML: <a14:m><m:oMathPara><m:oMath>, inside mc | +| `office/math/editable_0c0c46.pptx` | [figedit](https://raw.githubusercontent.com/giszzt/figedit/main/assets/examples/parallel-loops/editable.pptx) | MIT | OMML: <a14:m><m:oMathPara>, inside mc:Alternat | +| `office/math/equation_16f2f6.docx` | [dotnet Open XML SDK test assets](https://raw.githubusercontent.com/dotnet/Open-XML-SDK/main/test/DocumentFormat.OpenXml.Tests.Assets/assets/TestDataStorage/v2FxTestFiles/wordprocessing/equation/equation.docx) | MIT | OMML | +| `office/math/equation_a59623.doc` | [Apache POI test-data/document](https://raw.githubusercontent.com/apache/poi/trunk/test-data/document/equation.doc) | Apache-2.0 | MathML plus a StarMath 5.0 annotation, inside | +| `office/math/equations_b6ad03.docx` | [Microsoft MarkItDown test files](https://raw.githubusercontent.com/microsoft/markitdown/main/packages/markitdown/tests/test_files/equations.docx) | MIT | OMML | +| `office/math/equations_d0d980.docx` | [docling](https://raw.githubusercontent.com/docling-project/docling/main/tests/data/docx/sources/equations.docx) | MIT | OMML | +| `office/math/math_OOo311_71135a.odt` | [ODF Toolkit](https://raw.githubusercontent.com/tdf/odftoolkit/master/validator/src/test/resources/math_OOo311.odt) | Apache-2.0 | MathML, prefixed math: namespace + OOo modifie | +| `office/math/pascal_digital_binomial_theorem_Senior_20Seminar_20Thesi_82393b.pptx` | [Zenodo](https://zenodo.org/api/records/20702180/files/pascal_digital_binomial_theorem(Senior%20Seminar%20Thesis,%20%ED%95%99%EC%82%AC%20%EC%84%B8%EB%AF%B8%EB%82%98%20%EB%B0%9C%ED%91%9C%20%EC%9E%90%EB%A3%8C,%20%EC%9B%90%EB%B3%B8).pptx/content) | CC-BY-4.0 | OMML inside <a14:m> | +| `office/math/strict_20math_53ebf7.docx` | [docx4j sample documents](https://raw.githubusercontent.com/plutext/docx4j/VERSION_17_0_3/docx4j-samples-docx4j/sample-docs/strict/strict%20math.docx) | Apache-2.0 | OMML (ISO/IEC 29500 Strict namespace) | +| `office/math/table_with_equations_f14832.docx` | [docling DOCX test corpus](https://raw.githubusercontent.com/docling-project/docling/main/tests/data/docx/sources/table_with_equations.docx) | MIT | OMML | +| `office/math/tdf119223_394ffc.odp` | [LibreOffice core, Impress unit-test data](https://raw.githubusercontent.com/LibreOffice/core/master/sd/qa/unit/data/odp/tdf119223.odp) | MPL-2.0 | MathML with StarMath 5.0 annotation | +| `office/math/tdf130614_9b6224.ods` | [LibreOffice core, Calc UI-test data](https://raw.githubusercontent.com/LibreOffice/core/master/sc/qa/unit/uicalc/data/tdf130614.ods) | MPL-2.0 | MathML with StarMath 5.0 annotation | +| `office/math/tdf159046_e964cb.ods` | [LibreOffice core, Calc UI-test data](https://raw.githubusercontent.com/LibreOffice/core/master/sc/qa/unit/uicalc/data/tdf159046.ods) | MPL-2.0 | MathML with StarMath 5.0 annotation, embedded | +| `office/math/testMSEquation_govdocs_863534_a6c49e.doc` | [Apache Tika test corpus](https://raw.githubusercontent.com/apache/tika/main/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-microsoft-module/src/test/resources/test-documents/testMSEquation-govdocs-863534.doc) | Apache-2.0 | MTEF (Microsoft Equation Editor 3.0 / Design S | +| `office/math/testWORD_2006ml_9696cd.docx` | [Apache Tika microsoft-parser test documents](https://raw.githubusercontent.com/apache/tika/main/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-microsoft-module/src/test/resources/test-documents/testWORD_2006ml.docx) | Apache-2.0 | OMML | +| `office/math/unknown_content_bda4e1.odt` | [ODF Toolkit](https://raw.githubusercontent.com/tdf/odftoolkit/master/odfdom/src/test/resources/test-input/unknown-content.odt) | Apache-2.0 | MathML with StarMath 5.0 annotation | +| `office/math/w11_w11_fore0ww8_8441b1.rtf` | [dotnet/wpf-test](https://raw.githubusercontent.com/dotnet/wpf-test/main/src/Test/Editing/FeatureTests/Data/rtf/rtfcit/w11_w11_fore0ww8.rtf) | MIT | RTF EQ field instructions (\f fraction, \i int | +| `org/math/00_introduccion_02ccfe.org` | [agarbuno/aprendizaje-estadistico](https://raw.githubusercontent.com/agarbuno/aprendizaje-estadistico/latest/notas/00-introduccion.org) | MIT | LaTeX `\begin{align}` and inline `$...$` in Or | +| `org/math/01_montecarlo_c9ecc6.org` | [agarbuno/modelacion-bayesiana](https://raw.githubusercontent.com/agarbuno/modelacion-bayesiana/latest/notas/01-montecarlo.org) | MIT | LaTeX `\begin{align}` and inline `$...$` in Or | +| `org/math/02_mcmc_246b17.org` | [agarbuno/modelacion-bayesiana](https://raw.githubusercontent.com/agarbuno/modelacion-bayesiana/latest/notas/02-mcmc.org) | MIT | LaTeX `\begin{align}` environments and inline | +| `org/math/Org_Mode_885465.org` | [caiorss/Emacs-Elisp-Programming](https://raw.githubusercontent.com/caiorss/Emacs-Elisp-Programming/master/Org-Mode.org) | Unlicense | LaTeX `\begin{equation}` / `\begin{align}` env | +| `org/math/latex_0d83c6.org` | [orgajs](https://raw.githubusercontent.com/orgapp/orgajs/main/docs/advanced/latex.org) | MIT | Org mode `$$...$$`, `\(...\)`, `\[...\]` and ` | +| `pdf/math/19930091059_e5a481.pdf` | [NACA Report 1135, "Equations, Tables, and Charts for](https://ntrs.nasa.gov/api/citations/19930091059/downloads/19930091059.pdf) | Public domain | SCANNED: 70 pages of 300 dpi bitonal CCITT-G4 | +| `pdf/math/19930093947_a3f534.pdf` | [NACA Technical Memorandum 1278, "General solution of](https://ntrs.nasa.gov/api/citations/19930093947/downloads/19930093947.pdf) | Public domain | SCANNED: 21 pages of 300 dpi bitonal CCITT-G4 | +| `pdf/math/20100014819_ba4d91.pdf` | [NASA Technical Memorandum 20100014819, "Approximate ](https://ntrs.nasa.gov/api/citations/20100014819/downloads/20100014819.pdf) | Public domain | PDF text layer; equations are Word/Equation-Ed | +| `pdf/math/2306_08071_597a81.pdf` | [arXiv](https://arxiv.org/pdf/2306.08071) | CC-BY-4.0 | PDF text layer, LaTeX/Computer-Modern glyph ru | +| `pdf/math/2502_20028_047181.pdf` | [arXiv](https://arxiv.org/pdf/2502.20028) | CC-BY-4.0 | PDF text layer, LaTeX glyph runs; A4 page size | +| `pdf/math/2511_07120_8176dc.pdf` | [arXiv](https://arxiv.org/pdf/2511.07120) | CC-BY-4.0 | PDF text layer, Unicode-mapped math glyph runs | +| `pdf/math/CollegeAlgebra_OP_7d1fcd.pdf` | [OpenStax](https://assets.openstax.org/oscms-prodcms/media/documents/CollegeAlgebra-OP.pdf) | CC-BY-4.0 | PDF text layer, but built-up fractions/radical | +| `pdf/math/amsldoc_642b4e.pdf` | [American Mathematical Society](https://mirrors.ctan.org/macros/latex/required/amsmath/amsldoc.pdf) | LPPL-1.3c | PDF text layer, pdfTeX Type1 math fonts; mixes | +| `pdf/math/journal_pcbi_1012015_type_printable_1eeb41.pdf` | [PLOS Computational Biology 2024, "Modeling single ce](https://journals.plos.org/ploscompbiol/article/file?id=10.1371/journal.pcbi.1012015&type=printable) | CC-BY-4.0 | PDF text layer, but with a custom symbol-font | +| `pdf/math/physica_manual_bcb494.pdf` | [typst-physics](https://raw.githubusercontent.com/Leedehai/typst-physics/master/physica-manual.pdf) | MIT | PDF text layer, Typst-generated Unicode math g | +| `pdf/math/testmath_e28157.pdf` | [American Mathematical Society](https://mirrors.ctan.org/macros/latex/required/amsmath/testmath.pdf) | LPPL-1.3c | PDF text layer, pdfTeX Type1 math fonts; the A | +| `rst/math/comprehensive_math_test_276a5e.rst` | [Docutils](https://raw.githubusercontent.com/docutils/docutils/master/docutils/test/functional/input/data/comprehensive-math-test.rst) | Public domain | LaTeX inside reST `.. math::` and `:math:` rol | +| `rst/math/fitting_71d4d8.rst` | [lmfit-py](https://raw.githubusercontent.com/lmfit/lmfit-py/master/doc/fitting.rst) | BSD-3-Clause | LaTeX inside reST `.. math::`, including `:now | +| `rst/math/g_functions_7277dd.rst` | [SymPy](https://raw.githubusercontent.com/sympy/sympy/master/doc/src/modules/integrals/g-functions.rst) | BSD-3-Clause | LaTeX (with AMS `cases`) inside reST `.. math: | +| `rst/math/linear_model_1a957c.rst` | [scikit-learn](https://raw.githubusercontent.com/scikit-learn/scikit-learn/main/doc/modules/linear_model.rst) | BSD-3-Clause | LaTeX inside reST `.. math::` directive and `: | +| `rst/math/lombscargle_bedb55.rst` | [Astropy](https://raw.githubusercontent.com/astropy/astropy/main/docs/timeseries/lombscargle.rst) | BSD-3-Clause | LaTeX inside reST `.. math::` | +| `rst/math/math_776aea.rst` | [Docutils functional test suite](https://raw.githubusercontent.com/docutils/docutils/master/docutils/test/functional/input/data/math.rst) | Public domain | LaTeX inside reST `.. math::` (prefix and post | +| `rst/math/math_de2679.rst` | [Sphinx](https://raw.githubusercontent.com/sphinx-doc/sphinx/master/tests/roots/test-ext-math/math.rst) | BSD-2-Clause | LaTeX inside reST `.. math::` with `:label:`, | +| `rst/math/mixed_linear_524bae.rst` | [statsmodels](https://raw.githubusercontent.com/statsmodels/statsmodels/main/docs/source/mixed_linear.rst) | BSD-3-Clause | LaTeX inside reST `.. math::` and `:math:` | +| `rst/math/neutron_physics_1490f3.rst` | [OpenMC](https://raw.githubusercontent.com/openmc-dev/openmc/develop/docs/source/methods/neutron_physics.rst) | MIT | LaTeX inside reST `.. math::` with `:label:` e | +| `rst/math/physical_models_c61dfa.rst` | [Astropy](https://raw.githubusercontent.com/astropy/astropy/main/docs/modeling/physical_models.rst) | BSD-3-Clause | LaTeX inside reST `.. math::` | +| `typst/math/main_979fe4.typ` | [typst/packages](https://raw.githubusercontent.com/typst/packages/main/packages/preview/ntnu-physics-report-replica/0.1.0/template/main.typ) | MIT | Typst math | +| `typst/math/main_c87a40.typ` | [typst/packages](https://raw.githubusercontent.com/typst/packages/main/packages/preview/clean-math-paper/0.2.8/template/main.typ) | MIT | Typst math | +| `typst/math/manual_4ee3cf.typ` | [typst/packages](https://raw.githubusercontent.com/typst/packages/main/packages/preview/lacy-ubc-math-project/0.2.0/manual.typ) | MIT | Typst math | +| `typst/math/physica_manual_b4d792.typ` | [Leedehai/typst-physics](https://raw.githubusercontent.com/Leedehai/typst-physics/master/physica-manual.typ) | MIT | Typst math | +| `xml/math/7f8rqRq4vSnJ7B738VKMKqF_11b207.xml` | [SciELO](https://raw.githubusercontent.com/scieloorg/packtools/master/tests/fixtures/htmlgenerator/latex/7f8rqRq4vSnJ7B738VKMKqF.xml) | BSD-2-Clause | LaTeX in <tex-math> (with \documentclass/amsma | +| `xml/math/Tutorial_2006_4bafe3.xml` | ["Learning Modern 3D Graphics Programming"](https://raw.githubusercontent.com/paroj/gltut/master/Documents/Positioning/Tutorial%2006.xml) | MIT | DocBook <mathphrase> plain-text math; <equatio | +| `xml/math/elife_41046_v2_622635.xml` | [eLife Sciences](https://raw.githubusercontent.com/elifesciences/elife-article-xml/master/articles/elife-41046-v2.xml) | CC-BY-4.0 | MathML (mml:-prefixed), JATS 1.x disp-formula | +| `xml/math/equation_004_a5d8f4.xml` | [The DocBook Project](https://raw.githubusercontent.com/docbook/xslTNG/main/src/test/resources/xml/equation.004.xml) | MIT | MathML embedded in DocBook 5 <equation> | +| `xml/math/equation_005_a1808c.xml` | [The DocBook Project](https://raw.githubusercontent.com/docbook/xslTNG/main/src/test/resources/xml/equation.005.xml) | MIT | Verbatim LaTeX in DocBook <mathphrase role="te | +| `xml/math/example_04c981.xml` | [transpect / mml2tex](https://raw.githubusercontent.com/transpect/mml2tex/master/example/example.xml) | BSD-2-Clause | MathML (mml:-prefixed) inside DocBook 5 <equat | +| `xml/math/f_5dcc94.xml` | [SciELO](https://raw.githubusercontent.com/scieloorg/packtools/master/tests/fixtures/htmlgenerator/mmlmath/f.xml) | BSD-2-Clause | MathML, both default-namespace and mml:-prefix | +| `xml/math/journal_pcbi_1005589_type_manuscript_58c02e.xml` | [PLOS Computational Biology](https://journals.plos.org/ploscompbiol/article/file?id=10.1371/journal.pcbi.1005589&type=manuscript) | CC-BY-4.0 | MathML inside JATS <alternatives>, JATS Journa | +| `xml/math/manuscript_933c4c.xml` | [Texture](https://raw.githubusercontent.com/substance/texture/master/data/kitchen-sink/manuscript.xml) | MIT | LaTeX in <tex-math> CDATA, JATS disp-formula / | + +Committed: 136. The binary formats among them live in the bucket and are pinned by `corpus.lock.json`, following the storage split in `README.md`. + +## Reference only, not committed + +These carry ShareAlike, GFDL or GPL terms, or upstream metadata that disagrees with the project's own stated licence. The redistribution policy in `LICENSES.md` keeps such content out of the repository, so their provenance is recorded without vendoring the bytes. + +| document | source | licence | +|---|---|---| +| `2_1_common_math_84f243.adoc` | [Modelica Association](https://raw.githubusercontent.com/modelica/fmi-standard/main/docs/2_1_common_math.adoc) | CC-BY-SA-4.0 | +| `EquationAsScientificNumbering_7e7710.docx` | [LibreOffice core, sw/qa/extras/ooxmlexport/data](https://raw.githubusercontent.com/LibreOffice/core/master/sw/qa/extras/ooxmlexport/data/EquationAsScientificNumbering.docx) | COPYLEFT - FLAGGED | +| `README_38c17d.asciidoc` | [Hilscher / Muhkuh test framework](https://raw.githubusercontent.com/muhkuh-sys/org.muhkuh.tests-ramtest/master/README.asciidoc) | GPL-2.0 | +| `linear_algebra_e4ca4c.epub` | ["A First Course in Linear Algebra" by Robert A. Beez](https://github.com/IDPF/epub3-samples/releases/download/20230704/linear-algebra.epub) | GNU FDL 1.2 or later | +| `lln_clt_5360eb.md` | [QuantEcon](https://raw.githubusercontent.com/QuantEcon/lecture-python-intro/main/lectures/lln_clt.md) | CC-BY-SA-4.0 | +| `math_1a3c42.fb2` | [pandoc](https://raw.githubusercontent.com/jgm/pandoc/main/test/fb2/math.fb2) | GPL-2.0-or-later | +| `math_8f5f31.odp` | [LibreOffice core, Impress unit-test data](https://raw.githubusercontent.com/LibreOffice/core/master/sd/qa/unit/data/odp/math.odp) | MPL-2.0 | +| `math_mso2k7_597eb9.docx` | [LibreOffice core, sw/qa/extras/ooxmlexport/data](https://raw.githubusercontent.com/LibreOffice/core/master/sw/qa/extras/ooxmlexport/data/math-mso2k7.docx) | COPYLEFT - FLAGGED | +| `math_nary_5b4ff9.docx` | [LibreOffice core, sw/qa/extras/ooxmlexport/data](https://raw.githubusercontent.com/LibreOffice/core/master/sw/qa/extras/ooxmlexport/data/math-nary.docx) | COPYLEFT - FLAGGED | +| `mathtype_569f25.docx` | [LibreOffice core, sw/qa/extras/ooxmlexport/data](https://raw.githubusercontent.com/LibreOffice/core/master/sw/qa/extras/ooxmlexport/data/mathtype.docx) | COPYLEFT - FLAGGED | +| `writer_3efc89.org` | [Pandoc test suite](https://raw.githubusercontent.com/jgm/pandoc/main/test/writer.org) | FLAG | +| `writer_db63ab.fb2` | [pandoc](https://raw.githubusercontent.com/jgm/pandoc/main/test/writer.fb2) | GPL-2.0-or-later | + +Reference only: 12. diff --git a/html/math/2212_09410_f9ff0c.html b/html/math/2212_09410_f9ff0c.html new file mode 100644 index 0000000..e68e8f3 --- /dev/null +++ b/html/math/2212_09410_f9ff0c.html @@ -0,0 +1,2298 @@ +<!DOCTYPE html><html lang="en"> +<head> +<meta http-equiv="content-type" content="text/html; charset=UTF-8"> +<title>[2212.09410] Less is More: Parameter-Free Text Classification with Gzip + + + + + + + + + + + + + + + + + + + +
+
+
+

Less is More: Parameter-Free Text Classification with Gzip

+
+ +Zhiying Jiang + +   +Matthew Y.R. Yang + +   +Mikhail Tsirlin + +   +Raphael Tang + +   +Jimmy Lin + +Affiliation: [1ex] +David R. Cheriton School of Computer Science + +Affiliation: University of Waterloo + +Affiliation: [1ex] +{zhiying.jiang, m259yang, mtsirlin, r33tang, jimmylin}@uwaterloo.ca +
+ +
Abstract
+ +

Deep neural networks (DNNs) are often used for text classification tasks as they usually achieve high levels of accuracy. However, DNNs can be computationally intensive with billions of parameters and large amounts of labeled data, which can make them expensive to use, to optimize and to transfer to out-of-distribution (OOD) cases in practice. In this paper, we propose a non-parametric alternative to DNNs that’s easy, light-weight and universal in text classification: a combination of a simple compressor like gzip with a kk-nearest-neighbor classifier. Without any training, pre-training or fine-tuning, our method achieves results that are competitive with non-pretrained deep learning methods on six in-distributed datasets. It even outperforms BERT on all five OOD datasets, including four low-resource languages. Our method also performs particularly well in few-shot settings where labeled data are too scarce for DNNs to achieve a satisfying accuracy.

+ +
+
+

1 Introduction

+ +
+

Text classification, as one of the most fundamental tasks in natural language processing (NLP), has improved substantially with the help of neural networks Li et al. 2022. +However, most neural networks are data hungry, the degree of which increases with the number of parameters. +They also have many hyperparameters that must be carefully tuned for different datasets, and the preprocessing of text data (e.g., tokenization, stop word removal) must be tailored to the specific model and dataset. Despite their ability to capture latent correlations and recognize implicit patterns LeCun et al. 2015 complex deep neural networks may be overkill for simple tasks such as text classification. +For example, Adhikari et al. 2019b find that a simple long short-term memory network (LSTM; Hochreiter and Schmidhuber 1997) with appropriate regularization can achieve competitive results. Shen et al. 2018 further show that even word-embedding-based methods can achieve results comparable to convolutional neural networks (CNNs) and recurrent neural networks (RNNs).

+
+
+

In this paper, we propose a simple, lightweight and universal alternative to DNNs for text classification that combines a lossless compressor with a kk-nearest-neighbor classifier. It’s simple because it doesn’t require any pre-processing or training. It’s lightweight in that it achieves results competitive to DNN methods without the need of parameters or GPU resource. It’s universal as compressors are data-type agnostic, non-parametric methods do not bring inductive bias by the training procedure and it performs well on out-of-distribution (OOD) cases, where datasets are unseen by the model during pre-training or training stage.

+
+
+

Lossless compressors aim to represent information using as few bits as possible by assigning shorter codes to symbols with higher probability. +The intuition of using compressor for classification is that (1) compressors are good at capturing regularity; (2) objects from the same category share more regularity than those that aren’t. For example, x1x_{1} below belongs to the same category as x2x_{2} but belongs to a different category from x3x_{3}. If we use C()C(\cdot) to represent compressed length, we will find C(x1x2)C(x1)<C(x1x3)C(x1)C(x_{1}x_{2})-C(x_{1})<C(x_{1}x_{3})-C(x_{1}) where C(x1x2)C(x_{1}x_{2}) means the compressed length of concatenation of x1x_{1} and x2x_{2}. In other words, C(x1x2)C(x1)C(x_{1}x_{2})-C(x_{1}) can be interpreted as how many bytes we can save to encode x2x_{2} if we know x1x_{1}.

+
+

x1x_{1} = Japan’s Seiko Epson Corp. said Wednesday it has developed a 12-gram flying microrobot, the world’s lightest.

+

x2x_{2} = The latest tiny flying robot that could help in search and rescue or surveillance has been unveiled in Japan.

+

x3x_{3} = Michael Phelps won the gold medal in the 400 individual medley and set a world record in a time of 4 minutes 8.26 seconds.

+
+

This simple intuition can be formalized as a distance metric derived from Kolmogorov complexity Kolmogorov 1963 which will be discussed in detail in Section 3.

+
+
+

Our contributions are as follows: +(1) We propose a parameter-free method that achieves results comparable to non-pretrained neural network models that have millions of parameters on six out of seven in-distributed datasets; +(2) We demonstrate that our method outperforms non-pretrained neural networks in few-shot settings when labeled data is extremely limited; +(3) We show that our method outperforms pre-trained models on out-of-distributed datasets, under both full and few-shot settings; +(4) We find that, as a universal baseline, our method is particularly effective for datasets that are easily compressible.

+
+
+
+

2 Related Work

+ +
+

2.1 Compressor-Based Text Classification

+ +
+

Compressor-based distance metrics have been used mainly for plagiarism detection Chen et al. 2004, clustering Vitányi et al. 2009 and classifying time series data Chen et al. 1999; Keogh et al. 2004.

+
+
+

Several previous works explore methods using a compressor-based distance metric for text classification: Li et al. 2004 applies it to language identification as language are different in length by nature (e.g., addresses <English>, adressebok <Norwegian>, adressekartotek <Danish>); Khmelev and Teahan 2003 uses it for authorship categorization; Frank et al. 2000; Teahan and Harper 2003 utilize Prediction by Partial Matching (PPM) for topic classification. PPM, a text compression scheme utilizing language modeling, estimates the cross entropy between the probability distribution built on class cc and the document dd: Hc(d)H_{c}(d). The intuition is that the lower the cross entropy is, the more likely that dd belongs to cc.

+
+
+

Summarized in Russell 2010, the procedure of using compressor to estimate Hc(d)H_{c}(d) is that: (1) for each class cc, concatenate all samples dcd_{c} in the training set belonging to cc; (2) compress dcd_{c} as one long document to get the compressed length C(dc)C(d_{c}); (3) concatenate the given test sample dud_{u} with dcd_{c} and compress to get C(dcdu)C(d_{c}d_{u}); (4) the predicted class is argmincC(dcdu)C(dc)\argmin_{c}C(d_{c}d_{u})-C(d_{c}).

+
+
+

The major drawback of this method is that concatenating all training documents in one class makes it hard to take full advantage of large training set, as compressors like gzip has a limited size of sliding window, which is responsible for “how much” the compressor can look back to find repeated patterns. Marton et al. 2005 further investigate the distance metric C(dc(i)dc)C(dc(i))C(d_{c}^{(i)}d_{c})-C(d_{c}^{(i)}) where dc(i)d_{c}^{(i)} is a single document belonging to class cc. +Coutinho and Figueiredo 2015; Kasturi and Markov 2022 focus on improving representations based on compressor to improve the classification accuracy.

+
+
+

To the best of our knowledge, all the previous work use relatively small datasets like 20News and Reuters-10. +There is neither a comparison between compressor-based methods and deep learning methods nor any comprehensive study on large-sized datasets.

+
+
+
+

2.2 DNN-Based Text Classification

+ +
+

The deep learning methods used for text classification can be divided into two: transductive learning, represented by Graph Convolutional Networks (GCN) Yao et al. 2019, and inductive learning, where both recurrent neural networks (RNN) and convolutional neural networks (CNN) are main forces. We focus on inductive learning in this paper as transductive learning assumes the test dataset is presented during the training.

+
+
+

Zhang et al. 2015 first use the character-based CNN with millions of parameters for text classification. Conneau et al. 2017 extend the idea with more layers. +Along the line of RNNs, Kawakami 2008 introduce a method that uses LSTMs Hochreiter and Schmidhuber 1997 to learn the sequential information for classification. To better capture the important information regardless of its position in the sentence, Wang et al. 2016 incorporate the attention mechanism into the relation classification. Yang et al. 2016 include a hierarchical structure for sentence-level attention.

+
+
+

As the number of parameters and the complexity of models increase, Joulin et al. 2017 start to explore the possibility of using simple linear model with a hidden layer coping with nn-gram features and hierarchical softmax to improve efficiency.

+
+
+

The status quo of classification is further changed by the prevalence of pre-trained models like BERT Kenton and Toutanova 2019, with thousands of millions of parameters pre-trained on corpus containing billions of words. BERT can achieve the state of the art on numerous tasks including text classification Adhikari et al. 2019a with just some fine-tunings. Built on BERT, Reimers and Gurevych 2019 calculate semantic similarity between pairs of sentences efficiently by using a siamese network architecture and fine-tuning on multiple NLI datasets Bowman et al. 2015; Williams et al. 2018.

+
+
+
+
+

3 Our Approach

+ +
+

Kolmogorov complexity K(x)K(x) characterizes the length of the shortest binary program that can generate xx. K(x)K(x) is theoretically the ultimate lower bound for information measurement. Given this notion of information measurement, how, do we compare information content between two objects? +To this end, Bennett et al. 1998 define information distance E(x,y)E(x,y) as the length of the shortest binary program that converts xx to yy:

+ + + + + + + + + + + + + + +
E(x,y)\displaystyle E(x,y)=max{K(x|y),K(y|x)}\displaystyle=\max\{K(x|y),K(y|x)\}(1)
=K(xy)min{K(x),K(y)}\displaystyle=K(xy)-\min\{K(x),K(y)\}(2)
+
+
+

However, E(x,y)E(x,y) is not computable as Kolmogorov complexity is incomputable, and absolute distance makes comparison among objects hard. Li et al. 2004 proposes a normalized and computable version of information distance, Normalized Compression Distance (NCD), utilizing compressed length C(x)C(x) to approximate Kolmogorov complexity K(x)K(x). Formally, it’s defined as follows +(detailed derivation is shown in Appendix A):

+ + + + + + + +
NCD(x,y)=C(xy)min{C(x),C(y)}max{C(x),C(y)}NCD(x,y)=\frac{C(xy)-\min\{C(x),C(y)\}}{\max\{C(x),C(y)\}}(3)
+

The intuition behind using compressed length is that the length of xx that has been maximally compressed by a compressor is close to K(x)K(x). The higher the compression ratio, the closer C(x)C(x) is to K(x)K(x). +Our main experiment results use gzip as the compressor, thus, C(x)C(x) means the length of xx after compressed by gzip. C(xy)C(xy) is the compressed length of concatenation of xx and yy. With the distance matrix NCD provides, we can then use kk-nearest-neighbor to classify.

+
+
+

Our method can be implemented with fifteen lines of Python code below, whose input is training_set, test_set, both of which consist of an array of (text, label), and k:

+
+
+
+
+ 1 + + + + + + + + import gzip +
+
+ 2 + + + + + + + + import numpy as np +
+
+ 3 + + + + + + + + +
+
+ 4 + + + + + + + + for (x1, _) in test_set: +
+
+ 5 + + + + + + + + Cx1 = len(gzip.compress(x1.encode())) +
+
+ 6 + + + + + + + + distance_from_x1 = [] +
+
+ 7 + + + + + + + + for (x2, _) in training_set: +
+
+ 8 + + + + + + + + Cx2 = len(gzip.compress(x2.encode()) +
+
+ 9 + + + + + + + + x1x2 = " ".join([x1, x2]) +
+
+ 10 + + + + + + + + Cx1x2 = len(gzip.compress(x1x2.encode()) +
+
+ 11 + + + + + + + + ncd = (Cx1x2 - min(Cx1,Cx2)) / max(Cx1, Cx2) +
+
+ 12 + + + + + + + + distance_from_x1.append(ncd) +
+
+ 13 + + + + + + + + sorted_idx = np.argsort(np.array(distance_from_x1)) +
+
+ 14 + + + + + + + + top_k_class = training_set[sorted_idx[:k], 1] +
+
+ 15 + + + + + + + + predict_class = max(set(top_k_class), key=top_k_class.count) +
+
+
Listing 1: Python Code for Text Classification with Gzip
+
+
+
+

4 Experiments

+ +
+

4.1 Datasets

+ +
+

We choose this diverse basket of datasets to investigate the effects of the number of training samples, the number of classes, the length of the text and the difference in distribution on accuracy. The details of each dataset’s statistics are listed in Table 1. Previous works on text classification have two disjoint preferences when choosing evaluation datasets: CNN and RNN-based methods favor large scale datasets (AG News, SogouNews, DBpedia, YahooAnswers) for evaluation, whereas transductive methods like graph convolutional neural network focus on datasets with smaller training sets (20News, Ohsumed, R8, R52) Li et al. 2022. We include datasets on both sides in order to investigate how our method performs with both abundant training samples and limited ones. Apart from the variation of the dataset sizes, we also take the effects of number of classes into consideration by intentionally including datasets like R52 to evaluate our the performance on datasets with large number of classes. Previous work Marton et al. 2005 show that the length of text also affects the accuracy of compressor-based methods so we present the statistics in Table 1 as well. +Except for SogouNews, we also include other four out-of-distributed datasets — Kinyarwanda news, Kirundi news, Filipino dengue and Swahili news to further evaluate our method’s robustness.

+
+
+
+

4.2 Baselines

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dataset#Training#Test#ClassesAvg#WordsAvg#Chars#Vocab
AG News120,0007,600443.9236.4128,349
DBpedia560,00070,0001453.7301.31,031,601
YahooAnswers1,400,00060,00010107.2520.81,554,607
20News11,3147,53220406.021902.5277,330
ohsumed3,3574,04323212.11273.255,142
R85,4852,1898102.4586.823,584
R526,5322,56852109.6631.426,283
KinyarwandaNews17,0144,25414232.31872.3240,366
KirundiNews3,68992314210.21721.563,143
DengueFilipino4,015500510.162.712,819
SwahiliNews22,2077,3386327.02196.5569,603
SogouNews450,00060,0005589.42780.0610,908
+
Table 1: Details of datasets used for evaluation.
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model#ParamPre-trainingTrainingExternal DataPre-Process
TFIDF+LR260,000tok+tfidf+dict (+lower)
LSTM5,190,000tok+dict (+wv+lower+pad)
Bi-LSTM+Attn8,210,000tok+dict (+wv+lower+pad)
HAN29,700,000tok+dict (+wv+lower+pad)
charCNN2,700,000dict (+lower+pad)
textCNN30,700,000tok+dict (+wv+lower+pad)
RCNN18,800,000tok+dict (+wv+lower+pad)
VDCNN13,700,000dict (+lower+pad)
fasttext8,190,000tok+dict (+lower+pad+ngram)
BERT109,000,000tok+dict+pe (+lower+pad)
W2V0tok+dict (+lower)
SentBERT0tok+dict (+lower)
TextLength0
gzip0
+
Table 2: Models used for comparison and their number of parameters; whether they are pre-trained; whether data augmentation is used and whether pre-processing is needed.
+
+
+

We compare our result with (1) neural network methods that require training and (2) zero-training methods that use the kkNN classifier directly, with or without pre-training. +Specifically, we choose mainstream architectures for text classification, like logistic regression, fasttext Joulin et al. 2017, RNNs with or without attention (vanilla LSTM Hochreiter and Schmidhuber 1997, bidirectional LSTMs Schuster and Paliwal 1997 with attention Wang et al. 2016, hierarchical attention networks Yang et al. 2016), CNNs (character CNNs Zhang et al. 2015, recurrent CNNs Lai et al. 2015, very deep CNNs Conneau et al. 2017) and BERT Devlin et al. 2019 Adhikari et al. 2019a. We also include three other zero-training methods: word2vec (W2V) Mikolov et al. 2013, pre-trained sentence BERT Reimers and Gurevych 2019, and the length of the instance, all using a kkNN classifier. To prevent the class from being predicted based on text length, we evaluate a baseline where the instance text length is used as the only input into a kkNN classifier. +We call this baseline the TextLength method.

+
+
+

We present model statistics and trade-offs in Table 2. +Since the number of classes, the vocabulary size, and the dimensions affect the number of parameters, we estimate the model size using AGNews. +This dataset has a relatively small vocabulary size and number of classes, hence making the estimation of the lower bound out of the studied datasets. Some methods require pre-training either on the target dataset or on other external datasets. Most neural networks require pre-processing like tokenization (“tok”), building vocabulary dictionaries and mapping tokens (“dict”), using pre-trained word2vec (“wv”), lowercasing the words (“lower”) and padding the sequence to a certain length (“pad”). Other model-specific pre-processing includes adding extra bag of n-grams (“ngram”) for fasttext and using positional embedding (“pe”) for BERT.

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model/DatasetAGNewsDBpediaYahooAnswers20NewsOhsumedR8R52
Training Required
TFIDF+LR0.8980.9820.7150.8270.5490.9490.874
LSTM0.8610.9850.7080.6570.4110.9370.855
Bi-LSTM+Attn0.9170.9860.7320.5880.2710.8680.693
HAN0.8960.9860.7450.6460.4620.9600.914
charCNN0.9140.9860.7120.4010.2690.8230.724
textCNN0.8170.9810.7280.7510.5700.9510.895
RCNN0.9120.9840.7020.7160.4720.8100.773
VDCNN0.9130.9870.7340.4910.2370.8580.750
fasttext0.9110.9780.7020.6900.2180.8270.571
BERT0.9440.9920.7680.8680.7410.9820.960
Zero Training
W2V0.8920.9610.6890.4600.2840.9300.856
SentBERT0.9400.9370.7820.7780.7190.9470.910
Zero Training & Zero Pre-Training
TextLength0.2750.0930.1050.0530.0900.4550.362
gzip (ours)0.9370.9700.6380.6850.5210.9540.896
+
Table 3: Test accuracy with each section’s best results bolded, and best results beaten by gzip underlined.
+
+
+
+

4.3 Result on In-Distributed Datasets

+ +
+

We train all baselines on eight datasets (training details are in Appendix B). The result of using the full training sets are shown in Table 3. As we can see, our method performs surprisingly well on AG News, R8 and R52. For AG News, fine-tuning BERT achieves the best performance among all methods, and gzip, with no pretraining, achieves competitive result, within 0.007 points of BERT. +The accuracy of gzip on DBpedia is about 1%1\% lower than other neural network methods. For YahooAnswers, the accuracy of gzip is about 7%7\% lower than the average neural methods. This may due to the fact that the vocabulary size of YahooAnswers is large, making it hard for the compressor to compress (detailed discussion is in Section 5).

+
+
+

Starting from 20News dataset, the training size becomes smaller, where non-pretrained deep learning models are thought to be less advantageous. On the 20News dataset, pre-trained methods achieve the best result and gzip’s accuracy is in the middle. Ohsumed is a dataset containing paper abstracts in the medical domain, aimed at categorizing 23 cardiovascular diseases. On Ohsumed, gzip is lower than textCNN, BERT, SentBERT, competitive to LR and higher than others. +For R8, gzip has the third highest accuracy, only lower than HAN and BERT. For R52, gzip ranks the fourth, surpassed by HAN, BERT and SentBERT.

+
+
+

Overall, BERT-based models are robust even when the size of training samples are small, but do not excel when the dataset is out of distributed of the pre-training corpus (e.g., SogouNews). Character-based models like charCNN and VDCNN perform badly when the training data is small and the vocabulary size is large (e.g., 20News). The advantage of word-based models is non-obvious when the training data is small either, but they are better at handling big vocabulary size. They are also inferior to character-based models when classifying corpus that are not English, similar to BERT-based models. Logistic regression with TFIDF features, although doesn’t achieve the best on any dataset, is very robust to the size of the dataset. The result of TextLength is close to random guess on all but R8 and R52, showing that the distribution of length doesn’t reflect the information of class in other six datasets, indicating the compressed length information used in NCD does not benefit from the length distribution of different classes.

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Datasetaveragegzip
AGNews0.9010.937
DBpedia0.9780.970
YahooAnswers0.7260.638
20News0.6560.685
Ohsumed0.4330.521
R80.9030.954
R520.8150.896
+
Table 4: Test accuracy comparison between the average of all baseline models (excluding TextLength) and gzip.
+
+
+

gzip does not perform well on extremely large dataset (e.g., YahooAnswers), but are competitive on medium and small-size datasets. Performance-wise, the only non-preptrained deep learning model that’s competitive to gzip is HAN, who surpass gzip on 50% datasets and still achieve relatively high accuracy when it’s beaten by gzip, unlike textCNN. The difference is that gzip doesn’t require training.

+
+
+

We list the average of all baseline models’ test accuracy (except TextLength for its extremely low accuracy) in Table 4. We can see our method is either higher or close to the average on all but YahooAnswers.

+
+
+
+

4.4 Result on Out-Of-Distributed Datasets

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model/DatasetKinyarwandaNewsKirundiNewsDengueFilipinoSwahiliNewsSogouNews
Shot#Full5-shotFull5-shotFull5-shotFull5-shotFull5-shot
BERT0.8380.240±\pm0.0600.8790.386±\pm0.0990.9790.409±\pm0.0580.8970.396±\pm0.0960.9520.221±\pm0.041
mBERT0.8350.229±\pm0.0660.8740.324±\pm0.0710.9830.465±\pm0.0480.9060.558±\pm0.1690.9530.282±\pm0.060
gzip (ours)0.8910.458±\pm0.0650.9050.541±\pm0.0560.9980.652±\pm0.0480.9270.627±\pm0.0720.9750.649±\pm0.061
+
+
Table 5: Test accuracy on out-of-distributed datasets with 95% confidence interval over five trials in five-shot setting.
+
+
+

Generalizing to Out-Of-Distributed datasets have always been a challenge in machine learning. Even with the success of pre-trained models, this problem is not alleviated. In fact, Yu et al. 2021 have shown that improved in-distributed accuracy on pre-trained models may lead to poor OOD performance in image classification. +In order to compare our method with pre-trained models on text classification, we choose five datasets that are unseen in BERT’s pre-trained corpus. Specifically, we use Kinyarwanda news, Kirundi news, Filipino dengue, Swahili news and Sogou news. Those datasets are chosen to have Roman script which means they have a very similar alphabet as English. For example, Swahili has the same vowels as English but doesn’t have q,x as consonants; Sogou news only have Pinyin – a phonetic romanization of Chinese. Therefore, those datasets can be viewed as permutation of English alphabets.

+
+
+

We use BERT pre-trained on English and BERT pre-trained on 104 languages (mBERT). We can see that on languages that mBERT has been pre-trained on (Kinyarwanda, Kirundi or Pinyin), mBERT has lower accuracy than BERT in both full-data setting and few-shot setting. On Filipino and Swahili, mBERT has much higher accuracy than BERT especially in few-shot setting. However, on all five datasets, our method outperform both BERT and mBERT by large margin without any pre-training or fine-tuning.

+
+
+

This shows the robustness of our method facing the OOD datasets. Our method is universal in a way that it is designed to handle unseen datasets as compressor is data-type-agnostic and non-parametric methods do not bring inductive bias induced by the training procedure.

+
+
+
+
5510105050100100000.20.20.40.40.60.60.80.811# of shotsTest AccuracyfasttextBi-LSTM+AttnHANW2VSentBERTBERTgzip
5510105050100100000.20.20.40.40.60.60.80.811# of shotsTest AccuracyfasttextBi-LSTM+AttnHANW2VSentBERTBERTgzip
5510105050100100000.20.20.40.40.60.60.80.811# of shotsTest AccuracyfasttextBi-LSTM+AttnHANW2VSentBERTBERTgzip
+
Figure 1: Comparison among different methods using different shots on AG News, DBpedia and SogouNews with 95% confidence interval over five trials.
+
+
+
+

4.5 Few-Shot Learning

+ +
+

We further compare the result of gzip under the few-shot-learning setting with deep learning methods. We first carry out experiments on AGNews, DBpedia and SogouNews across both non-pretrained deep neural networks and pre-trained ones using nn-shot labeled examples per class from training dataset, where n={5,10,50,100}n=\{5,10,50,100\}. We chose these three datasets as their scale is large enough to cover 100-shot setting and they vary in text lengths as well as languages. We choose methods whose trainable parameters range from zero parameters like word2vec and sentence BERT to hundreds of millions of parameters like BERT, covering both word-based models (HAN) and the n-gram one (fasttext).

+
+
+

The result is plotted in Figure 1 (detailed numbers are shown in Appendix C). As we can see, gzip outperforms non-pretrained models on 5,10,505,10,50 settings for all three datasets and especially in the n=5n=5 setting, gzip outperforms deep learning models by large margin. For example, the accuracy of gzip is 115% better than fasttext on AGNews 5-shot setting. In the 100-shot setting, gzip also outperforms non-pretrained models on AGNews and SogouNews but is a little bit lower than them on DBpedia.

+
+
+

It’s been investigated in the previous work Nogueira et al. 2020; Zhang et al. 2021 that pre-trained models are excellent few-shot learners. The advantages of BERT and SentBERT on the AGNews are obvious where they achieve the highest and the second highest accuracy on every shot number. However, on SogouNews, both BERT and SentBERT are surpassed by gzip on every shot number, consistent with the result on full dataset. This is reasonable as the inductive bias learned from the pre-training data is so strong—notice how low the accuracy is when only given 5-shot training samples to BERT, that hinders BERT to be applied to the dataset that’s significantly different from the pre-trained datasets. +The surprising part is that even on DBpedia gzip still outperforms SentBERT on 50-shot and 100-shot settings. Note that BERT has been pre-trained on Wikipedia and DBpedia is extracted from Wikipedia, which may explain the nearly perfect score of BERT on DBpedia. In general, the larger the number of labeled training samples are, the closer that the accuracy gap between gzip and deep learning models are, except for W2V, which is extremely unstable. This is due to the vectors being trained for a limited set of words, meaning that numerous tokens in the test set are out-of-vocabulary.

+
+
+

Given pre-trained models’ outstanding performance in few-shot settings on in-distributed datasets, we further investigate their few-shot performance on out-of-distributed datasets. In Table 5, we carry out experiments under 5-shot setting with BERT and mBERT. The advantage of using our method in 5-shot is more obvious than on the full datasets — our method improves the accuracy of BERT by 90.8%90.8\%, 40.2%40.2\%, 59.4%59.4\%, 58.3%58.3\% and 193.7%193.7\% and surpasses mBERT’s accuracy by 100.0%100.0\%, 67.0%67.0\%, 40.2%40.2\%, 12.4%12.4\% and 130.1%130.1\% on the corresponding five datasets.

+
+
+
+
+

5 Analyses

+ +
+

To understand the merits and shortcomings of using gzip for classification, we evaluate gzip’s performance in terms of both the absolute accuracy and the relative performance compared to the neural methods. An absolute low accuracy with a high relative performance suggests that the dataset itself is difficult, while a high accuracy with a low relative performance means the dataset is better solved by a neural network. As our method performs well on out-of-distributed datasets, we are more interested in analyzing in-distributed cases. We carry out on seven in-distributed datasets and one out-of-distributed datasets across fourteen models to account for different ranks. We analyze both the relative performance and the absolute accuracy regarding the vocabulary size and the compression rate of both datasets (i.e., how easily a dataset can be compressed) and compressors (i.e., how well a compressor can compress).

+
+
+

To represent the relative performance with regard to other methods, we use the normalized rank percentage, computed as rank of gziptotal#methods\frac{\text{rank of gzip}}{\text{total\#methods}}; the lower the score, the better gzip is. We use “bits per character”(bpc) to evaluate the compression rate. The procedure is to randomly sample a thousand instances from the training and test set respectively, calculate the compressed length and divide by the number of characters. Sampling is to +keep the size of the dataset a constant.

+
+
+
+
0.20.20.40.40.60.60.80.8111.21.21.41.41.61.6106\cdot 10^{6}000.20.20.40.40.60.60.80.8111.21.2Vocabulary SizeNormalized Rank PercentageAGNewsDBpediaYahooAnswers20NewsOhsumedR8R52SogouNews
222.22.22.42.42.62.62.82.8333.23.23.43.4000.20.20.40.40.60.60.80.8111.21.2Bits per CharacterNormalized Rank PercentageAGNewsDBpediaYahooAnswers20NewsOhsumedR8R52SogouNews
+
Figure 2: Relative performance v.s. vocabulary size and compression rate.
+
+
+

5.1 Relative Performance

+ +
+

Combining Table 1 and Table 3, we see that accuracy is largely unaffected by the average length of a single sample: with the Spearman coefficient rs=0.220r_{s}=-0.220. But the relative performance is more correlated with vocabulary size (rs=0.561r_{s}=0.561) as we can see in Figure 2. SogouNews is an outlier in the first plot: on a fairly large vocabulary-sized dataset, gzip ranks the first. The second plot may provide an explanation for that — the compression ratio for SogouNews is high which means even with a relatively large vocabulary size, there are also repetitive information that can be squeezed out. With rs=0.785r_{s}=0.785 on the correlation between the normalized rank percentage and the compression rate, we can see when a dataset is easier to compress, our method may be a strong candidate as a classifier.

+
+
+
+
55101050501001000.60.60.80.811# of shotsTest Accuracybz2lzmazstdgzip
55101050501001000.60.60.80.811# of shotsTest Accuracybz2lzmazstdgzip
55101050501001000.60.60.80.811# of shotsTest Accuracybz2lzmazstdgzip
+
Figure 3: Comparison among different compressors on AG News, SogouNews and DBpedia, with 95% confidence interval over five trials.
+
+
+
Figure 4: Compression ratio V.S. Test Accuracy across different compressors on three datasets under different shot settings
+
+
+
+

5.2 Absolute Accuracy

+ +
+

Similarly we evaluate the accuracy of classification with respect to the vocabulary size and we’ve found there is almost no monotonic relation (OPENrs=0.071)r_{s}=0.071). With regard to bpc, the monotonic relation is not as strong as the one with the rank percentage (rs=0.56r_{s}=-0.56). Considering the effect that vocabulary size has on the relative performance, our method with gzip may be more susceptible to the vocabulary size than neural network methods. To distinguish between a “hard” dataset and an “easy” one, we average all models’ accuracies. The dataset that has the lowest accuracies are 20News and Ohsumed, which are two datasets that have the longest average length of texts.

+
+
+
+

5.3 Using Other Compressors

+ +
+

With compressor-based distance metrics we can use any compressor. Because of the large size of the test set of the datasets, we randomly chose 1,000 test samples to evaluate and repeat the experiments for each setting five times to calculate the mean and 95% confidence interval.

+
+
+

We carry out experiments on other three compressors: bz2, lzma and zstandard under the few-shot setting. Each of them has different underlying algorithms from gzip. bz2 uses Burrows-Wheeler algorithm to permute the order of characters in the strings to create more repeated “substrings” that can be compressed. That’s one of the reasons why bz2 has a higher compression ratio (e.g., it can achieve 2.57 bpc on AGNews while gzip can achieve only 3.38 bpc). lzma is based on LZ77, a dictionary-based compression algorithm, where the idea is to use (offset, length) to represent the n-gram that has previously appeared in the search buffer. lzma then uses range coding to further encode (offset, length). Similarly, gzip uses DEFLATE algorithm, which also uses LZ77 and instead of range coding, it takes advantage of Huffman coding to further encode (offset, length). zstandard (zstd) is a new compression algorithm that’s built on LZ77, Huffman coding as well as Asymmetric Numeral Systems (ANS) Duda 2009. We pick zstd to evaluate for its fast speed, with close compression rate to gzip. A competitive result may indicate it can be used to speed up the classification.

+
+
+

We plot all the test accuracy in Figure 4 with the compression ratio for each compressor. Compression ratio is calculated by original sizecompressed size\frac{\text{original size}}{\text{compressed size}}, so the larger the compression ratio is, the more a compressor can compress. We use compression ratio instead of bpc here as the latter one is too close to each other and cannot be differentiated from one another. Markers of ‘+’ represents the mean of each compressor’s test accuracy across different shot settings. The dataset is not explicitly labeled but we can tell that there are roughly three clusters in the plot. AGNews is the cluster with the lowest compression ratio and SogouNews is the one with the highest compression ratio. Note that gzip and zstd with compression ratio of about 7 belongs to the SogouNews result.

+
+
+

On SogouNews, both gzip and zstd have the compression ratio equal to about 7; bz2 and lzma have the compression ratio over 9. The difference of accuracy is more obvious on the AGNews and DBpedia with bz2 being the worst-performing compressor. This is counterintuitive, as a compressor with a higher compression ratio suggests that it can approximate Kolmogorov complexity better, and bz2 has a higher compression ratio. We conjecture it may be because in practice, Burrows-Wheeler algorithm used by bz2 dismisses the information of character order. This is shown more clearly in Figure 4bz2 is always lower than the regression line. In general, gzip achieves a relatively high and stable accuracy across three datasets. lzma is competitive with gzip but the speed is much slower.

+
+
+

We’ve found in Section 5.1 that for a single compressor, the easier a dataset can compress, the more probable it can achieve a higher accuracy than deep learning models. Here we investiage the correlation across compressors. We’ve found the compression ratio and test accuracy has a moderate monotonic and linear correlation and as the shot number increases, the linear correlation is more obvious with rs=0.605r_{s}=0.605 for all shot settings and Pearson correlation rp=0.575,0.638,0.691,0.719r_{p}=0.575,0.638,0.691,0.719 respectively on 5, 10, 50 and 100 setting across four compressors. Combining the special case of bz2 with the linear correlation between compression ratio and test accuracy, we know that in general a compressor with a high compression ratio can perform better on a more compressible dataset. But the actual compression algorithm still has its effect on the test accuracy despite the high compression ratio.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + +
+
+

Method

+
+
+

AGNews

+
+
+

SogouNews

+
+
+

DBpedia

+
+
+

YahooAnswers

+
+
+

gzip(ce)

+
+
+

0.739 + +±\pm0.046 +

+
+
+

0.741 + +±\pm0.076 +

+
+
+

0.880 + +±\pm0.010 +

+
+
+

0.408 + +±\pm0.012 +

+
+
+

gzip(kkNN)

+
+
+

0.752 + +±\pm0.041 +

+
+
+

0.862 + +±\pm0.033 +

+
+
+

0.852 + +±\pm0.008 +

+
+
+

0.352 + +±\pm0.014 +

+
+
+
Table 6: Comparison with other compressor-based methods under the 100-shot setting.
+
+
+
+

5.4 Using Other Compressor-Based Methods

+ +
+

The distance metric used by previous work Marton et al. 2005; Russell 2010 is mainly C(dcdu)C(dc)C(d_{c}d_{u})-C(d_{c}) as we mention in Section 2.1. +Although using this distance metric is faster than pair-wise distance matrix computation on small datasets, it has several drawbacks: (1) Most compressors have a limited “size”, for gzip it’s the sliding window size that can be used to search back of the repeated string while for lzma it’s the dictionary size it can keep record of. This means even if there are large number of training samples, the compressor cannot take full advantage of those samples; (2) When dcd_{c} is large, compressing dcdud_{c}d_{u} can be really slow and this slowness cannot be solved by parallelization. These two main drawbacks stop this method to be applied to a really large dataset. Thus, we randomly pick 1000 test samples and 100-shot from each class in training samples to compare these two methods. In Table 6, “gzip (ce)” means using the cross entropy C(dcdu)C(dc)C(d_{c}d_{u})-C(d_{c}) while “gzip (kkNN)” refers to our method. We carry our each experiment for five times and calculate the mean and 95% confidence interval. On AGNews and SogouNews using kkNN and NCD is better than using cross entropy. The reason for the large accuracy gap between them on SogouNews is probably because each instance in SogouNews is very long, causing about 11.2K per sample, while gzip typically has 32K window size only. Only concatenation a few samples makes the compression ineffective. The cross-entropy method does perform very well on YahooAnswers, which may benefit from using multiple references in the single category as YahooAnswers is a divergent dataset created by numerous online users.

+
+
+

We also test the performance of compressor-based cross entropy method on full AGNews dataset as it is a relatively smaller one with shorter single instance. The accuracy is 0.745, not much higher than 100-shot setting, which further confirms that using C(dcdu)C(dc)C(d_{c}d_{u})-C(d_{c}) as a distance metric cannot take full advantage of the large datasets.

+
+
+
+
+

6 Conclusions and Future Work

+ +
+

In this paper, we use gzip together with a compressor-based distance metric to achieve classification accuracy comparable to neural network classifiers on in-distributed datasets and outperform pre-trained models on out-of-distributed datasets. We also show the effectiveness of using this method in few-shot scenarios. +In future works, we will extend this work by generalizing gzip to neural compressors on text, as recent studies Jiang et al. 2022 show that combining neural compressors that derived from deep latent variables models with compressor-based distance metrics for image classification can even outperform semi-supervised methods.

+
+
+
+

References

+ +
    + +
  • Adhikari et al. (2019a) + +Ashutosh Adhikari, Achyudh Ram, Raphael Tang, and Jimmy Lin. +2019a. + + +Docbert: Bert for document classification. + + +arXiv preprint arXiv:1904.08398. + +
  • + +
  • Adhikari et al. (2019b) + +Ashutosh Adhikari, Achyudh Ram, Raphael Tang, and Jimmy Lin. +2019b. + + +Rethinking complex neural network architectures for document +classification. + + +In Proceedings of the 2019 Conference of the North American +Chapter of the Association for Computational Linguistics: Human Language +Technologies, Volume 1 (Long and Short Papers), pages 4046–4051. + +
  • + +
  • Bennett et al. (1998) + +Charles H Bennett, Péter Gács, Ming Li, Paul MB Vitányi, and +Wojciech H Zurek. 1998. + + +Information distance. + + +IEEE Transactions on information theory, 44(4):1407–1423. + +
  • + +
  • Bowman et al. (2015) + +Samuel Bowman, Gabor Angeli, Christopher Potts, and Christopher D Manning. +2015. + + +A large annotated corpus for learning natural language inference. + + +In Proceedings of the 2015 Conference on Empirical Methods in +Natural Language Processing, pages 632–642. + +
  • + +
  • Chen et al. (2004) + +Xin Chen, Brent Francia, Ming Li, Brian Mckinnon, and Amit Seker. 2004. + + +Shared information and program plagiarism detection. + + +IEEE Transactions on Information Theory, 50(7):1545–1551. + +
  • + +
  • Chen et al. (1999) + +Xin Chen, Sam Kwong, and Ming Li. 1999. + + +A compression algorithm for dna sequences and its applications in +genome comparison. + + +Genome informatics, 10:51–61. + +
  • + +
  • Conneau et al. (2017) + +Alexis Conneau, Holger Schwenk, Loïc Barrault, and Yann Lecun. 2017. + + +Very deep convolutional networks for text classification. + + +In Proceedings of the 15th Conference of the European Chapter +of the Association for Computational Linguistics: Volume 1, Long Papers, +pages 1107–1116. + +
  • + +
  • Coutinho and Figueiredo (2015) + +David Pereira Coutinho and Mario AT Figueiredo. 2015. + + +Text classification using compression-based dissimilarity measures. + + +International Journal of Pattern Recognition and Artificial +Intelligence, 29(05):1553004. + +
  • + +
  • Devlin et al. (2019) + +Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. + + +Bert: Pre-training of deep bidirectional transformers for language +understanding. + + +In Proceedings of the 2019 Conference of the North American +Chapter of the Association for Computational Linguistics: Human Language +Technologies, Volume 1 (Long and Short Papers), pages 4171–4186. + +
  • + +
  • Duda (2009) + +Jarek Duda. 2009. + + +Asymmetric numeral systems. + + +arXiv preprint arXiv:0902.0271. + +
  • + +
  • Frank et al. (2000) + +Eibe Frank, Chang Chui, and Ian H Witten. 2000. + + +Text categorization using compression models. + +
  • + +
  • Hochreiter and Schmidhuber (1997) + +Sepp Hochreiter and Jürgen Schmidhuber. 1997. + + +Long short-term memory. + + +Neural computation, 9(8):1735–1780. + +
  • + +
  • Jiang et al. (2022) + +Zhiying Jiang, Yiqin Dai, Ji Xin, Ming Li, and Jimmy Lin. 2022. + + +Few-shot non-parametric learning with deep latent variable model. + + +Advances in Neural Information Processing Systems (NeurIPS). + +
  • + +
  • Joulin et al. (2017) + +Armand Joulin, Edouard Grave, and Piotr Bojanowski Tomas Mikolov. 2017. + + +Bag of tricks for efficient text classification. + + +EACL 2017, page 427. + +
  • + +
  • Kasturi and Markov (2022) + +Nitya Kasturi and Igor L Markov. 2022. + + +Text ranking and classification using data compression. + + +In I (Still) Can’t Believe It’s Not Better! Workshop at NeurIPS +2021, pages 48–53. PMLR. + +
  • + +
  • Kawakami (2008) + +Kazuya Kawakami. 2008. + + +Supervised sequence labelling with recurrent neural networks. + + +Ph. D. thesis. + +
  • + +
  • Kenton and Toutanova (2019) + +Jacob Devlin Ming-Wei Chang Kenton and Lee Kristina Toutanova. 2019. + + +Bert: Pre-training of deep bidirectional transformers for language +understanding. + + +In Proceedings of NAACL-HLT, pages 4171–4186. + +
  • + +
  • Keogh et al. (2004) + +Eamonn Keogh, Stefano Lonardi, and Chotirat Ann Ratanamahatana. 2004. + + +Towards parameter-free data mining. + + +In Proceedings of the tenth ACM SIGKDD international conference +on Knowledge discovery and data mining, pages 206–215. + +
  • + +
  • Khmelev and Teahan (2003) + +Dmitry V Khmelev and William J Teahan. 2003. + + +A repetition based measure for verification of text collections and +for text categorization. + + +In Proceedings of the 26th annual international ACM SIGIR +conference on Research and development in informaion retrieval, pages +104–110. + +
  • + +
  • Kingma and Ba (2015) + +Diederik P Kingma and Jimmy Ba. 2015. + + +Adam: A method for stochastic optimization. + + +In ICLR (Poster). + +
  • + +
  • Kolmogorov (1963) + +Andrei N Kolmogorov. 1963. + + +On tables of random numbers. + + +Sankhyā: The Indian Journal of Statistics, Series A, pages +369–376. + +
  • + +
  • Lai et al. (2015) + +Siwei Lai, Liheng Xu, Kang Liu, and Jun Zhao. 2015. + + +Recurrent convolutional neural networks for text classification. + + +In Twenty-ninth AAAI conference on artificial intelligence. + +
  • + +
  • LeCun et al. (2015) + +Yann LeCun, Yoshua Bengio, and Geoffrey Hinton. 2015. + + +Deep learning. + + +nature, 521(7553):436–444. + +
  • + +
  • Li et al. (2004) + +Ming Li, Xin Chen, Xin Li, Bin Ma, and Paul MB Vitányi. 2004. + + +The similarity metric. + + +IEEE transactions on Information Theory, 50(12):3250–3264. + +
  • + +
  • Li et al. (2022) + +Qian Li, Hao Peng, Jianxin Li, Congying Xia, Renyu Yang, Lichao Sun, Philip S +Yu, and Lifang He. 2022. + + +A survey on text classification: From traditional to deep learning. + + +ACM Transactions on Intelligent Systems and Technology (TIST), +13(2):1–41. + +
  • + +
  • Marton et al. (2005) + +Yuval Marton, Ning Wu, and Lisa Hellerstein. 2005. + + +On compression-based text classification. + + +In European Conference on Information Retrieval, pages +300–314. Springer. + +
  • + +
  • Mikolov et al. (2013) + +Tomas Mikolov, Kai Chen, Greg Corrado, and Jeffrey Dean. 2013. + + +Efficient estimation of word representations in vector space. + + +arXiv preprint arXiv:1301.3781. + +
  • + +
  • Nogueira et al. (2020) + +Rodrigo Nogueira, Zhiying Jiang, Ronak Pradeep, and Jimmy Lin. 2020. + + +Document ranking with a pretrained sequence-to-sequence model. + + +In Findings of the Association for Computational Linguistics: +EMNLP 2020, pages 708–718. + +
  • + +
  • Reimers and Gurevych (2019) + +Nils Reimers and Iryna Gurevych. 2019. + + +Sentence-bert: Sentence embeddings using siamese bert-networks. + + +In Proceedings of the 2019 Conference on Empirical Methods in +Natural Language Processing and the 9th International Joint Conference on +Natural Language Processing (EMNLP-IJCNLP), pages 3982–3992. + +
  • + +
  • Russell (2010) + +Stuart J Russell. 2010. + + +Artificial intelligence a modern approach. + + +Pearson Education, Inc. + +
  • + +
  • Schuster and Paliwal (1997) + +Mike Schuster and Kuldip K Paliwal. 1997. + + +Bidirectional recurrent neural networks. + + +IEEE transactions on Signal Processing, 45(11):2673–2681. + +
  • + +
  • Shen et al. (2018) + +Dinghan Shen, Guoyin Wang, Wenlin Wang, Martin Renqiang Min, Qinliang Su, Yizhe +Zhang, Chunyuan Li, Ricardo Henao, and Lawrence Carin. 2018. + + +Baseline needs more love: On simple word-embedding-based models and +associated pooling mechanisms. + + +In Proceedings of the 56th Annual Meeting of the Association +for Computational Linguistics (Volume 1: Long Papers), pages 440–450. + +
  • + +
  • Teahan and Harper (2003) + +William J Teahan and David J Harper. 2003. + + +Using compression-based language models for text categorization. + + +In Language modeling for information retrieval, pages +141–165. Springer. + +
  • + +
  • Vitányi et al. (2009) + +Paul MB Vitányi, Frank J Balbach, Rudi L Cilibrasi, and Ming Li. 2009. + + +Normalized information distance. + + +In Information theory and statistical learning, pages 45–82. +Springer. + +
  • + +
  • Wang et al. (2016) + +Yequan Wang, Minlie Huang, Xiaoyan Zhu, and Li Zhao. 2016. + + +Attention-based lstm for aspect-level sentiment classification. + + +In Proceedings of the 2016 conference on empirical methods in +natural language processing, pages 606–615. + +
  • + +
  • Williams et al. (2018) + +Adina Williams, Nikita Nangia, and Samuel Bowman. 2018. + + +A broad-coverage challenge corpus for sentence understanding through +inference. + + +In Proceedings of the 2018 Conference of the NAACL-HLT, Volume +1 (Long Papers), pages 1112–1122, New Orleans, Louisiana. Association for +Computational Linguistics. + +
  • + +
  • Wolf et al. (2020) + +Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Clement Delangue, +Anthony Moi, Pierric Cistac, Tim Rault, Rémi Louf, Morgan Funtowicz, +et al. 2020. + + +Transformers: State-of-the-art natural language processing. + + +In Proceedings of the 2020 conference on empirical methods in +natural language processing: system demonstrations, pages 38–45. + +
  • + +
  • Yang et al. (2016) + +Zichao Yang, Diyi Yang, Chris Dyer, Xiaodong He, Alex Smola, and Eduard Hovy. +2016. + + +Hierarchical attention networks for document classification. + + +In Proceedings of the 2016 conference of the North American +chapter of the association for computational linguistics: human language +technologies, pages 1480–1489. + +
  • + +
  • Yao et al. (2019) + +Liang Yao, Chengsheng Mao, and Yuan Luo. 2019. + + +Graph convolutional networks for text classification. + + +In Proceedings of the AAAI conference on artificial +intelligence, volume 33, pages 7370–7377. + +
  • + +
  • Yu et al. (2021) + +Yaodong Yu, Heinrich Jiang, Dara Bahri, Hossein Mobahi, Seungyeon Kim, +Ankit Singh Rawat, Andreas Veit, and Yi Ma. 2021. + + +An empirical study of pre-trained vision models on +out-of-distribution generalization. + + +In NeurIPS 2021 Workshop on Distribution Shifts: Connecting +Methods and Applications. + +
  • + +
  • Zhang et al. (2021) + +Haode Zhang, Yuwei Zhang, Li-Ming Zhan, Jiaxin Chen, Guangyuan Shi, Xiao-Ming +Wu, and Albert YS Lam. 2021. + + +Effectiveness of pre-training for few-shot intent classification. + + +In Findings of the Association for Computational Linguistics: +EMNLP 2021, pages 1114–1120. + +
  • + +
  • Zhang et al. (2015) + +Xiang Zhang, Junbo Zhao, and Yann LeCun. 2015. + + +Character-level convolutional networks for text classification. + + +Advances in neural information processing systems, 28. + +
  • + +
+
+
+
+

Appendix A Derivation of NCD

+ +
+

Recall that information distance E(x,y)E(x,y) is:

+
+
+ + + + + + + + + + + + + + +
E(x,y)\displaystyle E(x,y)=max{K(x|y),K(y|x)}\displaystyle=\max\{K(x|y),K(y|x)\}(4)
=K(xy)min{K(x),K(y)}\displaystyle=K(xy)-\min\{K(x),K(y)\}(5)
+

E(x,y)E(x,y) equates the similarity between two objects with the existence of a program that can convert one to another. The simpler the converting program is, the more similar the objects are. For example, the negative of an image is very similar to the original one as the transformation can be simply described as “inverting the color of the image”.

+
+
+

In order to compare the similarity, relative distance is preferred. Vitányi et al. 2009 propose a normalized version of E(x,y)E(x,y) called Normalized Information Distance (NID).

+
+
+
Definition 1 (NID)
+
+

NID is a function: Ω×Ω[0,1]\Omega\times\Omega\rightarrow[0,1], where Ω\Omega is a non-empty set, defined as:

+ + + + + + + +
NID(x,y)=max{K(x|y),K(y|x)}max{K(x),K(y)}.\text{NID}(x,y)=\frac{\max\{K(x|y),K(y|x)\}}{\max\{K(x),K(y)\}}.(6)
+
+
+
+

Equation 6 can be interpreted as follows: Given two sequences xx, yy, K(y)K(x)K(y)\geq K(x):

+ + + + + + + +
NID(x,y)=K(y)I(x:y)K(y)=1I(x:y)K(y),\text{NID}(x,y)=\frac{K(y)-I(x:y)}{K(y)}=1-\frac{I(x:y)}{K(y)},(7)
+

where I(x:y)=K(y)K(y|x)I(x:y)=K(y)-K(y|x) means the mutual algorithmic information. I(x:y)K(y)\frac{I(x:y)}{K(y)} means the shared information (in bits) per bit of information contained in the most informative sequence, and  Equation 7 here is a specific case of Equation 6.

+
+
+

Normalized Compression Distance (NCD) is a computable version of NID based on real-world compressors. In this context, K(x)K(x) can be viewed as the length of xx after being maximally compressed. Suppose we have C(x)C(x) as the length of compressed xx produced by a real-world compressor, then NCD is defined as:

+ + + + + + + +
NCD(x,y)=C(xy)min{C(x),C(y)}max{C(x),C(y)}.\text{NCD}(x,y)=\frac{C(xy)-\min\{C(x),C(y)\}}{\max\{C(x),C(y)\}}.(8)
+
+
+

NCD is thus computable in that it not only uses compressed length to approximate K(x)K(x) but also replaces conditional Kolmogorov complexity with C(xy)C(xy) that only needs a simple concatenation of x,yx,y.

+
+
+
+

Appendix B Implementation Details

+ +
+

We use different hyper-parameters for full-dataset setting and few-shot setting.

+
+
+

For both LSTM, Bi-LSTM+Attn, fasttext, we use embedding size =256=256, dropout rate =0.3=0.3. For full-dataset setting, the learning rate is set to be 0.0010.001 and decay rate =0.9=0.9 for Adam optimizer Kingma and Ba 2015, number of epochs =20=20, with batch size =64=64; for few-shot setting, the learning rate =0.01=0.01, the decay rate =0.99=0.99, batch size =1=1, number of epochs =50=50 for 50-shot and 100-shot, epoch =80=80 for 5-shot and 10-shot. For LSTM and Bi-LSTM+Attn, we set RNN layer =1=1, hidden size =64=64. For fasttext, we use 1 hidden layer whose dimension is set to be 10.

+
+
+

For HAN, we use 1 layer for both word-level RNN and sentence-level RNN, the hidden size of both of them are set to 50, the hidden sizes of both attention layers are set to be 100. It’s trained with batch size =256=256, 0.50.5 decay rate for 66 epochs.

+
+
+

For BERT, the learning rate is set to be 2e52e-5 and the batch size is set to be 128128 for English and SogouNews while for low-resource languages, we set learning rate to be 1e51e-5 with batch size to be 16 for 5 epochs. We use transformers library for BERT’s implementation and specifically we use bert-base-uncased checkpoint for BERT and bert-base-multilingual-uncased for mBERT.

+
+
+

For charCNN and textCNN, we use the same hyper-parameters setting in Adhikari et al. 2019b except when in the few-shot learning setting, we reduce the batch size to 11, reducing the learning rate to 1e41e-4 and increase the number of epochs to 6060. +For VDCNN, we use the shallowest 99-layer version with embedding size set to be 1616, batch size set to be 6464 learning rate set to be 1e41e-4 for full-dataset setting and batch size =1=1, epoch number =60=60 for few-shot setting. For RCNN, we use embedding size =256=256, hidden size of RNN =256=256, learning rate =1e3=1e-3 and same batch size and epoch setting as VDCNN for full-dataset and few-shot settings.

+
+
+

For pre-processing, we don’t use any pre-trained word embedding for any word-based models. Neither do we use data augmentation during the training. The procedures of tokenization for both word-level and character-level, padding for batch processing are, however, inevitable.

+
+
+

For all zero-training methods, the only hyper-parameter is kk. +We set k=2k=2 for all the methods on all the datasets and we report the maximum possible accuracy getting from the experiments for each method. For Sentence-BERT, we use the “paraphrase-MiniLM-L6-v2” checkpoint.

+
+
+

For neural network methods, we use publicly available code for charCNN and textCNN implemented by Adhikari et al. 2019b, and we use Wolf et al. 2020 for BERT.

+
+
+

Our method only requires CPUs and we use 8-core CPUs to take advantage of multi-processing. The time of calculating distance matrix using gzip takes about half an hour on AGNews, two days on DBpedia and SogouNews, six days on YahooAnswers.

+
+
+

All the datasets can be downloaded from torchtext, text categorization corpora and hugging face datasets (Kinyarwanda and Kirundi News, Swahili News, Dengue Filipino).

+
+
+
+

Appendix C Few-Shot Results

+ +
+

The exact numerical value of accuracy shown in Figure 1 is listed in three tables below.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DatasetAGNews
#Shot51050100
fasttext0.273 +
+

±\pm0.021

+
0.329 +
+

±\pm0.036

+
0.550 +
+

±\pm0.008

+
0.684 +
+

±\pm0.010

+
Bi-LSTM+Attn0.269 +
+

±\pm0.022

+
0.331 +
+

±\pm0.028

+
0.549 +
+

±\pm0.028

+
0.665 +
+

±\pm0.019

+
HAN0.274 +
+

±\pm0.024

+
0.289 +
+

±\pm0.020

+
0.340 +
+

±\pm0.073

+
0.548 +
+

±\pm0.031

+
W2V0.388 +
+

±\pm0.186

+
0.546 +
+

±\pm0.162

+
0.531 +
+

±\pm0.272

+
0.395 +
+

±\pm0.089

+
BERT0.803 +
+

±\pm0.026

+
0.819 +
+

±\pm0.019

+
0.869 +
+

±\pm0.005

+
0.875 +
+

±\pm0.005

+
SentBERT0.716 +
+

±\pm0.032

+
0.746 +
+

±\pm0.018

+
0.818 +
+

±\pm0.008

+
0.829 +
+

±\pm0.004

+
gzip0.587 +
+

±\pm0.048

+
0.610 +
+

±\pm0.034

+
0.699 +
+

±\pm0.017

+
0.741 +
+

±\pm0.007

+
+
+
Table 7: Few-Shot result on AG News
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DatasetDBpedia
#Shot51050100
fasttext0.475 +
+

±\pm0.041

+
0.616 +
+

±\pm0.019

+
0.767 +
+

±\pm0.041

+
0.868 +
+

±\pm0.014

+
Bi-LSTM+Attn0.506 +
+

±\pm0.041

+
0.648 +
+

±\pm0.025

+
0.818 +
+

±\pm0.008

+
0.862 +
+

±\pm0.005

+
HAN0.350 +
+

±\pm0.012

+
0.484 +
+

±\pm0.010

+
0.501 +
+

±\pm0.003

+
0.835 +
+

±\pm0.005

+
W2V0.325 +
+

±\pm0.113

+
0.402 +
+

±\pm0.123

+
0.675 +
+

±\pm0.05

+
0.787 +
+

±\pm0.015

+
BERT0.964 +
+

±\pm0.041

+
0.979 +
+

±\pm0.007

+
0.986 +
+

±\pm0.002

+
0.987 +
+

±\pm0.001

+
SentBERT0.730 +
+

±\pm0.008

+
0.746 +
+

±\pm0.018

+
0.819 +
+

±\pm0.008

+
0.829 +
+

±\pm0.004

+
gzip0.622 +
+

±\pm0.022

+
0.701 +
+

±\pm0.021

+
0.825 +
+

±\pm0.003

+
0.857 +
+

±\pm0.004

+
+
+
Table 8: Few-Shot result on DBpedia
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DatasetSogouNews
#Shot51050100
fasttext0.545 +
+

±\pm0.053

+
0.652 +
+

±\pm0.051

+
0.782 +
+

±\pm0.034

+
0.809 +
+

±\pm0.012

+
Bi-LSTM+Attn0.534 +
+

±\pm0.042

+
0.614 +
+

±\pm0.047

+
0.771 +
+

±\pm0.021

+
0.812 +
+

±\pm0.008

+
HAN0.425 +
+

±\pm0.072

+
0.542 +
+

±\pm0.118

+
0.671 +
+

±\pm0.102

+
0.808 +
+

±\pm0.020

+
W2V0.141 +
+

±\pm0.005

+
0.124 +
+

±\pm0.048

+
0.133 +
+

±\pm0.016

+
0.395 +
+

±\pm0.089

+
BERT0.221 +
+

±\pm0.041

+
0.226 +
+

±\pm0.060

+
0.392 +
+

±\pm0.276

+
0.679 +
+

±\pm0.073

+
SentBERT0.485 +
+

±\pm0.043

+
0.501 +
+

±\pm0.041

+
0.565 +
+

±\pm0.013

+
0.572 +
+

±\pm0.003

+
gzip0.649 +
+

±\pm0.061

+
0.741 +
+

±\pm0.017

+
0.833 +
+

±\pm0.007

+
0.867 +
+

±\pm0.016

+
+
+
Table 9: Few-Shot result on SogouNews
+
+
+
+
+ +
+ + + + + diff --git a/html/math/2608_11028v2_419bae.html b/html/math/2608_11028v2_419bae.html new file mode 100644 index 0000000..fa9c7c8 --- /dev/null +++ b/html/math/2608_11028v2_419bae.html @@ -0,0 +1,726 @@ + + + +Particle Identification at Future Colliders + + + + + + + + + + + + + + + + +
+ + arXiv is now an independent nonprofit! + Learn more + +
+ +
+ + + +
+
+
+ + License: CC BY 4.0 + +
+arXiv:2608.11028v2 [hep-ex] 12 Aug 2026
+
+
+
+

[a]Roberto Preghenella

+
+

Particle Identification at Future Colliders +

+
+ +* +
+ +
Abstract
+ +

Particle identification (PID) remains a key ingredient of the physics programmes of future collider experiments. While traditional collider detectors rely on calorimetry, tracking and muon systems for particle classification, the identification of charged hadrons requires dedicated measurements of particle velocity through Cherenkov radiation, ionisation or time-of-flight techniques. Future facilities such as FCC-ee and the Electron-Ion Collider place demanding requirements on momentum coverage, detector integration and material budget, motivating the development of novel PID concepts. This contribution reviews several approaches currently under investigation, including compact Ring-Imaging Cherenkov detectors, cluster-counting drift chambers, timing-enhanced Cherenkov detectors and precision timing systems based on advanced silicon sensors. The role of emerging photodetector technologies and radiation-tolerance considerations for future collider environments is also discussed. This contribution summarises the main topics presented in the invited LHCP 2026 talk and focuses on selected representative examples rather than a comprehensive review of the field.

+ +
+
+

1 Introduction

+ +
+

Particle identification (PID) is one of the fundamental capabilities of modern particle-physics experiments [1]. Electrons, photons and muons can be efficiently identified through the characteristic signatures they leave in tracking detectors, calorimeters and muon systems. Charged hadrons, however, interact in a very similar manner inside a detector and cannot generally be distinguished solely on the basis of their energy deposition patterns. +The identification of charged pions, kaons and protons therefore requires an independent determination of the particle mass. Since the momentum is measured by the tracking system, the mass can be inferred through a measurement of the particle velocity. This principle forms the basis of most dedicated hadron-identification techniques employed in collider experiments, including Cherenkov imaging, time-of-flight measurements and ionisation-based methods [1].

+
+
+

Particle identification has played a central role in several major collider experiments. The flavour-physics programme of LHCb provides a particularly striking example of the impact of hadron identification on the reconstruction of complex final states and on the suppression of combinatorial backgrounds. Similar considerations apply to future collider facilities, where many key measurements rely on the capability to identify charged hadrons over broad momentum and angular ranges. +Future collider projects place new requirements on particle-identification systems. Future Higgs factories demand precise flavour tagging and exclusive reconstruction of hadronic final states while operating under stringent material-budget constraints [2]. The Electron–Ion Collider requires identification of charged hadrons over a broad kinematic range in order to access the three-dimensional structure of nucleons and nuclei [4]. At the same time, advances in photodetectors, precision timing and silicon technologies are opening new opportunities for detector concepts that were not feasible in previous generations of experiments.

+
+
+

This contribution provides an overview of the topics discussed in the invited talk “Particle Identification at Future Colliders” presented at LHCP 2026. Rather than attempting a comprehensive review of the field, it highlights a number of representative detector concepts and enabling technologies that illustrate current directions in the development of particle-identification systems for future collider experiments.

+
+
+
+

2 Physics Drivers for Particle Identification

+ +
+

2.1 Future Higgs Factories

+ +
Refer to caption +
Figure 1: +Invariant-mass spectra of reconstructed Λb0J/ψpK\Lambda_{b}^{0}\to J/\psi\,p\,K^{-} candidates used in pentaquark studies. The comparison between ATLAS, without dedicated hadron PID, and LHCb, with dedicated PID capabilities, illustrates the impact of particle identification on signal purity and background suppression. Adapted from Ref. [2]. +
+
+
+

Future high-luminosity electron–positron colliders such as FCC-ee, CEPC, ILC and CLIC aim to perform precision studies of the Higgs boson, electroweak observables and flavour physics. While the clean environment of lepton colliders reduces many of the experimental challenges encountered at hadron colliders, efficient identification of charged hadrons remains crucial for a number of measurements. +Several flavour-physics observables rely on the reconstruction of exclusive hadronic final states and on the separation of pions, kaons and protons. Examples include measurements of CKM matrix elements through decays such as Bs0Ds±KB_{s}^{0}\rightarrow D_{s}^{\pm}K^{\mp} , the study of heavy-flavour baryons through channels such as Λb0J/ψpK\Lambda_{b}^{0}\rightarrow J/\psi pK^{-} and searches for rare decays and exotic hadronic states [2]. In these analyses, particle identification can dramatically improve the signal-to-background ratio and reduce combinatorial ambiguities. +As illustrated in Fig. 1, dedicated hadron-identification capabilities can provide substantial improvements in reconstruction performance compared with detector systems relying solely on tracking and calorimetry. Such considerations motivate the inclusion of dedicated PID detectors in several future collider detector concepts.

+
+
+
+

2.2 The Electron–Ion Collider

+ +
Refer to caption +
Figure 2: +Particle-identification requirements at the Electron–Ion Collider. The broad momentum and rapidity coverage required for identified hadrons motivates the use of multiple complementary PID technologies. Adapted from Refs. [4, 3]. +
+
+
+

The Electron–Ion Collider will investigate the structure of nucleons and nuclei through deep-inelastic scattering over a broad range of centre-of-mass energies and momentum transfers [4]. Unlike Higgs factories, where particle identification is often used to improve the reconstruction of specific decay channels, identified hadrons constitute a primary observable of the EIC physics programme. +Semi-inclusive deep-inelastic scattering measurements require efficient separation of pions, kaons and protons in order to determine flavour-dependent parton-distribution functions, transverse-momentum-dependent distributions and fragmentation functions. Particle identification is also essential for studies of hadronisation in nuclear matter, strange-quark dynamics and exclusive processes. +Figure 2 illustrates the kinematic coverage relevant for identified hadrons in the EIC programme. No single PID technology can provide complete coverage of the required momentum and angular phase space, leading to detector concepts that combine multiple complementary techniques [3].

+
+
+
+
+

3 Compact Cherenkov Detectors for Future Colliders

+ +
+

Ring-Imaging Cherenkov (RICH) detectors remain one of the most powerful techniques for charged-hadron identification over broad momentum ranges. The measurement of the Cherenkov emission angle provides a direct determination of the particle velocity and, when combined with the momentum measured by the tracking system, allows the particle mass to be reconstructed. +Future collider experiments place increasingly stringent requirements on Cherenkov detectors. These include compact detector geometries, reduced material budgets, operation in magnetic fields, large active areas and compatibility with modern solid-state photodetectors. As a consequence, significant effort is being devoted to the development of new Cherenkov detector concepts that extend the capabilities of previous-generation systems.

+
+
+

3.1 The ePIC dual-radiator RICH

+ +
Refer to caption +
Figure 3: +Examples of compact RICH concepts for future collider experiments. +(top) The dual-radiator RICH (dRICH) detector developed for the ePIC experiment at the Electron–Ion Collider, combining aerogel and gas radiators for charged-hadron identification over a broad momentum range in the hadron-going direction. (bottom) +One cell of the ARC detector concept for future Higgs factories, where a compact dual-radiator optical system is integrated within a small radial envelope. Adapted from Refs. [5, 10]. +
+
+
+

The hadron-going region of the ePIC detector at the Electron–Ion Collider requires charged-hadron identification over a momentum range extending from a few GeV/cc up to several tens of GeV/cc. To satisfy this requirement, the ePIC detector employs a dual-radiator RICH (dRICH) detector combining aerogel and gas radiators within a compact optical system [5]. +The dRICH detector uses aerogel to provide particle identification at intermediate momenta, while a gaseous radiator extends the momentum reach towards higher values. Cherenkov photons are reflected by spherical mirrors and detected by large arrays of silicon photomultipliers (SiPMs), which offer excellent single-photon sensitivity, immunity to magnetic fields and high granularity [6, 7]. +Figure 3 illustrates the detector concept. The use of two radiators allows continuous coverage across the momentum range required by the EIC physics programme while maintaining a compact detector geometry compatible with the overall ePIC layout. +The adoption of SiPM-based photon detection represents a significant evolution with respect to previous collider RICH detectors. The large active area required by the ePIC dRICH has motivated the development of dedicated cooling systems, low-noise front-end electronics and radiation-tolerance studies aimed at ensuring long-term detector operation [8].

+
+
+
+

3.2 The ARC detector concept

+ +
+

A different set of constraints applies to future Higgs factories such as FCC-ee. In this case the experimental environment is comparatively clean, but detector concepts are often very compact and place stringent limits on radial space and material budget. Dedicated RICH detectors are therefore challenging to integrate, despite their excellent particle-identification performance.

+
+
+

The ARC concept, Array of RICH Cells, addresses this problem by replacing a single large RICH volume with an array of compact, optically independent cells [9]. It has been proposed as a compact RICH detector concept for FCC-ee and future Higgs factories, in particular in the context of detector concepts based on all-silicon tracking. The target radial envelope is of the order of 20 cm, with a material budget below about 0.1X00.1\,X_{0}. +Each ARC cell combines a dual-radiator configuration with compact focusing optics. A gaseous radiator, with C4F10 as baseline, provides high-momentum particle identification, while an aerogel radiator extends the separation power to lower momenta. The aerogel also provides thermal insulation for the photosensor plane. A spherical mirror focuses the Cherenkov light onto a highly granular photodetector array. +The ARC design exploits silicon photomultipliers as photon sensors. Their high photon-detection efficiency, fine granularity, magnetic-field compatibility and excellent timing capabilities make them attractive for compact collider RICH detectors. The relatively benign radiation environment of FCC-ee also reduces one of the main limitations associated with SiPM operation in Cherenkov applications. +Simulation studies indicate that the combination of aerogel and gas radiators can provide continuous π/K\pi/K separation at the level required for FCC-ee flavour physics, with a momentum reach extending up to about 40 GeV/cc [10]. ARC therefore illustrates how classical RICH principles can be adapted to the geometrical constraints of future compact collider detectors.

+
+
+
+

3.3 Timing-enhanced Cherenkov detectors

+ +
Refer to caption +
Figure 4: +Examples of compact Cherenkov detectors for future collider experiments. (top) High-performance DIRC detector based on fused-silica radiators and precision photon imaging. (bottom) The TORCH concept, which combines Cherenkov imaging and precision timing to provide low-momentum hadron identification. Adapted from Refs. [11, 12]. +
+
+
+

An important trend in modern Cherenkov detector development is the increasing integration of precision timing information into the reconstruction process. Traditional DIRC (Detection of Internally Reflected Cherenkov light) detectors rely primarily on photon imaging. More recent concepts exploit both photon position and photon arrival time to improve reconstruction performance and reduce ambiguities.

+
+
+

The high-performance DIRC (hpDIRC) developed for ePIC represents an evolution of this approach. The detector employs fused-silica radiators, precision optics and highly segmented photon sensors to achieve excellent angular resolution while maintaining a compact geometry suitable for collider experiments [11]. +A further development is represented by the TORCH concept, originally proposed for low-momentum hadron identification through precision time-of-flight measurements [12]. TORCH combines Cherenkov imaging and timing information by measuring the propagation time of photons inside thin quartz plates. The detector aims at timing resolutions of the order of a few tens of picoseconds per charged particle through the combination of many detected photons. +Figure 4 illustrates these two approaches. Together they exemplify the evolution of Cherenkov detectors from purely imaging devices towards systems in which timing information plays an increasingly important role in particle reconstruction.

+
+
+
+
+

4 Cluster Counting and PID in Tracking Detectors

+ +
Refer to caption +
Figure 5: +The IDEA detector concept and the cluster-counting technique. Particle identification is performed directly within the drift chamber through the measurement of the number of primary ionisation clusters rather than the total deposited energy. Adapted from Refs. [13, 14]. +
+
+
+

While Cherenkov detectors provide the highest performance over broad momentum ranges, alternative approaches seek to perform particle identification directly within the tracking detector. One of the most promising concepts in this direction is cluster counting. +Conventional gaseous tracking detectors exploit the average energy loss per unit length, dE/dxdE/dx, for particle identification. The resolution of this technique is fundamentally limited by the large fluctuations associated with the ionisation process. Cluster counting instead measures the number of primary ionisation clusters produced along the particle trajectory, thereby reducing the impact of Landau fluctuations and improving separation power.

+
+
+

The IDEA detector concept [13] for FCC-ee adopts this strategy through a large helium-based drift chamber capable of resolving individual ionisation clusters. Detailed studies have shown that cluster counting can significantly outperform conventional dE/dxdE/dx measurements, particularly in the momentum region relevant for flavour-physics applications. +Figure 5 illustrates both the IDEA detector concept and the principle of cluster counting. Analytical calculations predict excellent π/K\pi/K separation over a broad momentum range, with a narrow region around 1 GeV/cc where complementary timing information may be required. +More recently, detailed Garfield++ and Geant4 simulations have confirmed the expected performance up to momenta of approximately 20 GeV/cc. In addition, dedicated beam tests have demonstrated the feasibility of efficient cluster reconstruction using fast waveform digitisation and advanced signal-processing algorithms. These results provide important experimental validation of the cluster-counting approach and support its consideration as a PID technique for future collider detectors [14].

+
+
+
+

5 Emerging Technologies and Future Challenges

+ +
+

The requirements imposed by future collider experiments are driving rapid developments in detector technologies that extend well beyond traditional particle-identification systems. Advances in precision timing, silicon sensors and photodetectors are creating new opportunities for PID while simultaneously addressing challenges associated with detector integration, occupancy and radiation tolerance.

+
+
+

5.1 Precision Timing

+ +
+

Time-of-flight measurements have long been employed for particle identification at low and intermediate momenta. Historically, the achievable timing resolution limited their usefulness at high-energy collider experiments. Recent progress in detector technologies has dramatically changed this picture. +Over the last decade, silicon timing detectors based on the Low-Gain Avalanche Detector (LGAD) concept [15] have demonstrated a steady improvement in performance. Early devices achieved timing resolutions approaching 30 ps for minimum-ionising particles [17], while modern thin LGAD sensors routinely reach values close to 20 ps [18]. Such performance opens the possibility of extending time-of-flight techniques into momentum regions that were previously inaccessible.

+
+
+

Precision timing is also becoming an increasingly important ingredient of Cherenkov detectors. Concepts such as TORCH and timing-enhanced DIRC systems combine spatial and temporal information to improve reconstruction performance and reduce ambiguities. In future collider experiments, timing information is expected to contribute not only to event reconstruction and pile-up mitigation but also directly to particle identification.

+
+
+
+

5.2 Advanced Silicon Sensors

+ +
+

The development of advanced silicon sensors is creating new opportunities for PID systems that combine precise timing with excellent spatial resolution [16]. +A particularly promising technology is represented by AC-coupled LGADs (AC-LGADs). Unlike conventional LGADs, which provide excellent timing performance but relatively modest spatial resolution, AC-LGADs distribute the induced signal over multiple readout electrodes. This approach allows the simultaneous reconstruction of the hit position and the signal arrival time with unprecedented precision. +Recent prototypes have demonstrated spatial resolutions at the level of a few micrometres while preserving timing resolutions comparable to those achieved by conventional LGAD devices. Such capabilities make AC-LGADs attractive candidates for future tracking and timing systems where precise measurements of both space and time are required [19].

+
+
+

At the same time, developments in SPAD-based technologies and silicon photomultipliers continue to push the limits of single-photon detection. Originally developed for photon counting applications, SPAD arrays have also demonstrated excellent timing performance for charged-particle detection [20], illustrating the increasing convergence between tracking, timing and photodetection technologies.

+
+
+
+

5.3 Radiation Environment

+ +
+

The operating environment plays a crucial role in determining the suitability of a given PID technology. Future collider projects span a remarkably broad range of radiation conditions. +Future Higgs factories such as FCC-ee, CEPC and the ILC are expected to operate in comparatively benign radiation environments. Detector optimisation can therefore focus primarily on performance, material budget and integration constraints. +The situation changes significantly for hadron colliders and muon colliders. FCC-hh will operate at centre-of-mass energies approaching 100 TeV and at unprecedented luminosities, leading to very large particle fluxes and radiation levels throughout the detector volume. Technologies developed for future PID systems must therefore combine excellent performance with long-term radiation tolerance. +Radiation effects are particularly relevant for silicon photomultipliers  [21]. Increased dark-count rates, changes in gain and noise characteristics, and the need for low-temperature operation become important design considerations for large-area photon-detection systems. These issues have motivated extensive irradiation campaigns and dedicated studies aimed at understanding the long-term behaviour of modern photodetectors.

+
+
+
+

5.4 Muon Collider Considerations

+ +
+

Muon colliders present a unique detector environment among future collider proposals [22]. Unlike proton colliders, the primary collisions occur in a relatively clean lepton-collider environment. However, the finite lifetime of the circulating muon beams generates intense beam-induced backgrounds. +Electrons produced by muon decays interact with accelerator components and produce large fluxes of secondary particles that can enter the detector volume. In addition, electromagnetic interactions between the colliding beams generate large numbers of low-energy electron–positron pairs through two-photon processes. These backgrounds can contribute significantly to detector occupancy and radiation dose, particularly in the innermost detector regions [23, 24]. +As a consequence, particle-identification systems for muon colliders must be designed with particular attention to timing performance, occupancy rejection and radiation tolerance. The combination of precision timing and highly segmented detectors is expected to play a central role in mitigating beam-induced backgrounds while preserving PID performance.

+
+
+
+
+

6 Summary and Perspectives

+ +
+

Particle identification remains a key ingredient of the physics programmes of future collider experiments. Future Higgs factories and the Electron–Ion Collider place demanding and complementary requirements on detector systems, motivating the development of novel approaches to hadron identification.

+
+
+

Compact Cherenkov detectors such as the ePIC dRICH and hpDIRC demonstrate how modern photodetectors and optical designs can extend the capabilities of traditional RICH and DIRC technologies. At the same time, concepts such as TORCH illustrate the growing importance of precision timing in particle identification. An alternative direction is represented by cluster-counting drift chambers, which seek to perform PID directly within the tracking detector through measurements of primary ionisation clusters. +The rapid evolution of silicon technologies, including LGADs and AC-LGADs, is opening new opportunities for detector systems capable of combining precise timing and spatial measurements. In parallel, advances in silicon photomultipliers and SPAD-based sensors continue to expand the possibilities for photon detection in future experiments. +Finally, the increasingly diverse environments foreseen for future colliders, ranging from the relatively benign conditions of Higgs factories to the challenging backgrounds expected at FCC-hh and muon colliders, require careful consideration of radiation tolerance and detector robustness.

+
+
+

Future collider physics will continue to rely on advances in particle-identification systems and technologies. The developments reviewed in this article illustrate how innovation in detector concepts, photodetectors, timing systems and silicon sensors is shaping the next generation of PID capabilities.

+
+
+
+

References

+ +
    + +
  • [1] + +C. Lippmann, +Nucl. Instrum. Meth. A 666 (2012), 148-172 +doi:10.1016/j.nima.2011.03.009 +[arXiv:1101.3276 [hep-ex]]. + +
  • + +
  • [2] + +G. Wilkinson, +Eur. Phys. J. Plus 136 (2021) no.8, 835 +doi:10.1140/epjp/s13360-021-01810-4 +[arXiv:2106.01253 [physics.ins-det]]. + +
  • + +
  • [3] + +C. Chatterjee [ePIC], +PoS DIS2024 (2025), 266 +doi:10.22323/1.469.0266 +[arXiv:2410.20410 [physics.ins-det]]. + +
  • + +
  • [4] + +R. Abdul Khalek, A. Accardi, J. Adam, D. Adamiak, W. Akers, M. Albaladejo, A. Al-bataineh, M. G. Alexeev, F. Ameli and P. Antonioli, et al. +Nucl. Phys. A 1026 (2022), 122447 +doi:10.1016/j.nuclphysa.2022.122447 +[arXiv:2103.05419 [physics.ins-det]]. + +
  • + +
  • [5] + +M. Contalbrigo, B. R. Achari, J. Agarwala, N. Agrawal, M. Alexeev, C. Alice, R. Ammendola, S. Anjali, P. Antonioli and C. Baldanza, et al. +Nucl. Instrum. Meth. A 1088 (2026), 171537 +doi:10.1016/j.nima.2026.171537 + +
  • + +
  • [6] + +L. P. Rignanese, P. Antonioli, R. Preghenella and E. Scapparone, +Riv. Nuovo Cim. 47 (2024) no.5, 299-349 +[erratum: Riv. Nuovo Cim. 47 (2024) no.5, 351] +doi:10.1007/s40766-024-00056-x + +
  • + +
  • [7] + +R. Preghenella, M. Alexeev, P. Antonioli, C. Baldanza, L. Barion, M. Chiosso, M. Contalbrigo, F. Cossio, S. Dalla Torre and M. D. Da Rocha Rolo, et al. +Nucl. Instrum. Meth. A 1046 (2023), 167661 +doi:10.1016/j.nima.2022.167661 + +
  • + +
  • [8] + +R. Preghenella, M. Alexeev, P. Antonioli, C. Baldanza, L. Barion, M. Chiosso, M. Contalbrigo, F. Cossio, S. Dalla Torre and M. D. Da Rocha Rolo, et al. +Nucl. Instrum. Meth. A 1056 (2023), 168578 +doi:10.1016/j.nima.2023.168578 + +
  • + +
  • [9] + +R. Cardinale, et al. +https://doi.org/10.17181/6entj-pmm10 (2024) + +
  • + +
  • [10] + +S. Pezzulo, R. Cardinale, A. Tolosa-Delgado, R. Forty, S. Malde, M. Tat and G. Wilkinson, +Nucl. Instrum. Meth. A 1086 (2026), 171327 +doi:10.1016/j.nima.2026.171327 + +
  • + +
  • [11] + +G. Kalicy, +Nucl. Instrum. Meth. A 1062 (2024), 169168 +doi:10.1016/j.nima.2024.169168 + +
  • + +
  • [12] + +M. J. Charles et al. [LHCb], +Nucl. Instrum. Meth. A 639 (2011), 173-176 +doi:10.1016/j.nima.2010.09.021 +[arXiv:1009.3793 [physics.ins-det]]. + +
  • + +
  • [13] + +M. Abbrescia et al. [IDEA Study Group], +[arXiv:2502.21223 [physics.ins-det]]. + +
  • + +
  • [14] + +C. Caputo, G. Chiarello, A. Corvaglia, F. Cuna, B. D’Anzi, N. De Filippis, W. Elmetenawee, E. Gorini, F. Grancagnolo and M. Greco, et al. +Nucl. Instrum. Meth. A 1048 (2023), 167969 +doi:10.1016/j.nima.2022.167969 +[arXiv:2211.04220 [hep-ex]]. + +
  • + +
  • [15] + +H. F. W. Sadrozinski, S. Ely, V. Fadeyev, Z. Galloway, J. Ngo, C. Parker, B. Petersen, A. Seiden, A. Zatserklyaniy and N. Cartiglia, et al. +Nucl. Instrum. Meth. A 730 (2013), 226-231 +doi:10.1016/j.nima.2013.06.033 + +
  • + +
  • [16] + +R. Preghenella [ALICE], +PoS LHCP2020 (2021), 078 +doi:10.22323/1.382.0078 +[arXiv:2010.06913 [physics.ins-det]]. + +
  • + +
  • [17] + +J. Lange, M. Carulla, E. Cavallaro, L. Chytka, P. M. Davis, D. Flores, F. Förster, S. Grinstein, S. Hidalgo and T. Komarek, et al. +JINST 12 (2017) no.05, P05003 +doi:10.1088/1748-0221/12/05/P05003 +[arXiv:1703.09004 [physics.ins-det]]. + +
  • + +
  • [18] + +F. Carnesecchi, S. Strazzi, A. Alici, R. Arcidiacono, G. Borghi, M. Boscardin, N. Cartiglia, M. Centis Vignali, D. Cavazza and G. F. Dalla Betta, et al. +Eur. Phys. J. Plus 138 (2023) no.1, 99 +doi:10.1140/epjp/s13360-022-03619-1 +[arXiv:2208.05717 [physics.ins-det]]. + +
  • + +
  • [19] + +A. Apresyan, W. Chen, G. D’Amen, K. F. Di Petrillo, G. Giacomini, R. Heller, H. Lee, S. Los, C. S. Moon and A. Tricoli, +JINST 15 (2020) no.09, P09038 +doi:10.1088/1748-0221/15/09/P09038 +[arXiv:2006.01999 [physics.ins-det]]. + +
  • + +
  • [20] + +F. Carnesecchi, B. Sabiu, S. Strazzi, G. Vignola, N. Agrawal, A. Alici, P. Antonioli, S. Arcelli, F. Bellini and D. Cavazza, et al. +Eur. Phys. J. Plus 138 (2023) no.9, 788 +doi:10.1140/epjp/s13360-023-04397-0 +[arXiv:2305.17762 [physics.ins-det]]. + +
  • + +
  • [21] + +E. Garutti and Y. Musienko, +Nucl. Instrum. Meth. A 926 (2019), 69-84 +doi:10.1016/j.nima.2018.10.191 +[arXiv:1809.06361 [physics.ins-det]]. + +
  • + +
  • [22] + +C. Accettura, D. Adams, R. Agarwal, C. Ahdida, C. Aimè, N. Amapane, D. Amorim, P. Andreetto, F. Anulli and R. Appleby, et al. +Eur. Phys. J. C 83 (2023) no.9, 864 +[erratum: Eur. Phys. J. C 84 (2024) no.1, 36] +doi:10.1140/epjc/s10052-023-11889-x +[arXiv:2303.08533 [physics.acc-ph]]. + +
  • + +
  • [23] + +C. Bell et al. [MAIA], +[arXiv:2502.00181 [physics.ins-det]]. + +
  • + +
  • [24] + +P. Andreetto, N. Bartosik, A. Bersani, D. Calzolari, M. Casarsa, V. L. Ciccarella, E. Di Meco, R. Gargiulo, A. Gianelle and C. Giraldin, et al. +Eur. Phys. J. C 86 (2026) no.5, 554 +doi:10.1140/epjc/s10052-026-15654-8 +[arXiv:2511.23273 [hep-ex]]. + +
  • + +
+
+
+
+
+
+ + + + + +
+ diff --git a/html/math/2608_12173v1_cf6425.html b/html/math/2608_12173v1_cf6425.html new file mode 100644 index 0000000..25e158a --- /dev/null +++ b/html/math/2608_12173v1_cf6425.html @@ -0,0 +1,956 @@ + + + +Laboratory constraints on peV-scale mass splitting between ordinary and sterile neutron states + + + + + + + + + + + + + + + + +
+ + arXiv is now an independent nonprofit! + Learn more + +
+ +
+ + + +
+
+
+ + License: CC BY 4.0 + +
+arXiv:2608.12173v1 [hep-ex] 12 Aug 2026
+
+
+

Laboratory constraints on peV-scale mass splitting between ordinary and sterile neutron states +

+
+ +N. J. Ayres + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +   +Z. Berezhiani + +Affiliation: INFN, Laboratori Nazionali del Gran Sasso, Assergi, 67100 L’Aquila, Italy + +   +G. Bison + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +K. Bodek + +Affiliation: Marian Smoluchowski Institute of Physics, Jagiellonian University, 30-348 Cracow, Poland + +   +V. Bondar + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +   +P.-J. Chiu + +Present address: Department of Physics, National Taiwan University, 106319 Taipei, Taiwan + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +M. Daum + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +C. B. Doorenbos + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +S. Emmenegger + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +   +K. Kirch + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +V. Kletzl + +Present address: Marietta-Blau-Institute for Particle Physics, Austrian Academy of Sciences, 1010 Vienna, Austria + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +J. Krempel + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +   +B. Lauss + +Corresponding author: bernhard.lauss@psi.ch + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +D. Pais + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +I. Rienäcker + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +D. Ries + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +D. Rozpędzik + +Affiliation: Marian Smoluchowski Institute of Physics, Jagiellonian University, 30-348 Cracow, Poland + +   +P. Schmidt-Wellenburg + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +K. S. Tanaka + +Present address: Waseda University, 3-4-1 Ookubo, Shinjuku-ku, Tokyo 169-8555, Japan + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland + +   +J. Zejma + +Affiliation: Marian Smoluchowski Institute of Physics, Jagiellonian University, 30-348 Cracow, Poland + +   +N. Ziehl + +Corresponding author: ziehln@phys.ethz.ch + +Affiliation: Institute for Particle Physics and Astrophysics, ETH Zürich, 8093 Zürich, Switzerland + +   +G. Zsigmond + +Corresponding author: geza.zsigmond@psi.ch + +Affiliation: Laboratory for Particle Physics, PSI Center for Neutron and Muon Sciences, Paul Scherrer Institute (PSI), 5232 Villigen, Switzerland +
+ +
Abstract
+ +

Sterile states of matter, represented by a parallel “mirror” sector, may contribute to the observed dark matter in the Universe. We investigated the parameter space of neutron (n)(n) to mirror-neutron (n)(n^{\prime}) oscillations, in the case where the two states are not necessarily mass-degenerate, taking into account interactions in the mirror sector. By tuning the magnitude of an applied magnetic-field in the range 5 µT<B<360 µT$5\text{\,}\mathrm{\SIUnitSymbolMicro T}$<B<$360\text{\,}\mathrm{\SIUnitSymbolMicro T}$ to corresponding resonance conditions for finite mass splitting, we derive exclusion limits for the nnn-n^{\prime} oscillation time constant reaching about 20 s over the mass-difference range 0.3 - 22 peV22\text{\,}\mathrm{peV}. In parts of this parameter range, our limits exceed the model-dependent neutron-star-cooling bound, providing the first experimental constraints in this scenario that are more stringent than this astrophysical estimate.

+ +
+
+

Starting from the fifties of the last century, the existence of a parallel sector of “mirror” particles was proposed as an exact duplicate of the ordinary Standard Model (SM) particle sector [1, 2, 3, 4]. +Since then, its motivation was strengthened by considerations that cold mirror matter could account for dark matter [5, 6, 7, 8]. +Along with gravity, mirror particles might interact with ordinary matter via specific feeble interactions [9, 10]. +In particular, lepton and baryon violating cross-interactions between the ordinary and mirror particles can co-generate baryon asymmetries in both sectors and explain the observable and dark matter fractions in the Universe [11, 12]. The same interactions can induce mixing between neutral ordinary particles and their dark mirror partners as e.g. neutrino +mixing with mirror neutrinos which make the latter natural candidates for sterile neutrinos [13, 14, 15, 16]. +Interestingly, experimental bounds do not exclude a sizeable mass-mixing between the neutron and its sterile mirror partner, ϵnn+h.c.\epsilon_{nn^{\prime}}+{\rm h.c.}, +with nnn-n^{\prime} conversion time-scale much less than the neutron lifetime, τnn=/ϵnnO(1)\tau_{nn^{\prime}}=\hbar/\epsilon_{nn^{\prime}}\sim O(1) s [17, 18]. +Fast nnn\to n^{\prime} transition which violates baryon number by one unit can have +intriguing astrophysical implications [19, 20, 21, 22, 23, 24, 25]. +It evades immediate detection since under natural conditions it is suppressed by matter and magnetic field, or perhaps by some mass splitting between nn and nn^{\prime} [17, 18]. However, it can be measured under controlled experimental conditions via anomalous nnn\to n^{\prime} losses or via a regeneration process nnnn\to n^{\prime}\to n, using cold and ultracold neutrons (UCN) [17, 26, 18, 27].

+
+
+

A series of searches for anomalous UCN losses [28, 29, 30, 31, 32, 33, 34, 35] were focused on the case of exact mirror parity, when nn and nn^{\prime} are exactly degenerate in mass. Some of these experiments [30, 33] observed significant anomalies interpreted as a signal of nnn-n^{\prime} conversion in [36, 33], but the corresponding parameter space was practically excluded by the recent PSI experiment [35].

+
+
+

However, nn and nn^{\prime} can have non-zero mass splitting [5], which was invoked also to explain the neutron lifetime anomaly [37, 38, 39]. For example, spontaneous breaking of mirror parity, +motivated by asymmetric post-inflation reheating between the two sectors [40], can induce mass splitting mnmn=δm>O(1012)m_{n^{\prime}}-m_{n}=\delta m>O(10^{-12}) eV [41, 42]. +More generally, it can be mimicked by some environmental factors, such as hypothetical spin-independent long-range forces differently acting on nn and nn^{\prime} [18, 43] or even by differences in the gravitational interaction between ordinary and mirror particles in the context of modified theories of gravity [44, 45]. In theories with large extra dimensions, it can be induced by some difference between ordinary and mirror branes [46], or the neutrons can undergo mixing with finely spaced bulk fermions of the so-called Kaluza-Klein tower [47].

+
+
+

Recent experiments [48, 49, 50, 51, 52, 53, 54] set “wiggly” limits on τnn\tau_{nn^{\prime}}, reaching up to about 10 s for some narrow ranges of δm\delta m but are much weaker elsewhere. It should be noted that there is an astrophysical bound from the neutron star cooling, which is, however, model dependent and must be interpreted as an indicative order of magnitude estimate, τnn>O(10)\tau_{nn^{\prime}}>O(10) s [23, 24, 25]. This bound is important as a benchmark because it has so far been stronger than laboratory constraints in the finite-mass-splitting scenario.

+
+
+

To perform experiments with increased sensitivity, a collaboration at PSI assembled a dedicated apparatus described in [55, 56, 57]. +In this Letter, we report on a new analysis of raw data used in [35] as well as additional data sets covering larger mass splittings to further constrain the parameter space, namely, the +characteristic time τnn=/ϵnn\tau_{nn^{\prime}}=\hbar/\epsilon_{nn^{\prime}} as a function of δm\delta m. +We obtain new limits which in the range δm=3×10131×1011\delta m=3\times 10^{-13}-1\times 10^{-11} eV exceed the ones obtained in previous experiments [48, 50, 49, 51, 52, 53] as well as the astrophysical bound from neutron stars.

+
+
+

In a storage experiment, nnn\to n^{\prime} conversion would appear as a magnetic-field-dependent deficit in the number of detected UCNs, since sterile nn^{\prime} would no longer be confined by the material walls of the vessel. +The evolution of a two-state nnn-n^{\prime} system is described by the non-relativistic Hamiltonian

+ + + + + + + +
H=(EnϵnnϵnnEn).H=\begin{pmatrix}E_{n}&\epsilon_{nn^{\prime}}\\ +\epsilon_{nn^{\prime}}&E_{n^{\prime}}\end{pmatrix}.(1)
+

Here En=mn+VE_{n}=m_{n}+V, where VV is the potential induced by background matter +or a magnetic field. Analogously, En=mn+VE_{n^{\prime}}=m_{n^{\prime}}+V^{\prime}. +The difference of energy levels ΔE=EnEn\Delta E=E_{n^{\prime}}-E_{n} can be interpreted as a generalized +mass-splitting, δm=mnmn+V\delta m=m_{n^{\prime}}-m_{n}+V^{\prime}, an implicit function of the difference between the masses and an unknown potential VV^{\prime}, representing possible interactions in the mirror sector. +Solving the Schrödinger equation, the probability of nnn\to n^{\prime} transition as a function of free flight time tt between collisions becomes:

+ + + + + + + +
Pnn(t)=(2/τnn)2(Vδm)2sin2(Vδm2t).P^{nn^{\prime}}(t)=\frac{(2\hbar/\tau_{nn^{\prime}})^{2}}{(V-\delta m)^{2}}\sin^{2}\left(\frac{V-\delta m}{2\hbar}\,t\right).(2)
+

nnn\rightarrow n^{\prime} oscillations occur at maximum amplitude in case of degeneracy, when +ΔE=0\Delta E=0. This can be achieved by tuning, e.g., the magnetic field, BB, so that the +Zeeman energy V=±μnBV=\pm\mu_{n}B compensates the value of δm\delta m. +This implies that for a given sign of the mass difference only one of the neutron spin states can match the aforementioned degeneracy condition. When unpolarized UCNs are used, only half of the neutrons can oscillate into the sterile state. The propagation time, tt, resets upon wall collisions in the storage volume, since the reflected neutrons remain in the vessel and continue to oscillate, while the mirror neutrons escape.

+
+
+

In order to search for such transitions, our experiment employed tunable magnetic fields in the range of 5 µT<B<360 µT$5\text{\,}\mathrm{\SIUnitSymbolMicro T}$<B<$360\text{\,}\mathrm{\SIUnitSymbolMicro T}$. +We worked on the one hand with the asymmetry, Ai,jA_{i,j}, between neutron counts from two different i,ji,j magnetic-field settings as the experimental observable. +On the other hand, we calculated the corresponding ratio from the loss factors that might come from nnn\to n^{\prime} transitions, taking into account that neutron beta decay and neutron capture at wall collisions do not depend on the magnetic field settings. Equating the two gives

+ + + + + + + +
Aij=ninjni+nj=exp(msPinn)exp(msPjnn)exp(msPinn)+exp(msPjnn).A_{ij}=\frac{n_{i}-n_{j}}{n_{i}+n_{j}}=\frac{\exp(-m_{s}P^{nn^{\prime}}_{i})-\exp(-m_{s}P^{nn^{\prime}}_{j})}{\exp(-m_{s}P^{nn^{\prime}}_{i})+\exp(-m_{s}P^{nn^{\prime}}_{j})}.(3)
+

Here, ni,jn_{i,j} represent neutron counts after a storage time tst_{s}, when applying two magnetic fields, Bi,jB_{i,j}. During the magnetic field scan, one of the fields is meant to induce degeneracy and the other to serve as a contrasting non-degenerate reference. Pi,jnnP^{nn^{\prime}}_{i,j} is the mean probability from Eq. (2), for a free flight time between wall collisions, +and msm_{s} is the mean number of collisions of UCNs detected after storage time tst_{s}.

+
+
+

As also discussed in [35], in case of a realistic inhomogeneous magnetic field, one has to consider the local increment in the oscillation probability. This can be calculated as the product of the time derivative of the probability function in Eq. (2) and an infinitesimally short time step. The oscillation probability between two bounces, after neglecting higher order terms, becomes the sum of all infinitesimal probabilities along the path. +The total oscillation probability can be obtained by adding the probabilities between the bounces, as expressed in Eq. (3) using mean values msPi,jnnm_{s}P^{nn^{\prime}}_{i,j}. By performing detailed Monte Carlo (MC) simulations, one can more precisely calculate the cumulated probability during the storage and emptying periods, when the UCNs experience the magnetic field.

+
+
+

From the squared dependence of the probability in Eq. (2) on τnn\tau_{nn^{\prime}}, in linear approximation Eq. (3) becomes:

+ + + + + + + +
τnn=12|Aij||F(Bi,δm)F(Bj,δm)|\tau_{nn^{\prime}}=\frac{1}{\sqrt{2|\langle A_{ij}\rangle}|}\sqrt{|F(B_{i},\delta m)-F(B_{j},\delta m)|}(4)
+

The terms F(Bi,δm)F(B_{i},\delta m), which we hereafter denote as "resonance functions", +represent the cumulated oscillation probabilities (considered as 1\ll 1) for a unit τnn=1\tau_{nn^{\prime}}=1 s, and were calculated in MCUCN [58, 59, 60, 56] simulations, considering every applied magnetic-field setting separately as a function of δm\delta m [57].

+
+
+

An overview photograph and schematic of the apparatus +(used also for experiment [35]) +are shown in Fig. 1. For clarity, we briefly describe the setup installed in Area West of the PSI UCN source [61, 59, 60, 62]. During the filling period, UCNs passed through the West-1 beamport shutter (1), propagated along the Ni/Mo-coated glass guides (2), passed through the open horizontal guide shutter (3), and entered a 1 m high, 1.5 m3 large storage vessel (4) with uncoated 316L stainless-steel walls of low magnetic permeability, cleaned to minimize UCN losses using a procedure described in [63]. +The storage system was cleaned of magnetic spots (>180 µT180\text{\,}\mathrm{\SIUnitSymbolMicro T}) by abrasion and/or using a mobile demagnetization device [64], and was evacuated for the measurements. During monitoring and after storage, the neutrons were released through a fast butterfly shutter [65] (5) and counted by a 20 cm ×\times 20 cm GEM-based CASCADE [66] UCN detector (6). Eight rectangular coils (7) [67], around the vacuum tank of the storage vessel generated the target magnetic field during the storage and emptying periods. The top lid of the storage vessel (8) was temporarily opened to insert a device mapping the magnetic field in the storage volume. The setup was surrounded by concrete blocks for radiation protection (9).

+
+
+
+
Refer to caption
Refer to caption
+
Figure 1: Experimental setup: photo and schematic. Top - general view indicating the location of the main parts. Bottom - cut through the schematic (CAD): (1) West-1 beamport shutter, (2) UCN guides, (3) horizontal guide shutter, (4) storage vessel, (5) butterfly shutter, (6) UCN detector, (7) magnetic field coils perpendicular to the X, Y, Z directions, (8) top lid of the storage vessel, (9) radiation shielding (adapted from [56]).
+
+
+

The magnetic-field model providing input for the data analysis was based on dedicated mapping measurements inside the storage volume (using five FLC3-70 fluxgates from Stefan Mayer Instruments), supplemented by external three-axis fluxgate monitors (16 sensors, most of them Sensys FGM3D with an accuracy of 10 nT±$10\text{\,}\mathrm{nT}$\pm 0.1%), as described in [35]. +The measured response to the coil currents was characterized using a harmonic-polynomial field expansion detailed in [68]. The resulting coefficients provided the position-dependent magnetic field input for the MCUCN tracking calculations, which had previously been benchmarked using this experimental setup against UCN storage measurements [56].

+
+
Refer to caption +
Figure 2: UCN counts versus detection time after start of the proton-pulse typically measured during one storage measurement cycle. Five 0.1 s channels were added to reduce statistical fluctuations for better visibility. The UCN counts at ’filling’ and ’storing’ were due to a small leakage through the butterfly shutter.
+
+
+

A detailed description of the sequence of events during one measurement cycle, see Fig. 2, can be found in [35, 56]. +A storage cycle began with the UCN source proton-pulse and the filling of the storage vessel through the open beamport and experiment shutters. A short, 9 s9\text{\,}\mathrm{s} monitor interval, opening the butterfly shutter, was then recorded before the 180 s180\text{\,}\mathrm{s} storage period. Finally, the butterfly shutter was re-opened and the remaining UCNs were counted for 95 s95\text{\,}\mathrm{s}, yielding on average 1.2 million counts per cycle. All time periods were optimized around the lowest statistical uncertainty, making a compromise with the allowed operation parameters of the UCN source.

+
+
+

In the data analysis, we performed 5σ\sigma-clipping of the counts after storage (normalized with the monitor counts) to reject cycles with outliers caused by proton beam interlocks, beam-current drops, UCN source control problems, or synchronization problems with the optical link for the detector readout. Data were also rejected in case the magnetic field control system was not able to compensate for external influence. +The 5σ\sigma-clipping is justified by the assumption +that a genuine nnn-n^{\prime} signal would manifest in the form of a consistent magnetic-field-dependent drop in normalized counts, present in multiple +cycles and sequences at the same target field, and not as a single or sporadic undercount.

+
+
+

The measurements were performed within a time span of several months, during which the UCN source performance slightly drifted [69, 70]. During the data taking, the temperature of the vacuum tank was monitored by temperature sensors, which recorded both daily and seasonal fluctuations in the range of ±\pm5 °C5\text{\,}\mathrm{\SIUnitSymbolCelsius} (over the full period). +We observed, on the one hand, a daily temperature modulation in the monitor-normalized counts. +On the other hand, a close-to-linear temperature-correlated drift with a slope of 0.003 °C0.003\text{\,}\mathrm{\SIUnitSymbolCelsius}-1, which latter was corrected via re-normalization, including error propagation. +This drift could be attributed to changes with temperature of sizes of small gaps in the path of UCNs in the storage vessel and of the losses at wall reflections (see discussion in [71]), but also to the aforementioned variations in the UCN source output. All these affect the monitor and final counts slightly differently due to spectrum softening over time. The vacuum conditions were kept below 1×105\times 10^{-5} mbar, at which additional losses due to residual gases were expected to be below the statistical uncertainty of the normalized counts per cycle [56]. +To also minimize systematic errors from drifts in the UCN source yield and energy spectrum changes accompanying these, only data taken at most one day apart were combined into asymmetry values by pairing the i,j{i,j} field settings. These data groups led to a total of 832 magnetic-field setting comparisons, individually indicated by the indices i,j{i,j}.

+
+
+

The obtained asymmetries averaged over cycles Ai,j\langle A_{i,j}\rangle and the standard errors on the means δAi,j\delta\langle A_{i,j}\rangle are plotted in +Fig. 3. The mean values are distributed within the boundaries of the null hypothesis, H0H_{0}. This is represented by the 95 % C.L. of a Gaussian with a σ\sigma equal to the measured uncertainty and centered at zero. After correcting for the look-elsewhere effect with the Bonferroni procedure [72] (considering 96 independent tests, one for each magnetic field +value), anomalous UCN losses were excluded within 95% C.L.

+
+
+
Figure 3: Mean asymmetry Ai,j\langle A_{i,j}\rangle (blue dots) and the standard errors (red bars) as a function of the magnetic field differences converted into energy unit. The cyan-blue line shows the limits of the null-hypothesis H0H_{0} at 95% C.L., the black outline shows the same limit after correcting for the look-elsewhere (LE) effect. Ai,j\langle A_{i,j}\rangle is consistent with H0H_{0} within a standard error δAi,j\delta\langle A_{i,j}\rangle.
+
+
+
+
Refer to caption
Refer to caption
+
Figure 4: Top: Limits at 95% C.L. on τnn\tau_{nn^{\prime}} (linear axis) as a function of the mass splitting δm\delta m based on the results of this analysis, “PSI-2026” (purple), along with UCN beam measurements at ILL (Grenoble) (yellow [51] and cyan [73]), and the upper envelope of limits previously obtained from UCN storage measurements at PSI [34] and ILL [28, 30, 31, 33] +are shown in red. The astrophysical limit related to neutron star cooling [23, 24, 25] is indicated by the gray shade. +Bottom: Extended parameter ranges with additional limits from “regeneration” experiments STEREO [48] (blue), MURMUR [49] (green), SNS [50] (black).
+
+
+

We computed the τnn\tau_{nn^{\prime}} limits based on Eq. (4) combining Monte Carlo simulations of i,ji,j resonance function pairs and the distributions for the asymmetry i,ji,j in the UCN counts. +To obtain the latter, the asymmetry in Eq. (4) was sampled as a Gaussian distribution centered at the measured mean Ai,j\langle A_{i,j}\rangle with the standard error on this mean δAi,j\delta\langle A_{i,j}\rangle represented by the red error bars in Fig. 3. For each of the 832 Bi,jB_{i,j} field pairs, the 95 % C.L. limit for τnn\tau_{nn^{\prime}} was calculated as a function of the mass-difference δm\delta m. +In a next step, we took the upper envelope of all τnn(δm)\tau_{nn^{\prime}}(\delta m) curves, i.e. used the best sensitivity per δm\delta m value, as shown by the limit labeled “PSI-2026” in Fig. 4. +In the δm\delta m range of 6 - 22 peV22\text{\,}\mathrm{peV}, the sharp dips are caused by the widely spaced magnetic field settings, a consequence of a measurement-time compromise made to cover a larger interval and demonstrate the reach of sensitivity at higher δm\delta m values as well. +Previous results are shown for comparison: UCN and cold neutron beam experiments [50, 52, 51] and reactor measurements [48, 49], the latter ones also valid when nn and nn^{\prime} states have substantial mass splitting. The astrophysical limit τnn10\tau_{nn^{\prime}}\sim 10 s from constraints on the neutron star cooling [23, 24, 25] is partly below the results obtained in the present work. +Along the horizontal axis of Fig. 4, a possible contribution from a mirror magnetic potential is convertible as δm/\delta m/peV = B/16.58 µTB^{\prime}/$16.58\text{\,}\mathrm{\SIUnitSymbolMicro T}$.

+
+
+

To summarize, we have analyzed new and previous UCN-storage data, within a mass-splitting framework for nnn-n^{\prime} transitions. No magnetic-field-dependent loss signal was observed. The resulting 95% C.L. limits on τnn\tau_{nn^{\prime}} reach 20 s over parts of the δm\delta m interval from 0.3 to 22 peV22\text{\,}\mathrm{peV}, extending the experimental coverage of the small mass-splitting region.

+
+
+

Acknowledgments - +We thank M. Meier and L. Noorda for the excellent technical support, and are grateful for the valuable assistance of many support groups at PSI, especially the BSQ group operating the UCN source, the accelerator operating crews, the ‘Hallendienst’ and the mechanical workshops. +We acknowledge the great support from the ETH IPA and D-PHYS mechanical workshops and the vocational training division.

+
+
+

ETH and PSI appreciate the financial support from the Swiss National Science Foundation through projects 162574 (ETH), 169596 (PSI), 172626 (PSI), 172639 (ETH), 178951 (PSI), 188700 (PSI), 196416 (ETH), 200441 (ETH), 10003932 (ETH). +We further acknowledge funding from the ETH Career Seed Grant SEED-13 20-2 and the SNF spark programme grant CRSK-2_196416. +The collaborators from the Jagiellonian University Cracow wish to acknowledge support from the National Science Center, Poland, under grant No. 2016/23/D/ST2/00715, No. 2018/30/M/ST2/00319 and No. 2020/37/B/ST2/02349, and also by the Minister of Education and Science under the agreement No. 2022/WK/07. +The work of Z.B. was supported in part by the research grant No. +2022E2J4RK “PANTHEON: Perspectives in Astroparticle and +Neutrino THEory with Old and New messengers" under the program +PRIN 2022 funded by the Italian Ministero dell’Università e della +Ricerca (MUR) and by the European Union – Next Generation EU.

+
+
+

References

+ + +
+
+
+
+
+ + + + + +
+ diff --git a/html/math/index_6de724.html b/html/math/index_6de724.html new file mode 100644 index 0000000..c9d2f14 --- /dev/null +++ b/html/math/index_6de724.html @@ -0,0 +1,394 @@ + + + + + + + + Variational Autoencoders + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+

Variational autoencoders

+

+ + + + + +
+ +

Latent variable models form a rich class of probabilistic models that can infer hidden structure in the underlying data. In this post, we will study variational autoencoders, which are a powerful class of deep generative models with latent variables.

+ +

Representation

+ +

Consider a directed, latent variable model as shown below.

+ +
+drawing +
+Graphical model for a directed, latent variable model. +
+
+ +

In the model above, and denote the latent and observed variables respectively. The joint distribution expressed by this model is given as

+
+ +

From a generative modeling perspective, this model describes a generative process for the observed data using the following procedure

+
+ +

If one adopts the belief that the latent variables somehow encode semantically meaningful information about , it is natural to view this generative process as first generating the “high-level” semantic information about first before fully generating . Such a perspective motivates generative models with rich latent variable structures such as hierarchical generative models —where information about is generated hierarchically—and temporal models such as the Hidden Markov Model—where temporally-related high-level information is generated first before constructing .

+ +

We now consider a family of distributions where describes a probability distribution over . Next, consider a family of conditional distributions where describes a conditional probability distribution over given . Then our hypothesis class of generative models is the set of all possible combinations

+
+

Given a dataset , we are interested in the following learning and inference tasks

+ + + + +

Learning Directed Latent Variable Models

+ +

One way to measure how closely fits the observed dataset is to measure the Kullback-Leibler (KL) divergence between the data distribution (which we denote as ) and the model’s marginal distribution . The distribution that ``best’’ fits the data is thus obtained by minimizing the KL divergence.

+ +
+ +

As we have seen previously, optimizing an empirical estimate of the KL divergence is equivalent to maximizing the marginal log-likelihood over

+
+ +

However, it turns out this problem is generally intractable for high-dimensional as it involves an integration (or sums in the case is discrete) over all the possible latent sources of variation . One option is to estimate the objective via Monte Carlo. For any given datapoint , we can obtain the following estimate for its marginal log-likelihood

+ +
+ +

In practice however, optimizing the above estimate suffers from high variance in gradient estimates.

+ +

Rather than maximizing the log-likelihood directly, an alternate is to instead construct a lower bound that is more amenable to optimization. To do so, we note that evaluating the marginal likelihood is at least as difficult as as evaluating the posterior for any latent vector since by definition .

+ +

Next, we introduce a variational family of distributions that approximate the true, but intractable posterior . Further henceforth, we will assume a parameteric setting where any distribution in the model family is specified via a set of parameters and distributions in the variational family are specified via a set of parameters .

+ +

Given and , we note that the following relationships hold true1 for any and all variational distributions

+ +
+

where we have used Jensen’s inequality in the final step. The Evidence Lower Bound or ELBO in short admits a tractable unbiased Monte Carlo estimator

+
+

so long as it is easy to sample from and evaluate densities for .

+ +

Which variational distribution should we pick? Even though the above derivation holds for any choice of variational parameters , the tightness of the lower bound depends on the specific choice of .

+ +
+drawing +
+Illustration for the KL divergence gap between the marginal log-likelihood \(\log p_\theta(\bx)\) for a point \(\bx\) and the corresponding ELBO for a single 1D-parameter variational distribution \(q_\lambda(\bx)\). +
+
+ +

In particular, the gap between the original objective(marginal log-likelihood ) and the ELBO equals the KL divergence between the approximate posterior and the true posterior . The gap is zero when the variational distribution exactly matches .

+ +

In summary, we can learn a latent variable model by maximizing the ELBO with respect to both the model parameters and the variational parameters for any given datapoint

+
+ +

Black-Box Variational Inference

+ +

In this post, we shall focus on first-order stochastic gradient methods for optimizing the ELBO. These optimization techniques are desirable in that they allow us to sub-sample the dataset during optimization—but require our objective function to be differentiable with respect to the optimization variables. + +This inspires Black-Box Variational Inference (BBVI), a general-purpose Expectation-Maximization-like algorithm for variational learning of latent variable models, where, for each mini-batch , the following two steps are performed.

+ +

Step 1

+ +

We first do per-sample optimization of by iteratively applying the update

+
+

where , and denotes an unbiased estimate of the ELBO gradient. This step seeks to approximate the log-likelihood .

+ +

Step 2

+ +

We then perform a single update step based on the mini-batch

+
+

which corresponds to the step that hopefully moves closer to .

+ +

Gradient Estimation

+ +

The gradients and can be estimated via Monte Carlo sampling. While it is straightforward to construct an unbiased estimate of by simply pushing through the expectation operator, the same cannot be said for . Instead, we see that

+
+

This equality follows from the log-derivative trick (also commonly referred to as the REINFORCE trick). The full derivation involves some simple algebraic manipulations and is left as an exercise for the reader. The gradient estimator is thus

+
+

However, it is often noted that this estimator suffers from high variance. One of the key contributions of the variational autoencoder paper is the reparameterization trick, which introduces a fixed, auxiliary distribution and a differentiable function such that the procedure

+
+

is equivalent to sampling from . By the Law of the Unconscious Statistician, we can see that

+
+

In contrast to the REINFORCE trick, the reparameterization trick is often noted empirically to have lower variance and thus results in more stable training. +

+ +

Parameterizing Distributions via Deep Neural Networks

+ +

So far, we have described and in the abstract. To instantiate these objects, we consider choices of parametric distributions for , , and . A popular choice for is the unit Gaussian

+
+

in which case is simply the empty set since the prior is a fixed distribution. Another alternative often used in practice is a mixture of Gaussians with trainable mean and covariance parameters.

+ +

The conditional distribution is where we introduce a deep neural network. We note that a conditional distribution can be constructed by defining a distribution family (parameterized by ) in the target space (i.e. defines an unconditional distribution over ) and a mapping function . + +In other words, defines the conditional distribution

+
+

The function is also referred to as the decoding distribution since it maps a latent code to the parameters of a distribution over observed variables . In practice, it is typical to specify as a deep neural network.
+ +In the case where is a Gaussian distribution, we can thus represent it as

+
+

where and are neural networks that specify the mean and covariance matrix for the Gaussian distribution over when conditioned on .

+ +

Finally, the variational family for the proposal distribution needs to be chosen judiciously so that the reparameterization trick is possible. Many continuous distributions in the location-scale family can be reparameterized. In practice, a popular choice is again the Gaussian distribution, where

+
+

where is the Cholesky decomposition of . For simplicity, practitioners often restrict to be a diagonal matrix (which restricts the distribution family to that of factorized Gaussians).

+ +

Amortized Variational Inference

+ +

A noticable limitation of black-box variational inference is that Step 1 executes an optimization subroutine that is computationally expensive. Recall that the goal of the Step 1 is to find

+
+

For a given choice of , there is a well-defined mapping from . A key realization is that this mapping can be learned. In particular, one can train an encoding function (parameterized by ) +(where is the space of parameters) +on the following objective

+
+

It is worth noting at this point that can be interpreted as defining the conditional distribution . With a slight abuse of notation, we define

+
+

and rewrite the optimization problem as

+
+

It is also worth noting that optimizing over the entire dataset as a subroutine everytime we sample a new mini-batch is clearly not reasonable. However, if we believe that is capable of quickly adapting to a close-enough approximation of given the current choice of , then we can interleave the optimization and . The yields the following procedure, where for each mini-batch , we perform the following two updates jointly

+
+

rather than running BBVI’s Step 1 as a subroutine. By leveraging the learnability of , this optimization procedure amortizes the cost of variational inference. If one further chooses to define as a neural network, the result is the variational autoencoder.

+ +

Footnotes

+
+
    +
  1. +

    The first equality only holds if the support of includes that of . If not, it is an inequality. 

    +
  2. +
+
+ + + +
+ Variational Autoencoders - Aditya Grover + + + + diff --git a/html/math/math_8h_079059.html b/html/math/math_8h_079059.html new file mode 100644 index 0000000..2f55711 --- /dev/null +++ b/html/math/math_8h_079059.html @@ -0,0 +1,196 @@ + + + + + + + +MRSL Motion Primitive Library: include/mpl_basis/math.h File Reference + + + + + + + + + +
+
+ + + + + + +
+
MRSL Motion Primitive Library +  1.2 +
+
A motion primitive library for generating trajectory for mobile robots
+
+
+ + + + + + + + +
+
+ + +
+ +
+ + +
+
+
+Functions
+
+
math.h File Reference
+
+
+ +

Polynomial roots solver. +More...

+
#include <mpl_basis/data_type.h>
+#include <iostream>
+#include <unsupported/Eigen/Polynomials>
+
+

Go to the source code of this file.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+Functions

+decimal_t normalize_angle (decimal_t angle)
 
+std::vector< decimal_tquad (decimal_t b, decimal_t c, decimal_t d)
 Quadratic equation: $b*t^2+c*t+d = 0$.
 
+std::vector< decimal_tcubic (decimal_t a, decimal_t b, decimal_t c, decimal_t d)
 Cubic equation: $a*t^3+b*t^2+c*t+d = 0$.
 
+std::vector< decimal_tquartic (decimal_t a, decimal_t b, decimal_t c, decimal_t d, decimal_t e)
 Quartic equation: $a*t^4+b*t^3+c*t^2+d*t+e = 0$.
 
std::vector< decimal_tsolve (decimal_t a, decimal_t b, decimal_t c, decimal_t d, decimal_t e)
 General solver for $a*t^4+b*t^3+c*t^2+d*t+e = 0$. More...
 
+std::vector< decimal_tsolve (decimal_t a, decimal_t b, decimal_t c, decimal_t d, decimal_t e, decimal_t f)
 General solver for $a*t^5+b*t^4+c*t^3+d*t^2+e*t+f = 0$.
 
+std::vector< decimal_tsolve (decimal_t a, decimal_t b, decimal_t c, decimal_t d, decimal_t e, decimal_t f, decimal_t g)
 General solver for $a*t^6+b*t^5+c*t^4+d*t^3+e*t^2+f*t+g = 0$.
 
+int factorial (int n)
 Return $n!$.
 
+decimal_t power (decimal_t t, int n)
 Return $t^n$.
 
+template<typename Derived >
Derived::PlainObject pseudoInverse (Eigen::MatrixBase< Derived > const &m)
 
+template<typename Derived >
Derived::PlainObject matrixSquareRoot (Eigen::MatrixBase< Derived > const &mat, bool semidefinite_mat=false)
 
+

Detailed Description

+

Polynomial roots solver.

+

Solving real roots for n-th order polynomial: if n < 5, the closed form solution will be calculated; if n >= 5, using Eigen Polynomials solver which is slower but correct.

+

Function Documentation

+ +

◆ solve()

+ +
+
+ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
std::vector<decimal_t> solve (decimal_t a,
decimal_t b,
decimal_t c,
decimal_t d,
decimal_t e 
)
+
+inline
+
+ +

General solver for $a*t^4+b*t^3+c*t^2+d*t+e = 0$.

+

$a, b, c$ can be zero. The function itself checks the highest order of the polynomial.

+ +
+
+
+ + + + diff --git a/html/math/math_d0ba73.html b/html/math/math_d0ba73.html new file mode 100644 index 0000000..3225bdb --- /dev/null +++ b/html/math/math_d0ba73.html @@ -0,0 +1,1179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The math of Survival Analysis - PySurvival + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Skip to content + + + +
+ +
+ +
+ + + + +
+
+ + +
+
+
+ +
+
+
+ + +
+
+
+ + +
+
+
+ + +
+
+ + + + + + + + + + + +

The math of Survival Analysis

+

Now that we have introduced the main notions in Survival Analysis, let's define the variables and functions that we will be using and give simple examples to provide additional insight:

+
+

+, Survival Time

+

+ is a positive random variable representing the waiting time until an event occurs. Its probability density function (p.d.f.) is and cumulative distribution function (c.d.f.) is given by + +

+
    +
  • Example: +Let's take the example of credit risk and assume that the event of interest is fully repaying a loan. We can now analyze the cumulative distribution function of two distinct borrowers through time. +
    + + +
    Figure 1 - Comparing cumulative distribution functions
    PySurvival - Comparing cumulative distribution functions
    +
    +
    +Here, we can see that the probability that Borrower B has fully repaid his/her loan reaches 50% or 80% much faster than Borrower A's. This indicates that Borrower B is potentially less risky than Borrower A.
  • +
+
+

+, Survival function

+

+ is the probability that the event of interest has not occurred by some time + +

+
    +
  • +

    Example: +Here, we will consider the example of churn modeling, assume that the event of interest is stopping the SaaS subscription and analyze the survival function of three distinct customers through time. +

    + + +
    Figure 2 - Comparing survival functions
    PySurvival - Comparing survival functions
    +
    +
    +Here, we can see that the probability of remaining a customer reaches 50% much faster for Client C than Client B. On the other hand, Client A's probability doesn't even go below 60% from week 0 to week 15 of the analysis. In a nutshell,

    +
      +
    • Client C is very likely to churn within the first 2 weeks
    • +
    • Client B is likely to churn within the next 15 weeks
    • +
    • Client A is very likely to remain a customer within the next 15 weeks.
    • +
    +
  • +
+
+

+, hazard function and risk score

+

+ expresses the conditional probability that the event will occur within , given that it has not occurred before. + +

+

Thus, the hazard and Survival functions are linked by the following formula: + +where is the cumulative hazard function

+

However, the hazard function is rarely used in its original form. Most of the time, we subdivide the time axis in parts and calculate the risk score of a sample , such that: + +

+
    +
  • Example: Let's reuse our churn example. The previous conclusion can be translated into risk scores such that: . Indeed the faster you experience the event, the higher your risk score is.
  • +
+ + + + + + + + + +
+
+
+
+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/html/math/math_experiments_mathml_ttm_3b80f9.html b/html/math/math_experiments_mathml_ttm_3b80f9.html new file mode 100644 index 0000000..ec0bd02 --- /dev/null +++ b/html/math/math_experiments_mathml_ttm_3b80f9.html @@ -0,0 +1,664 @@ + + + + + + +Math Conversion Tests + + + + +
+

Math Conversion Tests

+ +
+

Math alphabet / Mathvariant

+

TeX's math alphabet macros change font features of (some) letters and +digits. Non-alphanumerical symbols, function names, and mathematical text +are left unchanged.

+
+
default:
+

V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}

+ +
+
mathrm:
+

\mathrm{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathbf:
+

\mathbf{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathit:
+

\mathit{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathbfit:
+

\mathbfit{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathbb:
+

\mathbb{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathcal:
+

\mathcal{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathscr:
+

\mathscr{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathfrak:
+

\mathfrak{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathsf:
+

\mathsf{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathsfit:
+

\mathsfit{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathsfbfit:
+

\mathsfbfit{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathbfsfit:
+

\mathbfsfit{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
mathtt:
+

\mathtt{V_R x \pm \cos(\alpha_\text{out}) \approx 3 \Gamma +\quad \forall x \in \mathbb{R}}

+ +
+
+

MathML 4 defines the mathvariant style attribute, in MathML core, +characters from the Mathematical Alphanumeric Symbols Unicode block +are used.

+

The mathvariants bold-script, bold-fraktur, and sans-bold are +rarely used. They are currently not supported by Docutils's native MathML +output. In LaTeX, \mathbfscr and \mathbffrac is supported by the +mathalpha package.

+

Bold variants of any symbol can be achieved in combination with the +\boldsymbol command, e.g.

+
+
bold-fraktur:
+

\boldsymbol{\mathfrak{V_R x}}

+ +
+
+

Note, that \boldsymbol emboldens also non-alphanumerical symbols.

+
+

Complex Example

+

From the baskervaldx package documentation:

+
+
Simplest form of the Central Limit Theorem:
+

Let + +X1 + +, +X2 + +, be a sequence of iid random variables with mean +0 +and variance +1 on a probability space (\Omega,\mathcal{F},\mathbb{P}). +Then

+ +
+\mathbb{P}\left(\frac{X_1+\cdots+X_n}{\sqrt{n}} \le y\right)
+\to\mathfrak{N}(y)
+\coloneq \int_{-\infty}^y
+  \frac{\mathrm{e}^{-t^2/2}}{\sqrt{2\mathrm{\pi}}}\, \mathrm{d}t
+\quad\mbox{as $n\to\infty$,}
+
+ +

or, equivalently, letting S_n\coloneq\sum_1^n X_k,

+ +
+\mathbb{E} f\left(S_n/\sqrt{n}\right)
+\to \int_{-\infty}^\infty f(t)
+  \frac{\mathrm{e}^{-t^2/2}}{\sqrt{2\mathrm{\pi}}}\, \mathrm{d}t
+\quad\mbox{as $n\to\infty$,
+  for every $f\in\mathrm{b} \mathcal{C}(\mathbb{R})$.}
+
+ +
+
+
+
+
+

Inferred <mrow>s in MathML

+

The elements <msqrt>, <mstyle>, <merror>, <mpadded>, <mphantom>, <menclose>, +<mtd>, <mscarry>, and <math> treat their contents as a single inferred mrow +formed from all their children.

+
+ + a=2+x,   b=1+ +x2 + +,   c= +sin(x) +23 + +, + +
+

inline: +a=2+x,b=1+ +x2 + +,c= +sin(x) +23 + +.

+
+
+

Scripts and Limits

+

Accents should be nearer to the base: + + +a + + +a + +, +l + + +l + +, +i + + +i + +, + + +r + + + +r + +.

+

Sub- and superscript may be given in any order: + + +xi +j += +xi +j + and + +0 +1 += +0 +1 +.

+

Double exponent: + +x +104 + + + +, + +r +Tin + + + + and + +xi + +n2 + + +.

+
+
+

Nested groups

+

tex-token returns "{" for nested groups:

+
+ + +das ist ein tollertext (unescaped { and } is +ignored by LaTeX) + + +
+
+
+

Big delimiters and symbols

+

Compare automatic sizing with fixed sizes:

+ +
+\left( 3                          \right)
+\left( f(x)                       \right)
+\left( \bar x                     \right)
+\left( \overline x                \right)
+\left( n_i                        \right) &= () \\
+\left( \underline x               \right) &= \bigl(\text{big}\bigr)\\
+\left( 3^2                        \right)
+\left( \sqrt{3}                   \right)
+\left( \sqrt{3^2}                 \right)
+\left( \sum                       \right)
+\left( \bigotimes                 \right)
+\left( \prod                      \right) &= \Bigl(\text{Big}\Bigr)\\
+\left( \frac{3  }{2}              \right)
+\left( \frac{3^2}{2^4}            \right)
+\binom{3  }{2}
+\begin{pmatrix} a & b \\ c & d \end{pmatrix}
+\left( \frac{1}{\sqrt 2}          \right)
+\left( \int                       \right)
+\left( \int_0                     \right)
+\left( \int^1                     \right)
+\left( \int_0^1                   \right) &= \biggl(\text{bigg}\biggr)\\
+\left( \frac{\sqrt 2}{2}          \right)
+\left( \sum_0                     \right)
+\left( \sum^1                     \right)
+\left( \sum_0^1                   \right)
+\left( \frac{\frac1x}{\frac{1}{n}}\right) &= \Biggl(\text{Bigg}\Biggr)\\
+\left( \intop_0                   \right)
+\left( \intop^1                   \right)
+\left( \intop_0^1                 \right)
+
+ +

And in text:

+
+
+():
+

+(3)(f(x))( +x + +)( +x + +)( +ni + +)()( +0 + +)(Π)

+
+
+ ( +big + ):
+

\left(\underline x \right) +\left( 3^2 \right) +\binom{3}{2} +\left(\begin{smallmatrix} a & b \\ +c & d \end{smallmatrix} \right) +\left( \bigotimes \right)

+ +
+
+ ( +Big + ):
+

+(3)( +32 + +)( +3 +2 + +)( + +32 + + + +24 + + + +)( +2 +2 + +)()( +0 + +)( +1 + +)( +0 +1 +)( +1 + +)( +0 +1)( + +1 +x + + + +1 +n + + + +)

+
+
+

Test \left, \right, and the bigl/bigr, … size commands +with all extensible delimiters.

+

pairing:

+
+ + (b) (b ) (b )    [b] [b ] [b ]    {b} {b } {b }    b b b + +
+
+\left.\lceil  b \right\rceil  \ \bigl\lceil  b \Bigr\rceil  \ \biggl\lceil  b \Biggr\rceil
+\quad
+\left.\lfloor b \right\rfloor \ \bigl\lfloor b \Bigr\rfloor \ \biggl\lfloor b \Biggr\rfloor
+\quad
+\left.\lvert  b \right\rvert  \ \bigl\lvert  b \Bigr\rvert  \ \biggl\lvert  b \Biggr\rvert
+\quad
+\left.\lVert  b \right\rVert  \ \bigl\lVert  b \Bigr\rVert  \ \biggl\lVert  b \Biggr\rVert
+
+ +
+\left.\lgroup b \right\rgroup \ \bigl\lgroup b \Bigr\rgroup \ \biggl\lgroup b \Biggr\rgroup
+\quad
+\left.\lmoustache b \right\rmoustache \ \bigl\lmoustache b \Bigr\rmoustache \ \biggl\lmoustache b \Biggr\rmoustache
+\quad
+\left./           b \right\backslash  \ \bigl/           b \Bigr\backslash  \ \biggl/           b \Biggr\backslash
+
+ +

non-pairing:

+
+ + |b| |b | |b |    |b| |b | |b |    b b b     b b b + +
+
+\left.\arrowvert b \right\arrowvert \ \bigl\arrowvert b \Bigr\arrowvert \ \biggl\arrowvert b \Biggr\arrowvert
+\quad
+\left.\Arrowvert b \right\Arrowvert \ \bigl\Arrowvert b \Bigr\Arrowvert \ \biggl\Arrowvert b \Biggr\Arrowvert
+\quad
+\left.\bracevert b \right\bracevert \ \bigl\bracevert b \Bigr\bracevert \ \biggl\bracevert b \Biggr\bracevert
+
+ +

Variable-sized operators:

+

Inline: \int\ \iint\ \iiint\ \iiiint\ \idotsint \oint\ \smallint\ +\sum\ \prod\ \coprod\ \bigwedge\ \bigvee\ \bigcap\ \bigcup\ \biguplus\ +\bigsqcup\ \bigodot\ \bigoplus\ \bigotimes and Display:

+ +
+\int\ \iint\ \iiint\ \iiiint\ \idotsint\ \oint\ \smallint\
+\sum\ \prod\ \coprod\ \bigwedge\ \bigvee\ \bigcap\ \bigcup\
+\biguplus\ \bigsqcup\ \bigodot\ \bigoplus\ \bigotimes
+
+ +
+\int_1 f\ \intop_1 f\ \iint_1 f\ \smallint_1 f\ \sum_1\
+\prod_1\ \bigwedge_1\ \bigcap_1\ \biguplus_1\ \bigodot_1\ \int^N\
+\intop^N\ \iiiint^N\ \oint^N\ \smallint^N\ \sum^N\ \coprod^N\
+\bigvee^N\ \bigcup^N\ \bigsqcup^N\ \bigotimes^N
+
+ +
+\int_1^N\ \intop_1^N\ \iint_1^N\ \iiint_1^N\ \iiiint_1^N\
+\idotsint_1^N\ \oint_1^N\ \smallint_1^N\ \sum_1^N\ \prod_1^N\
+\coprod_1^N\ \bigwedge_1^N\ \bigvee_1^N\ \bigcap_1^N\ \bigcup_1^N
+\ \biguplus_1^N\ \bigsqcup_1^N\ \bigodot_1^N\ \bigoplus_1^N\
+\bigotimes_1^N
+
+ +
+
+

Text

+

The text may contain non-ASCII characters: +n_ +Stoß +.

+

Some text-mode LaTeX commands are supported with math_output "html". +In other output formats, use literal Unicode: \text{ç é è ë ê ñ ů ž ©} +to get the result of the accent macros +\text{\c{c} \'e \`e \"e \^e \~n \r{u} \v{z} \textcircled{c}}.

+ + +
+
+ + diff --git a/html/math/math_output_html_378195.html b/html/math/math_output_html_378195.html new file mode 100644 index 0000000..ee5a417 --- /dev/null +++ b/html/math/math_output_html_378195.html @@ -0,0 +1,179 @@ + + + + + + +Mathematics + + + + +
+

Mathematics

+ +

Docutils supports inline math with the prefix or postfix :math: +role specificator, n! + sin(x2n) and Ac = (π)/(4)d2, as well as displayed math via the +math directive:

+
+f(ϵ) = (1)/(1 + exp(ε)/(kBT)) +
+

Content may start on the first line of the directive, e.g.

+
+N = (number of apples)/(7) +
+

Equations can be labeled with a reference name using the :name: option. +See eq:M and eq:schrödinger below.

+

The determinant of the matrix

+
+M =  + +a + + +b + + + + + +  + + +  + + + + + +c + + +d + + + + +
+

is |M| = ad − bc.

+

More than one display math block can be put in one math directive. +For example, the following sum and integral with limits:

+
+10xndx = (1)/(n + 1) +
+
+mn = 1n = (m(m + 1))/(2) +
+

LaTeX-supported Unicode math symbols can be used in math roles and +directives:

+

The Schrödinger equation

+
+iħ()/(t)Ψ = ĤΨ,  +
+

with the wave function Ψ, describes how the quantum state of a +physical system changes in time.

+
+
Math-Accents:
+
+++++ + + + + + + + + + + + + + + + + + + +
á \acute{a} \dot{t}γ̂ \hat{\gamma}
à \grave{a} \ddot{t}α̃ \tilde{\alpha}
\breve{x}t \dddot{t}ı \vec{\imath}
ǎ \check{a}a \bar{a}R \vec{R}
+
+
+ +

Modulation Transfer Function:

+
+MTF = ||(ℱ{s(x)})/(ℱ{s(x)}|ωx = 0)|| =  abs( − ∞s(x)eiωxxdx)/( − ∞s(x)dx). +
+

Math split over two lines: If a double backslash is detected outside a +\begin{...} \end{...} pair, the math code is wrapped in an AMSmath +align environment:

+
+ + +sout(x) + + + = sin(x’)*sδ(x − x’) + + + + + +  + + +  + + + + + + + + + = sin(x’)sδ(x − x’)dx’ + + + + +
+

Cases with the AMSmath cases environment:

+
+sgn(x) =  + + + − 1  + + +x < 0  + + + + + +   + + +   + + + + + + − 1  + + +x > 0  + + + + + + +
+
+ + diff --git a/html/math/math_output_mathjax_f0d3c2.html b/html/math/math_output_mathjax_f0d3c2.html new file mode 100644 index 0000000..86df802 --- /dev/null +++ b/html/math/math_output_mathjax_f0d3c2.html @@ -0,0 +1,123 @@ + + + + + + +Mathematics + + + + +
+

Mathematics

+ +

Docutils supports inline math with the prefix or postfix :math: +role specificator, \(n! + \sin(x_n^2)\) and \(A_\text{c} = +\frac{\pi}{4} d^2\), as well as displayed math via the +math directive:

+
+\begin{equation*} +f(\epsilon) = \frac{1}{1 + \exp\left(\frac{\varepsilon}{k_\text{B}T}\right)} +\end{equation*} +
+

Content may start on the first line of the directive, e.g.

+
+\begin{equation*} +N = \frac{\text{number of apples}}{7} +\end{equation*} +
+

Equations can be labeled with a reference name using the :name: option. +See eq:M and eq:schrödinger below.

+

The determinant of the matrix

+
+\begin{equation*} +\mathbf{M} = \left(\begin{matrix}a&b\\c&d\end{matrix}\right) +\end{equation*} +
+

is \(|\mathbf{M}| = ad - bc\).

+

More than one display math block can be put in one math directive. +For example, the following sum and integral with limits:

+
+\begin{equation*} +\int_0^1 x^n dx = \frac{1}{n + 1} +\end{equation*} +
+
+\begin{equation*} +\sum_{n=1}^m n = \frac{m(m+1)}{2} +\end{equation*} +
+

LaTeX-supported Unicode math symbols can be used in math roles and +directives:

+

The Schrödinger equation

+
+\begin{equation*} +i\hbar \frac{\partial }{\partial t}\Psi = \hat{H}\Psi , +\end{equation*} +
+

with the wave function \(\Psi \), describes how the quantum state of a +physical system changes in time.

+
+
Math-Accents:
+
+++++ + + + + + + + + + + + + + + + + + + +
\(\acute{a}\) \acute{a}\(\dot{t}\) \dot{t}\(\hat{\gamma}\) \hat{\gamma}
\(\grave{a}\) \grave{a}\(\ddot{t}\) \ddot{t}\(\tilde{\alpha}\) \tilde{\alpha}
\(\breve{x}\) \breve{x}\(\dddot{t}\) \dddot{t}\(\vec{\imath}\) \vec{\imath}
\(\check{a}\) \check{a}\(\bar{a}\) \bar{a}\(\vec{R}\) \vec{R}
+
+
+ +

Modulation Transfer Function:

+
+\begin{equation*} +\text{MTF} = \left|\frac{\mathcal{F}\{s(x)\}} + {\mathcal{F}\{ s(x)\} |_{\omega _{x}=0}}\right| + = \mathrm{abs}\left(\frac + {\int _{-\infty }^{\infty }s(x) \mathrm{e}^{\mathrm{i}\omega _{x}x}\mathrm{d}{x}} + {\int _{-\infty }^{\infty }s(x)\mathrm{d}{x}} + \right). +\end{equation*} +
+

Math split over two lines: If a double backslash is detected outside a +\begin{...} \end{...} pair, the math code is wrapped in an AMSmath +align environment:

+
+\begin{align*} +s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_\delta (x-x') \\ + & = \int s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x' +\end{align*} +
+

Cases with the AMSmath cases environment:

+
+\begin{equation*} +\mathrm{sgn}(x) = \begin{cases} + -1 & x<0\\ + \phantom{-} 1 & x>0 + \end{cases} +\end{equation*} +
+
+ + diff --git a/html/math/math_output_mathml_64e3ae.html b/html/math/math_output_mathml_64e3ae.html new file mode 100644 index 0000000..5ae9bc8 --- /dev/null +++ b/html/math/math_output_mathml_64e3ae.html @@ -0,0 +1,501 @@ + + + + + + +Mathematics + + + + +
+

Mathematics

+ +

Docutils supports inline math with the prefix or postfix :math: +role specificator, + n + ! + + + sin + + ( + + x + n + 2 + + ) + and + + A + c + + = + + π + 4 + + + d + 2 + +, as well as displayed math via the +math directive:

+
+ + f + ( + ϵ + ) + = + + 1 + + 1 + + + exp + + + ( + + ε + + + k + B + + T + + + ) + + + + +
+

Content may start on the first line of the directive, e.g.

+
+ + N + = + + number of apples + 7 + + +
+

Equations can be labeled with a reference name using the :name: option. +See eq:M and eq:schrödinger below.

+

The determinant of the matrix

+
+ + 𝐌 + = + + ( + + + + a + + + b + + + + + c + + + d + + + + ) + + +
+

is + | + 𝐌 + | + = + a + d + + b + c +.

+

More than one display math block can be put in one math directive. +For example, the following sum and integral with limits:

+
+ + + + 0 + 1 + + + x + n + + d + x + = + + 1 + + n + + + 1 + + + +
+
+ + + + + n + = + 1 + + m + + n + = + + + m + ( + m + + + 1 + ) + + 2 + + +
+

LaTeX-supported Unicode math symbols can be used in math roles and +directives:

+

The Schrödinger equation

+
+ + i + + + + + + t + + + Ψ + = + + H + ˆ + + Ψ + , + +
+

with the wave function + Ψ +, describes how the quantum state of a +physical system changes in time.

+
+
Math-Accents:
+
+ + + + + + + + + + + + + + + + + + +

+ + a + ´ + + \acute{a}

+ + t + ˙ + + \dot{t}

+ + γ + ˆ + + \hat{\gamma}

+ + a + ` + + \grave{a}

+ + t + ¨ + + \ddot{t}

+ + α + ~ + + \tilde{\alpha}

+ + x + ˘ + + \breve{x}

+ + t + ˙˙˙ + + \dddot{t}

+ + ı + + + \vec{\imath}

+ + a + ˇ + + \check{a}

+ + a + ˉ + + \bar{a}

+ + R + + + \vec{R}

+
+
+ +

Modulation Transfer Function:

+
+ + MTF + = + + | + + + + { + s + ( + x + ) + } + + + + { + s + ( + x + ) + } + + | + + + ω + x + + = + 0 + + + + + | + + = + abs + + ( + + + + + + + + + + + s + ( + x + ) + + e + + i + + ω + x + + x + + + d + x + + + + + + + + + + + s + ( + x + ) + d + x + + + ) + + . + +
+

Math split over two lines: If a double backslash is detected outside a +\begin{...} \end{...} pair, the math code is wrapped in an AMSmath +align environment:

+
+ + + + + + s + out + + ( + x + ) + + + = + + s + in + + ( + x + ' + ) + * + + s + δ + + ( + x + + x + ' + ) + + + + + + = + + + s + in + + ( + x + ' + ) + + s + δ + + ( + x + + x + ' + ) + d + x + ' + + + + +
+

Cases with the AMSmath cases environment:

+
+ + sgn + ( + x + ) + = + + { + + + + + 1 + + + x + < + 0 + + + + + + + + 1 + + + x + > + 0 + + + + + +
+
+ + diff --git a/html/math/mathematics_mathml_blahtexml_875f65.html b/html/math/mathematics_mathml_blahtexml_875f65.html new file mode 100644 index 0000000..7471cd2 --- /dev/null +++ b/html/math/mathematics_mathml_blahtexml_875f65.html @@ -0,0 +1,5473 @@ + + + + + + +LaTeX syntax for mathematics + + + + +
+

Docutils | Overview | About | Users | Reference | Developers

+
+
+

LaTeX syntax for mathematics

+ +
+

Abstract

+

Docutils supports mathematical content with a "math" +directive and role. The input format is LaTeX math +syntax[1] with support for literal Unicode symbols.

+
+ + +
+

1 Inline formulas and displayed equations

+

The math role can be used for inline mathematical expressions: +:math:`\psi(r) = \exp(-2r)` will produce + + ψ + ( + r + ) + = + exp + ( + - + 2 + r + ) + +. +Inside the backtics you can write anything you would write between dollar +signs in a LaTeX document. [1]

+ +

The math directive is used for displayed equations. It corresponds to +an equation* or align* environment in a LaTeX document. If you +write:

+
.. math:: \psi(r) = e^{-2r}
+

you will get:

+
+ + + ψ + ( + r + ) + = + + e + + - + 2 + r + + + + +
+

A more complex example is the definition of the Fourier transform:

+
.. math::
+   :name: Fourier transform
+
+   (\mathcal{F}f)(y)
+    = \frac{1}{\sqrt{2\pi}^{\ n}}
+      \int_{\mathbb{R}^n} f(x)\,
+      e^{-\mathrm{i} y \cdot x} \,\mathrm{d} x.
+

which is rendered as:

+
+ + + ( + F + f + ) + ( + y + ) + = + + 1 + + + 2 + π + + + + n + + + + + + + R + n + + + f + ( + x + ) + + e + + - + i + y + + x + + + + d + x + . + + +
+

The :name: option puts a label on the equation that can be +linked to by hyperlink references.

+

Displayed equations can use \\ and & for line shifts and alignments:

+
.. math::
+
+ a &= (x + y)^2         &  b &= (x - y)^2 \\
+   &= x^2 + 2xy + y^2   &    &= x^2 - 2xy + y^2
+

LaTeX output will wrap it in an align* environment. +The result is:

+
+ + + + + + a + + + = + ( + x + + + y + + ) + 2 + + + + b + + + = + ( + x + - + y + + ) + 2 + + + + + + + = + + x + 2 + + + + 2 + x + y + + + + y + 2 + + + + + = + + x + 2 + + - + 2 + x + y + + + + y + 2 + + + + + + +
+

The aligned environment can be used as a component in a containing +expression. E.g.,

+
.. math::
+  \left.
+    \begin{aligned}
+      B' & = -\partial\times E,         \\
+      E' & = \partial\times B - 4\pi j,
+    \end{aligned}
+  \right\}
+  \qquad \text{Maxwell’s equations}
+

results in

+
+ + + + + + + + + + + B + + + + + = + - + + × + E + + + + + + E + + + + + = + + × + B + - + 4 + π + j + + + + + + + + + + } + + + Maxwell’s equations. + + +
+ +
+
+

2 Mathematical symbols

+

The following tables are adapted from the first edition of +"The LaTeX Companion" (Goossens, Mittelbach, Samarin) and the +AMS Short Math Guide.

+
+

2.1 Accents and embellishments

+

The "narrow" accents are intended for a single-letter base.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ + x + ´ + +

\acute{x}

+ + t + · + +

\dot{t}

+ + x + ` + +

\grave{x}

+ + x + + +

\vec{x}

+ + v + ¯ + +

\bar{v}

+ + t + ·· + +

\ddot{t}

+ + x + ̂ + +

\hat{x}

+ + x + ˘ + +

\breve{x}

\dddot{t}

\dddot{t}

\mathring{x}

\mathring{x}

+ + x + ˇ + +

\check{x}

\ddddot{t}

\ddddot{t}

+ + n + ˜ + +

\tilde{n}

+ + + +

When adding an accent to an i or j in math, dotless variants can be +obtained with \imath and \jmath: + + ı + ̂ + +, + + 𝚥 + + +.

+

For embellishments that span multiple symbols, use:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ + + g + b + i + + ˜ + +

\widetilde{gbi}

+ + + g + b + i + + ̂ + +

\widehat{gbi}

+ + + g + b + i + + ¯ + +

\overline{gbi}

+ + + g + b + i + + ¯ + +

\underline{gbi}

+ + + g + b + i + + + +

\overbrace{gbi}

+ + + g + b + i + + + +

\underbrace{gbi}

+ + + g + b + i + + + +

\overleftarrow{gbi}

\underleftarrow{gbi}

\underleftarrow{gbi}

+ + + g + b + i + + + +

\overrightarrow{gbi}

\underrightarrow{gbi}

\underrightarrow{gbi}

+ + + g + b + i + + + +

\overleftrightarrow{gbi}

\underleftrightarrow{gbi}

\underleftrightarrow{gbi}

+ + + +
+
+

2.2 Binary operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+* +

*

+ +

\circledast

+ +

\ominus

++ +

+

+ +

\circledcirc

+ +

\oplus

+- +

-

+ +

\circleddash

+ +

\oslash

+: +

:

+ +

\cup

+ +

\otimes

+ +

\Cap

+ +

\curlyvee

+± +

\pm

+ +

\Cup

+ +

\curlywedge

+ +

\rightthreetimes

+⨿ +

\amalg

+ +

\dagger

+ +

\rtimes

+* +

\ast

+ +

\ddagger

+ +

\setminus

+ +

\bigcirc

+ +

\diamond

+ +

\smallsetminus

+ +

\bigtriangledown

+÷ +

\div

+ +

\sqcap

+ +

\bigtriangleup

+ +

\divideontimes

+ +

\sqcup

+ +

\boxdot

+ +

\dotplus

+ +

\star

+ +

\boxminus

+ +

\doublebarwedge

+× +

\times

+ +

\boxplus

+ +

\gtrdot

+ +

\triangleleft

+ +

\boxtimes

+ +

\intercal

+ +

\triangleright

+ +

\bullet

+ +

\leftthreetimes

+ +

\uplus

+ +

\cap

+ +

\lessdot

+ +

\vee

+ +

\cdot

+ +

\ltimes

+ +

\veebar

+ +

\centerdot

+ +

\mp

+ +

\wedge

+ +

\circ

+ +

\odot

+ +

\wr

+
+
+

2.3 Extensible delimiters

+

Unless you indicate otherwise, delimiters in math formulas remain at the +standard size regardless of the height of the enclosed material. To get +adaptable sizes, use \left and \right prefixes, for example + + + g + ( + A + , + B + , + Y + ) + = + f + + + ( + + A + , + B + , + X + = + + h + + [ + X + ] + + + ( + Y + ) + + ) + + + or

+
+ + + + a + n + + = + + + ( + + + 1 + 2 + + + ) + + n + + + +
+

Use . for "empty" delimiters:

+
+ + + A + = + + + + + 1 + + 1 + - + n + + + + + | + + + n + = + 0 + + + + + +
+

See also the commands for fixed delimiter sizes below.

+

The following symbols extend when used with \left and \right:

+
+

2.3.1 Pairing delimiters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ + ( + ) + +

( )

+ + + + +

\langle \rangle

+ + [ + ] + +

[ ]

+ + + + +

\lceil \rceil

+ + { + } + +

\{ \}

+ + + + +

\lfloor \rfloor

+ + | + | + +

\lvert \rvert

\lgroup \rgroup

\lgroup \rgroup

+ + + + +

\lVert \rVert

\lmoustache \rmoustache

\lmoustache \rmoustache

+ + +
+
+

2.3.2 Nonpairing delimiters

+ + + + + + + + + + + + + + + + + + + + + + + + +

+| +

|

+| +

\vert

\arrowvert

\arrowvert

+ +

\|

+ +

\Vert

\Arrowvert

\Arrowvert

+/ +

/

+ +

\backslash

\bracevert

\bracevert

+ + + +

The use of | and \| for pairs of vertical bars may produce +incorrect spacing, e.g., |k|=|-k| produces + + | + k + | + = + | + - + k + | + + and +|\sin(x)| produces + + | + sin + ( + x + ) + | + +. The pairing delimiters, e.g. + + + | + - + k + | + + and + + | + sin + ( + x + ) + | + +, prevent this problem.

+
+
+
+

2.4 Extensible vertical arrows

+ + + + + + + + + + + + +

+ + \uparrow

+ + \Uparrow

+ + \downarrow

+ + \Downarrow

+ + \updownarrow

+ + \Updownarrow

+
+
+

2.5 Functions (named operators)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+arccos +

\arccos

+gcd +

\gcd

+Pr +

\Pr

+arcsin +

\arcsin

+hom +

\hom

+proj lim +

\projlim

+arctan +

\arctan

+inf +

\inf

+sec +

\sec

+arg +

\arg

+inj lim +

\injlim

+sin +

\sin

+cos +

\cos

+ker +

\ker

+sinh +

\sinh

+cosh +

\cosh

+lg +

\lg

+sup +

\sup

+cot +

\cot

+lim +

\lim

+tan +

\tan

+coth +

\coth

+lim inf +

\liminf

+tanh +

\tanh

+csc +

\csc

+lim sup +

\limsup

+ + lim + ¯ + +

\varlimsup

+deg +

\deg

+ln +

\ln

+ + lim + ¯ + +

\varliminf

+det +

\det

+log +

\log

+ + lim + + +

\varprojlim

+dim +

\dim

+max +

\max

+ + lim + + +

\varinjlim

+exp +

\exp

+min +

\min

+

Named operators outside the above list can be typeset with +\operatorname{name}, e.g.

+
+ + + sgn + ( + - + 3 + ) + = + - + 1 + . + + +
+ +

The \DeclareMathOperator command can only be used in the +LaTeX preamble.

+
+
+

2.6 Greek letters

+

Greek letters that have Latin look-alikes are rarely used in math +formulas and not supported by LaTeX.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+Γ +

\Gamma

+α +

\alpha

+μ +

\mu

+ω +

\omega

+Δ +

\Delta

+β +

\beta

+ν +

\nu

+ϝ +

\digamma

+Λ +

\Lambda

+γ +

\gamma

+ξ +

\xi

+ε +

\varepsilon

+Φ +

\Phi

+δ +

\delta

+π +

\pi

+ϰ +

\varkappa

+Π +

\Pi

+ϵ +

\epsilon

+ρ +

\rho

+φ +

\varphi

+Ψ +

\Psi

+ζ +

\zeta

+σ +

\sigma

+ϖ +

\varpi

+Σ +

\Sigma

+η +

\eta

+τ +

\tau

+ϱ +

\varrho

+Θ +

\Theta

+θ +

\theta

+υ +

\upsilon

+ς +

\varsigma

+Υ +

\Upsilon

+ι +

\iota

+ϕ +

\phi

+ϑ +

\vartheta

+Ξ +

\Xi

+κ +

\kappa

+χ +

\chi

+Ω +

\Omega

+λ +

\lambda

+ψ +

\psi

+

In LaTeX, the default font for capital Greek letters is upright/roman. +Italic capital Greek letters can be obtained by loading a package +providing the "ISO" math style. They are used by default in MathML.

+

Individual Greek italic capitals can also be achieved preceding the +letter name with var like \varPhi: +\varGamma\ \varDelta\ \varLambda\ \varPhi\ \varPi\ \varPsi\ \varSigma\ +\varTheta\ \varUpsilon\ \varXi\ \varOmega

+ +
+
+

2.7 Letterlike symbols

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ +

\forall

+ +

\aleph

+ħ +

\hbar

+ +

\ell

+ +

\complement

+ +

\beth

+ +

\hslash

+ +

\wp

+ +

\exists

+ +

\gimel

+ +

\Im

+ +

\Re

+ +

\Finv

+ +

\daleth

+ı +

\imath

+® +

\circledR

+ +

\Game

+ +

\partial

+𝚥 +

\jmath

+ +

\circledS

+ +

\mho

+ð +

\eth

+𝕜 +

\Bbbk

+
+
+

2.8 Math alphabets

+

The TeX math alphabet macros are intended for mathematical variables +where style variations are important semantically. +They style letters and numbers with a combination of font attributes +(shape, weight, family) --- non-alphanumerical symbols, function names, +and mathematical text are left unchanged.

+

MathML uses the mathvariant style attribute or pre-styled characters +from the Mathematical Alphanumeric Symbols Unicode block.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

command

example

result

\mathrm

s_\mathrm{out}

+ + s + out + +

\mathbf

\mathbf{r}^2=x^2+y^2

+ + + r + 2 + + = + + x + 2 + + + + + y + 2 + + +

\mathit

\mathit{\sin\Gamma}

+ + sin + + Γ + +

\mathcal

\mathcal{F}f(x)

+ + F + f + ( + x + ) + +

\mathbb

\mathbb{R \subset C}

+ + R + + C + +

\mathfrak

\mathfrak{a+b}

+ + a + + + b + +

\mathsf

\mathsf x

+x +

\mathtt

\mathtt{0.12}

+ + 0 + . + 12 + +

+

The set of characters in a given "math alphabet" varies. +LaTeX may produce garbage for unsupported characters. +Additional math alphabets are defined in LaTeX packages, e.g.,

+
    +
  • \mathbfit from isomath allows vector symbols in line with the +International Standard [ISO-80000-2]. +E.g., \mathbfit{r}^2=x^2+y^2 becomes \mathbfit{r}^2=x^2+y^2.

  • +
  • Several packages, e.g. mathrsfs, define \mathscr that selects a +differently shaped "script" alphabet.

  • +
+

The listing below shows the characters supported by Unicode and +Docutils with math_output MathML. [2]

+ +
+
default:
+

+ + A + B + C + D + E + F + G + H + I + J + K + L + M + N + O + P + Q + R + S + T + U + V + W + X + Y + Z + + a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z + + ı + 𝚥 + + +{ΓΔΘΛΞΠΣΥΦΨΩ\ αβγδεζηθικλμνξπρςστυφχψω\ ϵϑϕϰϱϖϜϝ\ \partial∇} + +0123456789 +

+ +
+
mathrm:
+

+ + ABCDEFGHIJKLMNOPQRSTUVWXYZ + + abcdefghijklmnopqrstuvwxyz + + ı + 𝚥 + + +\mathrm{ΓΔΘΛΞΠΣΥΦΨΩ\ αβγδεζηθικλμνξπρςστυφχψω\ ϵϑϕϰϱϖϜϝ\ \partial∇} + +0123456789 +

+ +
+
mathbf:
+

+ + A + B + C + D + E + F + G + H + I + J + K + L + M + N + O + P + Q + R + S + T + U + V + W + X + Y + Z + + a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z + + +\mathbf{ΓΔΘΛΞΠΣΥΦΨΩ\ αβγδεζηθικλμνξπρςστυφχψω\ ϵϑϕϰϱϖϜϝ\ \partial∇} + +0123456789 +

+ +
+
mathit:
+

+ + A + B + C + D + E + F + G + H + I + J + K + L + M + N + O + P + Q + R + S + T + U + V + W + X + Y + Z + + a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z + + ı + 𝚥 + + + + + Γ + Δ + Θ + Λ + Ξ + Π + Σ + Υ + Φ + Ψ + Ω + + α + β + γ + δ + ε + ζ + η + θ + ι + κ + λ + μ + ν + ξ + π + ρ + ς + σ + τ + υ + φ + χ + ψ + ω + + ϵ + ϑ + ϕ + ϰ + ϱ + ϖ + + + + + + +0123456789 + [2]

+
+
mathbfit:
+

\mathbfit{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +\mathbfit{ΓΔΘΛΞΠΣΥΦΨΩ\ αβγδεζηθικλμνξπρςστυφχψω\ ϵϑϕϰϱϖ\ \partial∇}

+ + +
+
mathcal:
+

\mathcal{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz}

+ +
+
mathscr:
+

\mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz}

+ +
+
mathbb:
+

\mathbb{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +\mathbb{ΓΠΣ\ γπ} +\mathbb{0123456789}

+ + + +
+
mathfrak:
+

+ + A + B + C + D + E + F + G + H + I + J + K + L + M + N + O + P + Q + R + S + T + U + V + W + X + Y + Z + + a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z + +

+
+
mathsf:
+

+ + A + B + C + D + E + F + G + H + I + J + K + L + M + N + O + P + Q + R + S + T + U + V + W + X + Y + Z + + a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z + + + +0123456789 +

+
+
mathsfit:
+

\mathsfit{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz}

+ +
+
mathsfbfit:
+

\mathsfbfit{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +\mathsfbfit{ΓΔΘΛΞΠΣΥΦΨΩ\ αβγδεζηθικλμνξπρςστυφχψω\ ϵϑϕϰϱϖ\ \partial∇}

+ + +
+
mathtt:
+

+ + A + B + C + D + E + F + G + H + I + J + K + L + M + N + O + P + Q + R + S + T + U + V + W + X + Y + Z + + a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z + + + +0123456789 +

+
+
+ +

In contrast to the math alphabet selectors, \boldsymbol only +changes the font weight. It can be used to get a bold version of +any mathematical symbol:

+
+ + + + V + i + + x + ± + cos + ( + α + ) + + 3 + Γ + + x + + R + + +
+
+ + + + V + i + + x + ± + cos + ( + α + ) + + 3 + Γ + + x + + R + + +
+

It is usually ill-advised to apply \boldsymbol to more than one symbol +at a time.

+
+
+

2.9 Miscellaneous symbols

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+# +

\#

+ +

\clubsuit

+¬ +

\neg

+& +

\&

+ +

\diamondsuit

+ +

\nexists

+ +

\angle

+ +

\emptyset

+ +

\prime

+ +

\backprime

+ +

\exists

+ +

\sharp

+ +

\bigstar

+ +

\flat

+ +

\spadesuit

+ +

\blacklozenge

+ +

\forall

+ +

\sphericalangle

+ +

\blacksquare

+ +

\heartsuit

+ +

\square

+ +

\blacktriangle

+ +

\infty

+ +

\surd

+ +

\blacktriangledown

+ +

\lozenge

+ +

\top

+ +

\bot

+ +

\measuredangle

+ +

\triangle

\diagdown

\diagdown

+ +

\nabla

+ +

\triangledown

\diagup

\diagup

+ +

\natural

+Ø +

\varnothing

+ + +
+
+

2.10 Punctuation

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+. +

.

+! +

!

+ +

\vdots

+/ +

/

+? +

?

+ +

\dotsb

+| +

|

+: +

\colon [3]

\dotsc

\dotsc

+ + + + +

'

+ +

\cdots

\dotsi

\dotsi

+; +

;

+ +

\ddots

\dotsm

\dotsm

+: +

:

+ +

\ldots

\dotso

\dotso

+ + + + + +
+
+

2.11 Relation symbols

+
+

2.11.1 Arrows

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ +

\circlearrowleft

+ +

\circlearrowright

+ +

\curvearrowleft

+ +

\curvearrowright

+ +

\hookleftarrow

+ +

\hookrightarrow

+ +

\leftarrow

+ +

\rightarrow

+ +

\Leftarrow

+ +

\Rightarrow

+ +

\leftarrowtail

+ +

\rightarrowtail

+ +

\leftharpoondown

+ +

\rightharpoondown

+ +

\leftharpoonup

+ +

\rightharpoonup

+ +

\leftleftarrows

+ +

\rightrightarrows

+ +

\leftrightarrow

+ +

\Leftrightarrow

+ +

\leftrightarrows

+ +

\rightleftarrows

+ +

\leftrightharpoons

+ +

\rightleftharpoons

+ +

\leftrightsquigarrow

+ +

\rightsquigarrow

+ +

\Lleftarrow

+ +

\Rrightarrow

+ +

\longleftarrow

+ +

\longrightarrow

+ +

\Longleftarrow

+ +

\Longrightarrow

+ +

\longleftrightarrow

+ +

\Longleftrightarrow

+ +

\looparrowleft

+ +

\looparrowright

+ +

\Lsh

+ +

\Rsh

+ +

\mapsto

+ +

\longmapsto

+ +

\multimap

+ +

\nleftarrow

+ +

\nrightarrow

+ +

\nLeftarrow

+ +

\nRightarrow

+ +

\nleftrightarrow

+ +

\nLeftrightarrow

+ +

\nwarrow

+ +

\nearrow

+ +

\swarrow

+ +

\searrow

+ +

\twoheadleftarrow

+ +

\twoheadrightarrow

+ +

\upharpoonleft

+ +

\upharpoonright

+ +

\downharpoonleft

+ +

\downharpoonright

+ +

\upuparrows

+ +

\downdownarrows

+

Synonyms: + + \gets, + + \to, + + \restriction.

+
+
+

2.11.2 Comparison

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+< +

<

+ +

\geq

+ +

\ll

+ +

\prec

+= +

=

+ +

\geqq

+ +

\lll

+ +

\precapprox

+> +

>

+ +

\geqslant

+ +

\lnapprox

+ +

\preccurlyeq

+ +

\approx

+ +

\gg

\lneq

\lneq

+ +

\preceq

+ +

\approxeq

+ +

\ggg

+ +

\lneqq

+ +

\precnapprox

+ +

\asymp

+ +

\gnapprox

+ +

\lnsim

+ +

\precneqq

+ +

\backsim

\gneq

\gneq

+ +

\ncong

+ +

\precnsim

+ +

\backsimeq

+ +

\gneqq

+ +

\neq

+ +

\precsim

+ +

\bumpeq

+ +

\gnsim

+ +

\ngeq

+ +

\risingdotseq

+ +

\Bumpeq

+ +

\gtrapprox

+≧̸ +

\ngeqq

+ +

\sim

+ +

\circeq

+ +

\gtreqless

+⩾̸ +

\ngeqslant

+ +

\simeq

+ +

\cong

+ +

\gtreqqless

+ +

\ngtr

+ +

\succ

+ +

\curlyeqprec

+ +

\gtrless

+ +

\nleq

+ +

\succapprox

+ +

\curlyeqsucc

+ +

\gtrsim

+≦̸ +

\nleqq

+ +

\succcurlyeq

+ +

\doteq

+ +

\leq

+⩽̸ +

\nleqslant

+ +

\succeq

+ +

\doteqdot

+ +

\leqq

+ +

\nless

+ +

\succnapprox

+ +

\eqcirc

+ +

\leqslant

+ +

\nprec

+ +

\succneqq

+ +

\eqsim

+ +

\lessapprox

+⪯̸ +

\npreceq

+ +

\succnsim

+ +

\eqslantgtr

+ +

\lesseqgtr

+ +

\nsim

+ +

\succsim

+ +

\eqslantless

+ +

\lesseqqgtr

+ +

\nsucc

+ +

\thickapprox

+ +

\equiv

+ +

\lessgtr

+⪰̸ +

\nsucceq

+ +

\thicksim

+ +

\fallingdotseq

+ +

\lesssim

+ +

\triangleq

+ + +

The commands \lvertneqq and \gvertneqq are not supported +with MathML output, as there is no corresponding Unicode character.

+

Synonyms: + + \ne, + + \le, + + \ge, + + + \Doteq, + + \llless, + + \gggtr.

+

Symbols can be negated prepending \not, e.g. + + + \not=, + + \not\equiv, + + + + + / + + + + \not\gtrless, + + + + / + + + + \not\lessgtr.

+
+
+

2.11.3 Miscellaneous relations

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+϶ +

\backepsilon

+ +

\ntrianglelefteq

+ +

\subseteq

+ +

\because

+ +

\ntriangleright

+ +

\subseteqq

+ +

\between

+ +

\ntrianglerighteq

+ +

\subsetneq

+ +

\blacktriangleleft

+ +

\nvdash

+ +

\subsetneqq

+ +

\blacktriangleright

+ +

\nVdash

+ +

\supset

+ +

\bowtie

+ +

\nvDash

+ +

\Supset

+ +

\dashv

+ +

\nVDash

+ +

\supseteq

+ +

\frown

+ +

\parallel

+ +

\supseteqq

+ +

\in

+ +

\perp

+ +

\supsetneq

+| +

\mid

+ +

\pitchfork

+ +

\supsetneqq

+ +

\models

+ +

\propto

+ +

\therefore

+ +

\ni

+ +

\shortmid

+ +

\trianglelefteq

+ +

\nmid

+ +

\shortparallel

+ +

\trianglerighteq

+ +

\notin

+ +

\smallfrown

+ +

\varpropto

+ +

\nparallel

+ +

\smallsmile

+ +

\vartriangle

+ +

\nshortmid

+ +

\smile

+ +

\vartriangleleft

+ +

\nshortparallel

+ +

\sqsubset

+ +

\vartriangleright

+ +

\nsubseteq

+ +

\sqsubseteq

+ +

\vdash

+⫅̸ +

\nsubseteqq

+ +

\sqsupset

+ +

\Vdash

+ +

\nsupseteq

+ +

\sqsupseteq

+ +

\vDash

+⫆̸ +

\nsupseteqq

+ +

\subset

+ +

\Vvdash

+ +

\ntriangleleft

+ +

\Subset

+

Synonyms: \owns \owns.

+ +

Symbols can be negated prepending \not, e.g. + + + \not\in, + + \not\ni.

+

The commands \varsubsetneq, \varsubsetneqq, \varsupsetneq, +and \varsupsetneqq are not supported with MathML output as there is no +corresponding Unicode character.

+
+
+
+

2.12 Variable-sized operators

+ + + + + + + + + + + + + + + + + + + + + + + +

+ + \sum

+ + \prod

+ + \bigcap

+ + \bigodot

+ + \int

+ + \coprod

+ + \bigcup

+ + \bigoplus

+ + \oint

+ + \bigwedge

+ + \biguplus

+ + \bigotimes

\smallint \smallint

+ + \bigvee

+ + \bigsqcup

+ +

Larger symbols are used in displayed formulas, sum-like symbols have +indices above/below the symbol:

+
+ + + + + + n + = + 1 + + N + + + a + n + + + + 0 + 1 + + f + ( + x + ) + d + x + + + + i + = + 1 + + 10 + + + b + i + + + + +
+
+
+
+

3 Notations

+
+

3.1 Top and bottom embellishments

+

See Accents and embellishments.

+
+
+

3.2 Extensible arrows

+

xleftarrow and xrightarrow produce arrows that extend automatically to +accommodate unusually wide subscripts or superscripts. These commands +take one optional argument (the subscript) and one mandatory argument +(the superscript, possibly empty):

+
A \xleftarrow{n+\mu-1} B \xrightarrow[T]{n\pm i-1} C
+

results in

+
+A \xleftarrow{n+\mu-1} B \xrightarrow[T]{n\pm i-1} C
+
+ +
+
+

3.3 Affixing symbols to other symbols

+

In addition to the standard accents and embellishments, other symbols +can be placed above or below a base symbol with the \overset and +\underset commands. The symbol is set in "scriptstyle" (smaller font +size). For example, writing \overset{*}{X} becomes + + X + * + + +and \underset{+}{M} becomes + + M + + + +.

+
+
+

3.4 Matrices

+

The matrix and cases environments can also contain \\ and +&:

+
.. math::
+   \left ( \begin{matrix} a & b \\ c & d \end{matrix}\right)
+

Result:

+
+ + + ( + + + + + + a + + + b + + + + + c + + + d + + + + + + ) + + +
+

The environments pmatrix, bmatrix, Bmatrix, vmatrix, and +Vmatrix have (respectively) ( ), [ ], { }, | |, and + + + + + +delimiters built in, e.g.

+
+ + + + ( + + + + + + a + + + b + + + + + c + + + d + + + + + + ) + + + + [ + + + + + + a + + + b + + + + + c + + + d + + + + + + ] + + + + + + + + + + a + + + b + + + + + c + + + d + + + + + + + + + +
+

To produce a small matrix suitable for use in text, there is a +smallmatrix environment + + + ( + + + + + + a + + + b + + + + + c + + + d + + + + + + ) + + + + +that comes closer to fitting within a single text line than a normal +matrix.

+

For piecewise function definitions there is a cases environment:

+
+\mathrm{sgn}(x) = \begin{cases}
+            -1 & x<0\\
+  \phantom{-}1 & x>0
+\end{cases}
+
+ +
+
+

3.5 Spacing commands

+

Horizontal spacing of elements can be controlled with the following +commands:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ + 3 + + 4 + +

3\qquad 4

= 2em

+ + 3 + + 4 + +

3\quad 4

= 1em

+ + 3 + + 4 + +

3~4

3\nobreakspace 4

+ + 3 + + 4 + +

3\ 4

escaped space

+ + 3 + + 4 + +

3\;4

3\thickspace 4

3\:4

3\:4

3\medspace 4

+ + 3 + + 4 + +

3\,4

3\thinspace 4

+34 +

3 4

regular space [4]

+ + 3 + + 4 + +

3\!4

3\negthinspace 4

negative space [5]

3\negmedspace 4

3\negmedspace 4

3\negthickspace 4

3\negthickspace 4

3\hspace{1ex}4

3\hspace{1ex}4

custom length

3\mspace{20mu}4

3\mspace{20mu}4

custom length [6]

+ + + + + + +

There are also three commands that leave a space equal to the height and +width of its argument. For example \phantom{XXX} results in space as +wide and high as three X’s:

+
+\frac{\phantom{XXX}+1}{XXX-1}
+
+ +

The commands \hphantom and \vphantom insert space with the +width or height of the argument. They are not supported with math_output +MathML.

+
+
+

3.6 Modular arithmetic and modulo operation

+

The commands \bmod, \pmod, \mod, and \pod deal with the +special spacing conventions of the “mod” notation. [7]

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

command

example

result

\bmod

\gcd(n,m \bmod n)

+ + gcd + ( + n + , + m + mod + n + ) + +

\pmod

x\equiv y \pmod b

+ + x + + y + ( + mod + b + ) + +

\mod

x\equiv y \mod c

+ + x + + y + mod + c + +

\pod

x\equiv y \pod d

x\equiv y \pod d

+

\operatorname{mod}(m,n)

+ + mod + ( + m + , + n + ) + +

+ + +
+
+

3.7 Roots

+ + + + + + + + + + + + + + + + + + + + + +

command

example

result

\sqrt

\sqrt{x^2-1}

+ + + x + 2 + + - + 1 + +

+

\sqrt[3n]{x^2-1}

+ + + + x + 2 + + - + 1 + + + 3 + n + + +

+

\sqrt\frac{1}{2}

+ + + 1 + 2 + + +

+
+
+

3.8 Boxed formulas

+

The command \boxed puts a box around its argument:

+
+\boxed{\eta \leq C(\delta(\eta) +\Lambda_M(0,\delta))}
+
+ +
+
+ +
+

5 Delimiter sizes

+

Besides the automatic scaling of extensible delimiters with \left +and \right, there are four commands to manually select delimiters of +fixed size:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +

Sizing

no

\left

\bigl

\Bigl

\biggl

\Biggl

command

\right

\bigr

\Bigr

\biggr

\Biggr

Result

+ + ( + b + ) + ( + + c + d + + ) + +

+ + + ( + + b + + ) + + + + ( + + + c + d + + + ) + + +

+ + ( + b + ) + ( + + c + d + + ) + +

+ + ( + b + ) + ( + + c + d + + ) + +

+ + ( + b + ) + ( + + c + d + + ) + +

+ + ( + b + ) + ( + + c + d + + ) + +

+

There are two or three situations where the delimiter size is commonly +adjusted using these commands:

+

The first kind of adjustment is done for cumulative operators with +limits, such as summation signs. With \left and \right the +delimiters usually turn out larger than necessary, and using the Big +or bigg sizes instead gives better results:

+
+ + + + + [ + + + + i + + + a + i + + + + + | + + + + j + + + x + + i + j + + + + | + + p + + + ] + + + 1 + / + p + + + +  versus  + [ + + + i + + + a + i + + | + + + j + + + x + + i + j + + + + | + p + + + ] + + 1 + / + p + + + + +
+

The second kind of situation is clustered pairs of delimiters, where +left and right make them all the same size (because that is adequate to +cover the encompassed material), but what you really want is to make some +of the delimiters slightly larger to make the nesting easier to see.

+
+ + + + ( + + ( + + a + 1 + + + b + 1 + + ) + - + ( + + a + 2 + + + b + 2 + + ) + + ) + + + + ( + + ( + + a + 2 + + + b + 1 + + ) + + + ( + + a + 1 + + + b + 2 + + ) + + ) + + + versus + ( + ( + + a + 1 + + + b + 1 + + ) + - + ( + + a + 2 + + + b + 2 + + ) + ) + ( + ( + + a + 2 + + + b + 1 + + ) + + + ( + + a + 1 + + + b + 2 + + ) + ) + + +
+

The third kind of situation is a slightly oversize object in running +text, such as + + | + + + + b + + + + d + + + + + | + + where the delimiters produced +by \left and \right cause too much line spreading. [8] In that case +\bigl and \bigr can be used to produce delimiters that are larger +than the base size but still able to fit within the normal line spacing: + + + | + + + b + + + + d + + + + | + +.

+ +
+
+

6 Text

+

The main use of the command \text is for words or phrases in a +display. It is similar to \mbox in its effects but, unlike \mbox, +automatically produces subscript-size text if used in a subscript, +k_{\text{B}}T becomes + + + k + B + + T + +.

+

Whitespace is kept inside the argument:

+
+ + + + f + + [ + + x + + i + - + 1 + + + , + + x + i + + ] + + +  is monotonic for  + i + = + 1 + , + + , + c + + + 1 + + +
+

The text may contain math commands wrapped in $ signs, e.g.

+
+(-1)^{n_i} = \begin{cases} -1 \quad \text{if $n_i$ is odd,} \\
+              +1 \quad \text{if $n_i$ is even.}
+\end{cases}
+
+ + +
+
+

7 Integrals and sums

+

The limits on integrals, sums, and similar symbols are placed either to +the side of or above and below the base symbol, depending on convention +and context. In inline formulas and fractions, the limits on sums, and +similar symbols like

+
+ + + + lim + + n + + + + + + + 1 + n + + + 1 + n + + + +
+

move to index positions: + + + lim + + n + + + + + + + 1 + n + + + 1 + n + + +.

+
+

7.1 Altering the placement of limits

+

The commands \intop and \ointop produce integral signs with +limits as in sums and similar: \intop_0^1, \ointop_c and

+ + +
+\intop_0^1 \quad \ointop_c
+   \quad \text{vs.} \quad
+\int^1_0   \quad \oint_c
+
+ +

The commands \limits and \nolimits override the default placement +of the limits for any operator; \displaylimits forces standard +positioning as for the sum command. They should follow immediately after +the operator to which they apply.

+

Compare the same term with default positions, \limits, and +\nolimits in inline and display mode: + + + lim + + x + + 0 + + + f + ( + x + ) + +, + + + + lim + + x + + 0 + + + f + ( + x + ) + +, + + + lim + + x + + 0 + + + f + ( + x + ) + +, vs.

+
+ + + + lim + + x + + 0 + + + f + ( + x + ) + , + + lim + + x + + 0 + + + f + ( + x + ) + + lim + + x + + 0 + + + f + ( + x + ) + . + + +
+ + +
+
+
+

8 Changing the size of elements in a formula

+

The declarations [9] \displaystyle, \textstyle, +\scriptstyle, and \scriptscriptstyle, select a symbol size and +spacing that would be applied in display math, inline +math, first-order subscript, or second-order subscript, respectively +even when the current context would normally yield some other size.

+

For example :math:`\displaystyle \sum_{n=0}^\infty \frac{1}{n}` is printed as + + + + + n + = + 0 + + + + + 1 + n + + + +rather than + + + + + n + = + 0 + + + + + 1 + n + + + and

+
\frac{\scriptstyle\sum_{n > 0} z^n}
+{\displaystyle\prod_{1\leq k\leq n} (1-q^k)}
+

yields

+
+ + + + + + + + n + > + 0 + + + + z + n + + + + + + + 1 + + k + + n + + + ( + 1 + - + + q + k + + ) + + +  instead of the default  + + + + + + n + > + 0 + + + + z + n + + + + + + + 1 + + k + + n + + + ( + 1 + - + + q + k + + ) + + + . + + +
+ +
+
+[ISO-80000-2] +

Quantities and units – Part 2: Mathematical signs +and symbols to be used in the natural sciences and technology: +http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=31887.

+
+
+
+
+ + diff --git a/html/math/mathematics_mathml_pandoc_b65cef.html b/html/math/mathematics_mathml_pandoc_b65cef.html new file mode 100644 index 0000000..9d07f5f --- /dev/null +++ b/html/math/mathematics_mathml_pandoc_b65cef.html @@ -0,0 +1,2625 @@ + + + + + + +LaTeX syntax for mathematics + + + + +
+

Docutils | Overview | About | Users | Reference | Developers

+
+
+

LaTeX syntax for mathematics

+ +
+

Abstract

+

Docutils supports mathematical content with a "math" +directive and role. The input format is LaTeX math +syntax[1] with support for literal Unicode symbols.

+
+ + +
+

1 Inline formulas and displayed equations

+

The math role can be used for inline mathematical expressions: +:math:`\psi(r) = \exp(-2r)` will produce ψ(r)=exp(2r)\psi(r)=\exp(-2r). +Inside the backtics you can write anything you would write between dollar +signs in a LaTeX document. [1]

+ +

The math directive is used for displayed equations. It corresponds to +an equation* or align* environment in a LaTeX document. If you +write:

+
.. math:: \psi(r) = e^{-2r}
+

you will get:

+
+ψ(r)=e2r\psi(r) = e^{-2r} +
+

A more complex example is the definition of the Fourier transform:

+
.. math::
+   :name: Fourier transform
+
+   (\mathcal{F}f)(y)
+    = \frac{1}{\sqrt{2\pi}^{\ n}}
+      \int_{\mathbb{R}^n} f(x)\,
+      e^{-\mathrm{i} y \cdot x} \,\mathrm{d} x.
+

which is rendered as:

+
+(f)(y)=12πnnf(x)eiyxdx.(\mathcal{F}f)(y) + = \frac{1}{\sqrt{2\pi}^{\ n}} + \int_{\mathbb{R}^n} f(x)\, + e^{-\mathrm{i} y \cdot x} \,\mathrm{d} x. +
+

The :name: option puts a label on the equation that can be +linked to by hyperlink references.

+

Displayed equations can use \\ and & for line shifts and alignments:

+
.. math::
+
+ a &= (x + y)^2         &  b &= (x - y)^2 \\
+   &= x^2 + 2xy + y^2   &    &= x^2 - 2xy + y^2
+

LaTeX output will wrap it in an align* environment. +The result is:

+
+a=(x+y)2b=(xy)2=x2+2xy+y2=x22xy+y2\begin{aligned} +a & = (x + y)^2 & b & = (x - y)^2 \\ + & = x^2 + 2xy + y^2 & & = x^2 - 2xy + y^2\end{aligned} +
+

The aligned environment can be used as a component in a containing +expression. E.g.,

+
.. math::
+  \left.
+    \begin{aligned}
+      B' & = -\partial\times E,         \\
+      E' & = \partial\times B - 4\pi j,
+    \end{aligned}
+  \right\}
+  \qquad \text{Maxwell’s equations}
+

results in

+
+B=×EE=×B4πj}Maxwell’s equations.\left. + \begin{aligned} + B' & = -\partial\times E \\ + E' & = \partial\times B - 4\pi j + \end{aligned} +\;\right\} +\qquad \text{Maxwell’s equations.} +
+ +
+
+

2 Mathematical symbols

+

The following tables are adapted from the first edition of +"The LaTeX Companion" (Goossens, Mittelbach, Samarin) and the +AMS Short Math Guide.

+
+

2.1 Accents and embellishments

+

The "narrow" accents are intended for a single-letter base.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

x́\acute{x}

\acute{x}

ṫ\dot{t}

\dot{t}

x̀\grave{x}

\grave{x}

x\vec{x}

\vec{x}

v\bar{v}

\bar{v}

ẗ\ddot{t}

\ddot{t}

x̂\hat{x}

\hat{x}

x̆\breve{x}

\breve{x}

t\dddot{t}

\dddot{t}

x̊\mathring{x}

\mathring{x}

x̌\check{x}

\check{x}

t\ddddot{t}

\ddddot{t}

ñ\tilde{n}

\tilde{n}

+

When adding an accent to an i or j in math, dotless variants can be +obtained with \imath and \jmath: ı̂\hat \imath, ȷ\vec{\jmath}.

+

For embellishments that span multiple symbols, use:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

gbĩ\widetilde{gbi}

\widetilde{gbi}

gbî\widehat{gbi}

\widehat{gbi}

gbi¯\overline{gbi}

\overline{gbi}

gbi_\underline{gbi}

\underline{gbi}

gbi\overbrace{gbi}

\overbrace{gbi}

gbi\underbrace{gbi}

\underbrace{gbi}

gbi\overleftarrow{gbi}

\overleftarrow{gbi}

gbi\underleftarrow{gbi}

\underleftarrow{gbi}

gbi\overrightarrow{gbi}

\overrightarrow{gbi}

gbi\underrightarrow{gbi}

\underrightarrow{gbi}

gbi\overleftrightarrow{gbi}

\overleftrightarrow{gbi}

\underleftrightarrow{gbi}

\underleftrightarrow{gbi}

+ +
+
+

2.2 Binary operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

**

*

\circledast

\circledast

\ominus

\ominus

++

+

\circledcirc

\circledcirc

\oplus

\oplus

-

-

\circleddash

\circleddash

\oslash

\oslash

::

:

\cup

\cup

\otimes

\otimes

\Cap

\Cap

\curlyvee

\curlyvee

±\pm

\pm

\Cup

\Cup

\curlywedge

\curlywedge

\rightthreetimes

\rightthreetimes

\amalg

\amalg

\dagger

\dagger

\rtimes

\rtimes

*\ast

\ast

\ddagger

\ddagger

\\setminus

\setminus

\bigcirc

\bigcirc

\diamond

\diamond

\smallsetminus

\smallsetminus

\bigtriangledown

\bigtriangledown

÷\div

\div

\sqcap

\sqcap

\bigtriangleup

\bigtriangleup

\divideontimes

\divideontimes

\sqcup

\sqcup

\boxdot

\boxdot

\dotplus

\dotplus

\star

\star

\boxminus

\boxminus

\doublebarwedge

\doublebarwedge

×\times

\times

\boxplus

\boxplus

\gtrdot

\gtrdot

\triangleleft

\triangleleft

\boxtimes

\boxtimes

\intercal

\intercal

\triangleright

\triangleright

\bullet

\bullet

\leftthreetimes

\leftthreetimes

\uplus

\uplus

\cap

\cap

\lessdot

\lessdot

\vee

\vee

\cdot

\cdot

\ltimes

\ltimes

\veebar

\veebar

\centerdot

\centerdot

\mp

\mp

\wedge

\wedge

\circ

\circ

\odot

\odot

\wr

\wr

+
+
+

2.3 Extensible delimiters

+

Unless you indicate otherwise, delimiters in math formulas remain at the +standard size regardless of the height of the enclosed material. To get +adaptable sizes, use \left and \right prefixes, for example +g(A,B,Y)=f(A,B,X=h[X](Y))g(A,B,Y) = f \left(A,B,X=h^{[X]}(Y)\right) or

+
+an=(12)na_n = \left(\frac{1}{2}\right)^n +
+

Use . for "empty" delimiters:

+
+A=11n|n=0A = \left . \frac{1}{1-n}\, \right |_{n=0}^\infty +
+

See also the commands for fixed delimiter sizes below.

+

The following symbols extend when used with \left and \right:

+
+

2.3.1 Pairing delimiters

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +

()( )

( )

\langle \rangle

\langle \rangle

[][ ]

[ ]

\lceil \rceil

\lceil \rceil

{}\{ \}

\{ \}

\lfloor \rfloor

\lfloor \rfloor

||\lvert \rvert

\lvert \rvert

\lgroup \rgroup

\lgroup \rgroup

\lVert \rVert

\lVert \rVert

\lmoustache \rmoustache

\lmoustache \rmoustache

+
+
+

2.3.2 Nonpairing delimiters

+ + + + + + + + + + + + + + + + + + + + + + + + +

||

|

|\vert

\vert

\arrowvert

\arrowvert

\|

\|

\Vert

\Vert

\Arrowvert

\Arrowvert

//

/

\backslash

\backslash

\bracevert

\bracevert

+ + + +

The use of | and \| for pairs of vertical bars may produce +incorrect spacing, e.g., |k|=|-k| produces |k|=|k||k| = |-k| and +|\sin(x)| produces |sin(x)||\sin(x)|. The pairing delimiters, e.g. +|k|\lvert -k\rvert and |sin(x)|\lvert\sin(x)\rvert, prevent this problem.

+
+
+
+

2.4 Extensible vertical arrows

+ + + + + + + + + + + + +

\uparrow \uparrow

\Uparrow \Uparrow

\downarrow \downarrow

\Downarrow \Downarrow

\updownarrow \updownarrow

\Updownarrow \Updownarrow

+
+
+

2.5 Functions (named operators)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

arccos\arccos

\arccos

gcd\gcd

\gcd

Pr\Pr

\Pr

arcsin\arcsin

\arcsin

hom\hom

\hom

\projlim

\projlim

arctan\arctan

\arctan

inf\inf

\inf

sec\sec

\sec

arg\arg

\arg

\injlim

\injlim

sin\sin

\sin

cos\cos

\cos

ker\ker

\ker

sinh\sinh

\sinh

cosh\cosh

\cosh

lg\lg

\lg

sup\sup

\sup

cot\cot

\cot

lim\lim

\lim

tan\tan

\tan

coth\coth

\coth

liminf\liminf

\liminf

tanh\tanh

\tanh

csc\csc

\csc

limsup\limsup

\limsup

\varlimsup

\varlimsup

deg\deg

\deg

ln\ln

\ln

\varliminf

\varliminf

det\det

\det

log\log

\log

\varprojlim

\varprojlim

dim\dim

\dim

max\max

\max

\varinjlim

\varinjlim

exp\exp

\exp

min\min

\min

+ + + + + + +

Named operators outside the above list can be typeset with +\operatorname{name}, e.g.

+
+sgn(3)=1.\operatorname{sgn}(-3) = -1. +
+ +

The \DeclareMathOperator command can only be used in the +LaTeX preamble.

+
+
+

2.6 Greek letters

+

Greek letters that have Latin look-alikes are rarely used in math +formulas and not supported by LaTeX.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Γ\Gamma

\Gamma

α\alpha

\alpha

μ\mu

\mu

ω\omega

\omega

Δ\Delta

\Delta

β\beta

\beta

ν\nu

\nu

ϝ\digamma

\digamma

Λ\Lambda

\Lambda

γ\gamma

\gamma

ξ\xi

\xi

ε\varepsilon

\varepsilon

Φ\Phi

\Phi

δ\delta

\delta

π\pi

\pi

𝜘\varkappa

\varkappa

Π\Pi

\Pi

ϵ\epsilon

\epsilon

ρ\rho

\rho

φ\varphi

\varphi

Ψ\Psi

\Psi

ζ\zeta

\zeta

σ\sigma

\sigma

ϖ\varpi

\varpi

Σ\Sigma

\Sigma

η\eta

\eta

τ\tau

\tau

𝜚\varrho

\varrho

Θ\Theta

\Theta

θ\theta

\theta

υ\upsilon

\upsilon

ς\varsigma

\varsigma

Υ\Upsilon

\Upsilon

ι\iota

\iota

ϕ\phi

\phi

ϑ\vartheta

\vartheta

Ξ\Xi

\Xi

κ\kappa

\kappa

χ\chi

\chi

Ω\Omega

\Omega

λ\lambda

\lambda

ψ\psi

\psi

+

In LaTeX, the default font for capital Greek letters is upright/roman. +Italic capital Greek letters can be obtained by loading a package +providing the "ISO" math style. They are used by default in MathML.

+

Individual Greek italic capitals can also be achieved preceding the +letter name with var like \varPhi: +\varGamma\ \varDelta\ \varLambda\ \varPhi\ \varPi\ \varPsi\ \varSigma\ +\varTheta\ \varUpsilon\ \varXi\ \varOmega

+ +
+
+

2.7 Letterlike symbols

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

\forall

\forall

\aleph

\aleph

\hbar

\hbar

\ell

\ell

\complement

\complement

\beth

\beth

\hslash

\hslash

\wp

\wp

\exists

\exists

\gimel

\gimel

\Im

\Im

\Re

\Re

\Finv

\Finv

\daleth

\daleth

ı\imath

\imath

®\circledR

\circledR

\Game

\Game

\partial

\partial

ȷ\jmath

\jmath

\circledS

\circledS

\mho

\mho

ð\eth

\eth

𝕜\Bbbk

\Bbbk

+ +
+
+

2.8 Math alphabets

+

The TeX math alphabet macros are intended for mathematical variables +where style variations are important semantically. +They style letters and numbers with a combination of font attributes +(shape, weight, family) --- non-alphanumerical symbols, function names, +and mathematical text are left unchanged.

+

MathML uses the mathvariant style attribute or pre-styled characters +from the Mathematical Alphanumeric Symbols Unicode block.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

command

example

result

\mathrm

s_\mathrm{out}

souts_\mathrm{out}

\mathbf

\mathbf{r}^2=x^2+y^2

𝐫2=x2+y2\mathbf{r}^2=x^2+y^2

\mathit

\mathit{\sin\Gamma}

sin𝛤\mathit{\sin\Gamma}

\mathcal

\mathcal{F}f(x)

f(x)\mathcal{F}f(x)

\mathbb

\mathbb{R \subset C}

\mathbb{R \subset C}

\mathfrak

\mathfrak{a+b}

𝔞+𝔟\mathfrak{a+b}

\mathsf

\mathsf x

𝗑\mathsf x

\mathtt

\mathtt{0.12}

0.12\mathtt{0.12}

+

The set of characters in a given "math alphabet" varies. +LaTeX may produce garbage for unsupported characters. +Additional math alphabets are defined in LaTeX packages, e.g.,

+
    +
  • \mathbfit from isomath allows vector symbols in line with the +International Standard [ISO-80000-2]. +E.g., \mathbfit{r}^2=x^2+y^2 becomes 𝒓2=x2+y2\mathbfit{r}^2=x^2+y^2.

  • +
  • Several packages, e.g. mathrsfs, define \mathscr that selects a +differently shaped "script" alphabet.

  • +
+

The listing below shows the characters supported by Unicode and +Docutils with math_output MathML. [2]

+
+
default:
+

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzıȷ{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ \imath \jmath} +ΓΔΘΛΞΠΣΥΦΨΩαβγδεζηθικλμνξπρςστυφχψωϵϑϕ𝜘𝜚ϖϜϝ{\Gamma \Delta \Theta \Lambda \Xi \Pi \Sigma \Upsilon \Phi \Psi \Omega \ \alpha \beta \gamma \delta \varepsilon \zeta \eta \theta \iota \kappa \lambda \mu \nu \xi \pi \rho \varsigma \sigma \tau \upsilon \varphi \chi \psi \omega \ \epsilon \vartheta \phi \varkappa \varrho \varpi Ϝ\digamma \ \partial\nabla } +0123456789{0123456789}

+
+
mathrm:
+

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzıȷ\mathrm{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ \imath \jmath} +ΓΔΘΛΞΠΣΥΦΨΩαβγδεζηθικλμνξπρςστυφχψωϵϑϕ𝜘𝜚ϖϜϝ\mathrm{\Gamma \Delta \Theta \Lambda \Xi \Pi \Sigma \Upsilon \Phi \Psi \Omega \ \alpha \beta \gamma \delta \varepsilon \zeta \eta \theta \iota \kappa \lambda \mu \nu \xi \pi \rho \varsigma \sigma \tau \upsilon \varphi \chi \psi \omega \ \epsilon \vartheta \phi \varkappa \varrho \varpi Ϝ\digamma \ \partial\nabla } +0123456789\mathrm{0123456789}

+
+
mathbf:
+

𝐀𝐁𝐂𝐃𝐄𝐅𝐆𝐇𝐈𝐉𝐊𝐋𝐌𝐍𝐎𝐏𝐐𝐑𝐒𝐓𝐔𝐕𝐖𝐗𝐘𝐙𝐚𝐛𝐜𝐝𝐞𝐟𝐠𝐡𝐢𝐣𝐤𝐥𝐦𝐧𝐨𝐩𝐪𝐫𝐬𝐭𝐮𝐯𝐰𝐱𝐲𝐳\mathbf{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +𝚪𝚫𝚯𝚲𝚵𝚷𝚺𝚼𝚽𝚿𝛀𝛂𝛃𝛄𝛅𝛆𝛇𝛈𝛉𝛊𝛋𝛌𝛍𝛎𝛏𝛑𝛒ς𝛔𝛕𝛖𝛗𝛘𝛙𝛚𝛜𝛝𝛟𝜘𝜚ϖ𝟊ϝ\mathbf{\Gamma \Delta \Theta \Lambda \Xi \Pi \Sigma \Upsilon \Phi \Psi \Omega \ \alpha \beta \gamma \delta \varepsilon \zeta \eta \theta \iota \kappa \lambda \mu \nu \xi \pi \rho \varsigma \sigma \tau \upsilon \varphi \chi \psi \omega \ \epsilon \vartheta \phi \varkappa \varrho \varpi Ϝ\digamma \ \partial\nabla } +0123456789\mathbf{0123456789}

+
+
mathit:
+

𝐴𝐵𝐶𝐷𝐸𝐹𝐺𝐻𝐼𝐽𝐾𝐿𝑀𝑁𝑂𝑃𝑄𝑅𝑆𝑇𝑈𝑉𝑊𝑋𝑌𝑍𝑎𝑏𝑐𝑑𝑒𝑓𝑔h𝑖𝑗𝑘𝑙𝑚𝑛𝑜𝑝𝑞𝑟𝑠𝑡𝑢𝑣𝑤𝑥𝑦𝑧ıȷ\mathit{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ \imath \jmath} +𝛤𝛥𝛩𝛬𝛯𝛱𝛴𝛶𝛷𝛹𝛺𝛼𝛽𝛾𝛿𝜀𝜁𝜂𝜃𝜄𝜅𝜆𝜇𝜈𝜉𝜋𝜌ς𝜎𝜏𝜐𝜑𝜒𝜓𝜔𝜖𝜗𝜙𝜘𝜚ϖ\mathit{\Gamma \Delta \Theta \Lambda \Xi \Pi \Sigma \Upsilon \Phi \Psi \Omega \ \alpha \beta \gamma \delta \varepsilon \zeta \eta \theta \iota \kappa \lambda \mu \nu \xi \pi \rho \varsigma \sigma \tau \upsilon \varphi \chi \psi \omega \ \epsilon \vartheta \phi \varkappa \varrho \varpi \ \partial\nabla } +0123456789\mathit{0123456789} [2]

+
+
mathbfit:
+

𝑨𝑩𝑪𝑫𝑬𝑭𝑮𝑯𝑰𝑱𝑲𝑳𝑴𝑵𝑶𝑷𝑸𝑹𝑺𝑻𝑼𝑽𝑾𝑿𝒀𝒁𝒂𝒃𝒄𝒅𝒆𝒇𝒈𝒉𝒊𝒋𝒌𝒍𝒎𝒏𝒐𝒑𝒒𝒓𝒔𝒕𝒖𝒗𝒘𝒙𝒚𝒛\mathbfit{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +𝜞𝜟𝜣𝜦𝜩𝜫𝜮𝜰𝜱𝜳𝜴𝜶𝜷𝜸𝜹𝜺𝜻𝜼𝜽𝜾𝜿𝝀𝝁𝝂𝝃𝝅𝝆ς𝝈𝝉𝝊𝝋𝝌𝝍𝝎𝝐𝝑𝝓𝜘𝜚ϖ\mathbfit{\Gamma \Delta \Theta \Lambda \Xi \Pi \Sigma \Upsilon \Phi \Psi \Omega \ \alpha \beta \gamma \delta \varepsilon \zeta \eta \theta \iota \kappa \lambda \mu \nu \xi \pi \rho \varsigma \sigma \tau \upsilon \varphi \chi \psi \omega \ \epsilon \vartheta \phi \varkappa \varrho \varpi \ \partial\nabla }

+
+
mathcal:
+

𝒜𝒞𝒟𝒢𝒥𝒦𝒩𝒪𝒫𝒬𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵𝒶𝒷𝒸𝒹𝒻𝒽𝒾𝒿𝓀𝓁𝓂𝓃𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏\mathcal{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz}

+
+
mathscr:
+

𝒜𝒞𝒟𝒢𝒥𝒦𝒩𝒪𝒫𝒬𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵𝒶𝒷𝒸𝒹𝒻𝒽𝒾𝒿𝓀𝓁𝓂𝓃𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏\mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz}

+
+
mathbb:
+

𝔸𝔹𝔻𝔼𝔽𝔾𝕀𝕁𝕂𝕃𝕄𝕆𝕊𝕋𝕌𝕍𝕎𝕏𝕐𝕒𝕓𝕔𝕕𝕖𝕗𝕘𝕙𝕚𝕛𝕜𝕝𝕞𝕟𝕠𝕡𝕢𝕣𝕤𝕥𝕦𝕧𝕨𝕩𝕪𝕫\mathbb{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +Σ\mathbb{\Gamma \Pi \Sigma \ \gamma \pi } +0123456789\mathbb{0123456789}

+
+
mathfrak:
+

𝔄𝔅𝔇𝔈𝔉𝔊𝔍𝔎𝔏𝔐𝔑𝔒𝔓𝔔𝔖𝔗𝔘𝔙𝔚𝔛𝔜𝔞𝔟𝔠𝔡𝔢𝔣𝔤𝔥𝔦𝔧𝔨𝔩𝔪𝔫𝔬𝔭𝔮𝔯𝔰𝔱𝔲𝔳𝔴𝔵𝔶𝔷\mathfrak{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz}

+
+
mathsf:
+

𝖠𝖡𝖢𝖣𝖤𝖥𝖦𝖧𝖨𝖩𝖪𝖫𝖬𝖭𝖮𝖯𝖰𝖱𝖲𝖳𝖴𝖵𝖶𝖷𝖸𝖹𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓\mathsf{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +0123456789\mathsf{0123456789}

+
+
mathsfit:
+

𝘈𝘉𝘊𝘋𝘌𝘍𝘎𝘏𝘐𝘑𝘒𝘓𝘔𝘕𝘖𝘗𝘘𝘙𝘚𝘛𝘜𝘝𝘞𝘟𝘠𝘡𝘢𝘣𝘤𝘥𝘦𝘧𝘨𝘩𝘪𝘫𝘬𝘭𝘮𝘯𝘰𝘱𝘲𝘳𝘴𝘵𝘶𝘷𝘸𝘹𝘺𝘻\mathsfit{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz}

+
+
mathsfbfit:
+

\mathsfbfit{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +\mathsfbfit{ΓΔΘΛΞΠΣΥΦΨΩ\ αβγδεζηθικλμνξπρςστυφχψω\ ϵϑϕϰϱϖ\ \partial∇}

+ + +
+
mathtt:
+

𝙰𝙱𝙲𝙳𝙴𝙵𝙶𝙷𝙸𝙹𝙺𝙻𝙼𝙽𝙾𝙿𝚀𝚁𝚂𝚃𝚄𝚅𝚆𝚇𝚈𝚉𝚊𝚋𝚌𝚍𝚎𝚏𝚐𝚑𝚒𝚓𝚔𝚕𝚖𝚗𝚘𝚙𝚚𝚛𝚜𝚝𝚞𝚟𝚠𝚡𝚢𝚣\mathtt{ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz} +0123456789\mathtt{0123456789}

+
+
+ +

In contrast to the math alphabet selectors, \boldsymbol only +changes the font weight. It can be used to get a bold version of +any mathematical symbol:

+
+Vix±cos(α)3ΓxV_i x \pm \cos(\alpha) \approx 3\Gamma \quad \forall x\in\mathbb{R} +
+
+𝐕𝐢𝐱±cos(𝛂)3𝚪𝐱\boldsymbol{V_i x \pm \cos(\alpha) \approx 3\Gamma \quad \forall x\in\mathbb{R}} +
+

It is usually ill-advised to apply \boldsymbol to more than one symbol +at a time.

+
+
+

2.9 Miscellaneous symbols

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

#\#

\#

\clubsuit

\clubsuit

¬\neg

\neg

&\&

\&

\diamondsuit

\diamondsuit

\nexists

\nexists

\angle

\angle

\emptyset

\emptyset

\prime

\prime

\backprime

\backprime

\exists

\exists

\sharp

\sharp

\bigstar

\bigstar

\flat

\flat

\spadesuit

\spadesuit

\blacklozenge

\blacklozenge

\forall

\forall

\sphericalangle

\sphericalangle

\blacksquare

\blacksquare

\heartsuit

\heartsuit

\square

\square

\blacktriangle

\blacktriangle

\infty

\infty

\surd

\surd

\blacktriangledown

\blacktriangledown

\lozenge

\lozenge

\top

\top

\bot

\bot

\measuredangle

\measuredangle

\triangle

\triangle

\diagdown

\diagdown

\nabla

\nabla

\triangledown

\triangledown

\diagup

\diagup

\natural

\natural

\varnothing

\varnothing

+ + + +
+
+

2.10 Punctuation

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

..

.

!!

!

\vdots

\vdots

//

/

??

?

\dotsb

\dotsb

||

|

:\colon

\colon [3]

\dotsc

\dotsc

'

'

\cdots

\cdots

\dotsi

\dotsi

;;

;

\ddots

\ddots

\dotsm

\dotsm

::

:

\ldots

\ldots

\dotso

\dotso

+ + + + + + +
+
+

2.11 Relation symbols

+
+

2.11.1 Arrows

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

\circlearrowleft

\circlearrowleft

\circlearrowright

\circlearrowright

\curvearrowleft

\curvearrowleft

\curvearrowright

\curvearrowright

\hookleftarrow

\hookleftarrow

\hookrightarrow

\hookrightarrow

\leftarrow

\leftarrow

\rightarrow

\rightarrow

\Leftarrow

\Leftarrow

\Rightarrow

\Rightarrow

\leftarrowtail

\leftarrowtail

\rightarrowtail

\rightarrowtail

\leftharpoondown

\leftharpoondown

\rightharpoondown

\rightharpoondown

\leftharpoonup

\leftharpoonup

\rightharpoonup

\rightharpoonup

\leftleftarrows

\leftleftarrows

\rightrightarrows

\rightrightarrows

\leftrightarrow

\leftrightarrow

\Leftrightarrow

\Leftrightarrow

\leftrightarrows

\leftrightarrows

\rightleftarrows

\rightleftarrows

\leftrightharpoons

\leftrightharpoons

\rightleftharpoons

\rightleftharpoons

\leftrightsquigarrow

\leftrightsquigarrow

\rightsquigarrow

\rightsquigarrow

\Lleftarrow

\Lleftarrow

\Rrightarrow

\Rrightarrow

\longleftarrow

\longleftarrow

\longrightarrow

\longrightarrow

\Longleftarrow

\Longleftarrow

\Longrightarrow

\Longrightarrow

\longleftrightarrow

\longleftrightarrow

\Longleftrightarrow

\Longleftrightarrow

\looparrowleft

\looparrowleft

\looparrowright

\looparrowright

\Lsh

\Lsh

\Rsh

\Rsh

\mapsto

\mapsto

\longmapsto

\longmapsto

\multimap

\multimap

\nleftarrow

\nleftarrow

\nrightarrow

\nrightarrow

\nLeftarrow

\nLeftarrow

\nRightarrow

\nRightarrow

\nleftrightarrow

\nleftrightarrow

\nLeftrightarrow

\nLeftrightarrow

\nwarrow

\nwarrow

\nearrow

\nearrow

\swarrow

\swarrow

\searrow

\searrow

\twoheadleftarrow

\twoheadleftarrow

\twoheadrightarrow

\twoheadrightarrow

\upharpoonleft

\upharpoonleft

\upharpoonright

\upharpoonright

\downharpoonleft

\downharpoonleft

\downharpoonright

\downharpoonright

\upuparrows

\upuparrows

\downdownarrows

\downdownarrows

+

Synonyms: \gets \gets, \to \to, \restriction \restriction.

+
+
+

2.11.2 Comparison

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

<<

<

\geq

\geq

\ll

\ll

\prec

\prec

==

=

\geqq

\geqq

\lll

\lll

\precapprox

\precapprox

>>

>

\geqslant

\geqslant

\lnapprox

\lnapprox

\preccurlyeq

\preccurlyeq

\approx

\approx

\gg

\gg

\lneq

\lneq

\preceq

\preceq

\approxeq

\approxeq

\ggg

\ggg

\lneqq

\lneqq

\precnapprox

\precnapprox

\asymp

\asymp

\gnapprox

\gnapprox

\lnsim

\lnsim

\precneqq

\precneqq

\backsim

\backsim

\gneq

\gneq

\ncong

\ncong

\precnsim

\precnsim

\backsimeq

\backsimeq

\gneqq

\gneqq

\neq

\neq

\precsim

\precsim

\bumpeq

\bumpeq

\gnsim

\gnsim

\ngeq

\ngeq

\risingdotseq

\risingdotseq

\Bumpeq

\Bumpeq

\gtrapprox

\gtrapprox

\ngeqq

\ngeqq

\sim

\sim

\circeq

\circeq

\gtreqless

\gtreqless

\ngeqslant

\ngeqslant

\simeq

\simeq

\cong

\cong

\gtreqqless

\gtreqqless

\ngtr

\ngtr

\succ

\succ

\curlyeqprec

\curlyeqprec

\gtrless

\gtrless

\nleq

\nleq

\succapprox

\succapprox

\curlyeqsucc

\curlyeqsucc

\gtrsim

\gtrsim

\nleqq

\nleqq

\succcurlyeq

\succcurlyeq

\doteq

\doteq

\leq

\leq

\nleqslant

\nleqslant

\succeq

\succeq

\doteqdot

\doteqdot

\leqq

\leqq

\nless

\nless

\succnapprox

\succnapprox

\eqcirc

\eqcirc

\leqslant

\leqslant

\nprec

\nprec

\succneqq

\succneqq

\eqsim

\eqsim

\lessapprox

\lessapprox

\npreceq

\npreceq

\succnsim

\succnsim

\eqslantgtr

\eqslantgtr

\lesseqgtr

\lesseqgtr

\nsim

\nsim

\succsim

\succsim

\eqslantless

\eqslantless

\lesseqqgtr

\lesseqqgtr

\nsucc

\nsucc

\thickapprox

\thickapprox

\equiv

\equiv

\lessgtr

\lessgtr

\nsucceq

\nsucceq

\thicksim

\thicksim

\fallingdotseq

\fallingdotseq

\lesssim

\lesssim

\triangleq

\triangleq

+ + + + +

The commands \lvertneqq and \gvertneqq are not supported +with MathML output, as there is no corresponding Unicode character.

+

Synonyms: \ne \ne, \le \le, \ge \ge, +\Doteq \Doteq, \llless \llless, \gggtr \gggtr.

+ + +

Symbols can be negated prepending \not, e.g. +\not= \not=, \not\equiv \not\equiv, +\not\gtrless \not\gtrless, \not\lessgtr \not\lessgtr.

+ + + + +
+
+

2.11.3 Miscellaneous relations

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

϶\backepsilon

\backepsilon

\ntrianglelefteq

\ntrianglelefteq

\subseteq

\subseteq

\because

\because

\ntriangleright

\ntriangleright

\subseteqq

\subseteqq

\between

\between

\ntrianglerighteq

\ntrianglerighteq

\subsetneq

\subsetneq

\blacktriangleleft

\blacktriangleleft

\nvdash

\nvdash

\subsetneqq

\subsetneqq

\blacktriangleright

\blacktriangleright

\nVdash

\nVdash

\supset

\supset

\bowtie

\bowtie

\nvDash

\nvDash

\Supset

\Supset

\dashv

\dashv

\nVDash

\nVDash

\supseteq

\supseteq

\frown

\frown

\parallel

\parallel

\supseteqq

\supseteqq

\in

\in

\perp

\perp

\supsetneq

\supsetneq

\mid

\mid

\pitchfork

\pitchfork

\supsetneqq

\supsetneqq

\models

\models

\propto

\propto

\therefore

\therefore

\ni

\ni

\shortmid

\shortmid

\trianglelefteq

\trianglelefteq

\nmid

\nmid

\shortparallel

\shortparallel

\trianglerighteq

\trianglerighteq

\notin

\notin

\smallfrown

\smallfrown

\varpropto

\varpropto

\nparallel

\nparallel

\smallsmile

\smallsmile

\vartriangle

\vartriangle

\nshortmid

\nshortmid

\smile

\smile

\vartriangleleft

\vartriangleleft

\nshortparallel

\nshortparallel

\sqsubset

\sqsubset

\vartriangleright

\vartriangleright

\nsubseteq

\nsubseteq

\sqsubseteq

\sqsubseteq

\vdash

\vdash

\nsubseteqq

\nsubseteqq

\sqsupset

\sqsupset

\Vdash

\Vdash

\nsupseteq

\nsupseteq

\sqsupseteq

\sqsupseteq

\vDash

\vDash

\nsupseteqq

\nsupseteqq

\subset

\subset

\Vvdash

\Vvdash

\ntriangleleft

\ntriangleleft

\Subset

\Subset

+ + + + + + +

Synonyms: \owns \owns.

+

Symbols can be negated prepending \not, e.g. +\not\in \not\in, \not\ni \not\ni.

+ +

The commands \varsubsetneq, \varsubsetneqq, \varsupsetneq, +and \varsupsetneqq are not supported with MathML output as there is no +corresponding Unicode character.

+
+
+
+

2.12 Variable-sized operators

+ + + + + + + + + + + + + + + + + + + + + + + +

\sum \sum

\prod \prod

\bigcap \bigcap

\bigodot \bigodot

\int \int

\coprod \coprod

\bigcup \bigcup

\bigoplus \bigoplus

\oint \oint

\bigwedge \bigwedge

\biguplus \biguplus

\bigotimes \bigotimes

\smallint \smallint

\bigvee \bigvee

\bigsqcup \bigsqcup

+ +

Larger symbols are used in displayed formulas, sum-like symbols have +indices above/below the symbol:

+
+n=1Nan01f(x)dxi=110bi\sum_{n=1}^N a_n \qquad +\int_0^1f(x)\,dx \qquad +\prod_{i=1}^{10} b_i \ldots +
+
+
+
+

3 Notations

+
+

3.1 Top and bottom embellishments

+

See Accents and embellishments.

+
+
+

3.2 Extensible arrows

+

xleftarrow and xrightarrow produce arrows that extend automatically to +accommodate unusually wide subscripts or superscripts. These commands +take one optional argument (the subscript) and one mandatory argument +(the superscript, possibly empty):

+
A \xleftarrow{n+\mu-1} B \xrightarrow[T]{n\pm i-1} C
+

results in

+
+A \xleftarrow{n+\mu-1} B \xrightarrow[T]{n\pm i-1} C
+
+ +
+
+

3.3 Affixing symbols to other symbols

+

In addition to the standard accents and embellishments, other symbols +can be placed above or below a base symbol with the \overset and +\underset commands. The symbol is set in "scriptstyle" (smaller font +size). For example, writing \overset{*}{X} becomes X*\overset{*}{X} +and \underset{+}{M} becomes M+\underset{+}{M}.

+
+
+

3.4 Matrices

+

The matrix and cases environments can also contain \\ and +&:

+
.. math::
+   \left ( \begin{matrix} a & b \\ c & d \end{matrix}\right)
+

Result:

+
+(abcd)\left ( \begin{matrix} a & b \\ c & d \end{matrix} \right) +
+

The environments pmatrix, bmatrix, Bmatrix, vmatrix, and +Vmatrix have (respectively) ( ), [ ], { }, | |, and \Vert\ \Vert +delimiters built in, e.g.

+
+(abcd)[abcd]abcd\begin{pmatrix} a & b \\ c & d \end{pmatrix} \qquad +\begin{bmatrix} a & b \\ c & d \end{bmatrix} \qquad +\begin{Vmatrix} a & b \\ c & d \end{Vmatrix} +
+

To produce a small matrix suitable for use in text, there is a +smallmatrix environment +(abcd)\bigl(\begin{smallmatrix} a & b \\ c & d \end{smallmatrix}\bigr) +that comes closer to fitting within a single text line than a normal +matrix.

+

For piecewise function definitions there is a cases environment:

+
+sgn(x)={1x<01x>0\mathrm{sgn}(x) = \begin{cases} + -1 & x<0\\ + \phantom{-}1 & x>0 +\end{cases} +
+
+
+

3.5 Spacing commands

+

Horizontal spacing of elements can be controlled with the following +commands:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

343\qquad 4

3\qquad 4

= 2em

343\quad 4

3\quad 4

= 1em

343~4

3~4

3\nobreakspace 4

343\ 4

3\ 4

escaped space

343\;4

3\;4

3\thickspace 4

343\:4

3\:4

3\medspace 4

343\,4

3\,4

3\thinspace 4

343 4

3 4

regular space [4]

343\!4

3\!4

3\negthinspace 4

negative space [5]

3\negmedspace 4

3\negmedspace 4

3\negthickspace 4

3\negthickspace 4

3\hspace{1ex}4

3\hspace{1ex}4

custom length

343\mspace{20mu}4

3\mspace{20mu}4

custom length [6]

+ + + + +

There are also three commands that leave a space equal to the height and +width of its argument. For example \phantom{XXX} results in space as +wide and high as three X’s:

+
+XXX+1XXX1\frac{\phantom{XXX}+1}{XXX-1} +
+

The commands \hphantom and \vphantom insert space with the +width or height of the argument. They are not supported with math_output +MathML.

+
+
+

3.6 Modular arithmetic and modulo operation

+

The commands \bmod, \pmod, \mod, and \pod deal with the +special spacing conventions of the “mod” notation. [7]

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

command

example

result

\bmod

\gcd(n,m \bmod n)

gcd(n,mmodn)\gcd(n,m \bmod n)

\pmod

x\equiv y \pmod b

x\equiv y \pmod b

\mod

x\equiv y \mod c

xymodcx\equiv y \mod c

\pod

x\equiv y \pod d

x\equiv y \pod d

+

\operatorname{mod}(m,n)

mod(m,n)\operatorname{mod}(m,n)

+ + + +
+
+

3.7 Roots

+ + + + + + + + + + + + + + + + + + + + + +

command

example

result

\sqrt

\sqrt{x^2-1}

x21\sqrt{x^2-1}

+

\sqrt[3n]{x^2-1}

x213n\sqrt[3n]{x^2-1}

+

\sqrt\frac{1}{2}

\sqrt\frac{1}{2}

+ +
+
+

3.8 Boxed formulas

+

The command \boxed puts a box around its argument:

+
+ηC(δ(η)+ΛM(0,δ))\boxed{\eta \leq C(\delta(\eta) +\Lambda_M(0,\delta))} +
+
+
+ +
+

5 Delimiter sizes

+

Besides the automatic scaling of extensible delimiters with \left +and \right, there are four commands to manually select delimiters of +fixed size:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +

Sizing

no

\left

\bigl

\Bigl

\biggl

\Biggl

command

\right

\bigr

\Bigr

\biggr

\Biggr

Result

(b)(cd)\displaystyle +(b) +(\frac{c}{d})

(b)(cd)\displaystyle +\left(b\right) +\left(\frac{c} +{d}\right)

(b)(cd)\displaystyle +\bigl(b\bigr) +\bigl(\frac{c} +{d}\bigr)

\displaystyle +\Bigl(b\Bigr) +\Bigl(\frac{c} +{d}\Bigr)

(b)(cd)\displaystyle +\biggl(b\biggr) +\biggl(\frac{c} +{d}\biggr)

(b)(cd)\displaystyle +\Biggl(b\Biggr) +\Biggl(\frac{c} +{d}\Biggr)

+ +

There are two or three situations where the delimiter size is commonly +adjusted using these commands:

+

The first kind of adjustment is done for cumulative operators with +limits, such as summation signs. With \left and \right the +delimiters usually turn out larger than necessary, and using the Big +or bigg sizes instead gives better results:

+
+\left[\sum_i a_i\left\lvert\sum_j x_{ij}\right\rvert^p\right]^{1/p}
+\text{ versus }
+\biggl[\sum_i a_i\Bigl\lvert\sum_j x_{ij}\Bigr\rvert^p\biggr]^{1/p}
+
+ +

The second kind of situation is clustered pairs of delimiters, where +left and right make them all the same size (because that is adequate to +cover the encompassed material), but what you really want is to make some +of the delimiters slightly larger to make the nesting easier to see.

+
+((a1b1)(a2b2))((a2b1)+(a1b2))versus((a1b1)(a2b2))((a2b1)+(a1b2))\left((a_1 b_1) - (a_2 b_2)\right) +\left((a_2 b_1) + (a_1 b_2)\right) +\quad\text{versus}\quad +\bigl((a_1 b_1) - (a_2 b_2)\bigr) +\bigl((a_2 b_1) + (a_1 b_2)\bigr) +
+

The third kind of situation is a slightly oversize object in running +text, such as |bd|\left|\frac{b'}{d'}\right| where the delimiters produced +by \left and \right cause too much line spreading. [8] In that case +\bigl and \bigr can be used to produce delimiters that are larger +than the base size but still able to fit within the normal line spacing: +|bd|\bigl|\frac{b'}{d'}\bigr|.

+ +
+
+

6 Text

+

The main use of the command \text is for words or phrases in a +display. It is similar to \mbox in its effects but, unlike \mbox, +automatically produces subscript-size text if used in a subscript, +k_{\text{B}}T becomes kBTk_{\text{B}}T.

+

Whitespace is kept inside the argument:

+
+f[xi1,xi] is monotonic for i=1,,c+1f_{[x_{i-1},x_i]} \text{ is monotonic for } i = 1,\,\ldots ,\,c+1 +
+

The text may contain math commands wrapped in $ signs, e.g.

+
+(1)ni={1if ni is odd,+1if ni is even.(-1)^{n_i} = \begin{cases} -1 \quad \text{if $n_i$ is odd,} \\ + +1 \quad \text{if $n_i$ is even.} +\end{cases} +
+ +
+
+

7 Integrals and sums

+

The limits on integrals, sums, and similar symbols are placed either to +the side of or above and below the base symbol, depending on convention +and context. In inline formulas and fractions, the limits on sums, and +similar symbols like

+
+limn1n1n\lim_{n\to\infty} \sum_1^n \frac{1}{n} +
+

move to index positions: limn1n1n\lim_{n\to\infty} \sum_1^n \frac{1}{n}.

+
+

7.1 Altering the placement of limits

+

The commands \intop and \ointop produce integral signs with +limits as in sums and similar: \intop_0^1, \ointop_c and

+ + +
+\intop_0^1 \quad \ointop_c
+   \quad \text{vs.} \quad
+\int^1_0   \quad \oint_c
+
+ +

The commands \limits and \nolimits override the default placement +of the limits for any operator; \displaylimits forces standard +positioning as for the sum command. They should follow immediately after +the operator to which they apply.

+

Compare the same term with default positions, \limits, and +\nolimits in inline and display mode: limx0f(x)\lim_{x\to0}f(x), +limx0f(x)\lim\limits_{x\to0}f(x), limx0f(x)\lim\nolimits_{x\to0}f(x), vs.

+
+limx0f(x),limx0f(x)limx0f(x).\lim_{x\to0}f(x), \quad +\lim\limits_{x\to0}f(x) \quad +\lim\nolimits_{x\to0}f(x). +
+ + +
+
+
+

8 Changing the size of elements in a formula

+

The declarations [9] \displaystyle, \textstyle, +\scriptstyle, and \scriptscriptstyle, select a symbol size and +spacing that would be applied in display math, inline +math, first-order subscript, or second-order subscript, respectively +even when the current context would normally yield some other size.

+

For example :math:`\displaystyle \sum_{n=0}^\infty \frac{1}{n}` is printed as n=01n\displaystyle \sum_{n=0}^\infty \frac{1}{n} +rather than n=01n\sum_{n=0}^\infty \frac{1}{n} and

+
\frac{\scriptstyle\sum_{n > 0} z^n}
+{\displaystyle\prod_{1\leq k\leq n} (1-q^k)}
+

yields

+
+\frac{\scriptstyle\sum_{n > 0} z^n}
+{\displaystyle\prod_{1\leq k\leq n} (1-q^k)}
+\text{ instead of the default }
+\frac{\sum_{n > 0} z^n}
+{\prod_{1\leq k\leq n} (1-q^k)}.
+
+ + +
+
+[ISO-80000-2] +

Quantities and units – Part 2: Mathematical signs +and symbols to be used in the natural sciences and technology: +http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=31887.

+
+
+
+
+ + diff --git a/html/math/output_data_badc7e.html b/html/math/output_data_badc7e.html new file mode 100644 index 0000000..51b7b01 --- /dev/null +++ b/html/math/output_data_badc7e.html @@ -0,0 +1,304 @@ + + + + + + + + + + + Understanding Output — aequitas documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + +
+ +
+ + + + + + + + + + + + + + + + + +
+ + + + +
+
+
+
+ + + +
+

Understanding Output

+

Here we provide a highlevel overview of the bias and fairness metrics output by aequitas. For detailed definitions of the metrics see Understanding our metrics

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +

Output type

report

csv

High-level overview

Yes

No

Fairness

Yes

Yes

Disparity

Yes

Yes

Group-level metrics

Yes

Yes

+

You can get Aequitas output in report form via the webapp or CLI as well as a csv/DataFrame using the CLI or Python. Below we reproduce the tables found in the output using

+
+

Fairness overview

+

The webapp and pdf report begins with a high level analysis of fairness. If all fairness metrics are fair, The Bias Report will evalutate the current model as fair. Otherwise, it will deem it unfair and list groups unfairly affected under given fairness criteria. image0

+

In the above example, we see the model has Proportional Parity and False Positive Parity, but does not meet the False Negative Parity criteria for the race Amer-Indian-Eskimo and does not have Equal Parity for many race groups. On the webapp, you can click on the names of the fairness criteria for explanations of the criteria, an example of why you care and more detailed statistics explaining why a group does not have parity.

+
+
+

Fairness Criteria Assessments

+

Fairness is defined in relation to a reference group. In the Fairness Criteria Assessments, a group meets parity if

+
+

(1 - \tau) \leq Disparity Measure_{group_i} \leq \frac{1}{(1 - \tau)}

+

where \tau is the fairness threshold defined in the webapp.

+

image1

+

In our example \tau = 20\%, so any disparity measure between 0.8 and 1.25 will be deemed fair. (This is inline with the 80 percent rule for determining disparate impact).

+

Clicking on the word fair or unfair will bring you to the next table.

+
+
+

Disparity and Bias Metrics

+

Above Fairness was determined by the size of a disparity measure. In this table, you see the disparity measures value. Disparity is a ratio of a groups metric compared to a reference group. Notice the reference group will always have disparity of 1.

+

image2

+

From the high-level overview, we saw that many groups did not have Equal or Statistical Parity. Here we see that the ratio of those groups Predicted Postive Rates compared to the reference group are very low.

+
+
+

Group Metrics

+

The disparities above are derived from group level metrics. image3

+

For example, the False Positive Rate Disparity for black people compared to white people is calculated as follows.

+
+

FPR Disparity_{black} = \frac{FPR_{black}}{FPR_{white}} = \frac{.95}{.9} = 1.06

+
+
+ + +
+ +
+ + +
+
+ +
+ +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/html/math/reg_783dab.html b/html/math/reg_783dab.html new file mode 100644 index 0000000..14fdf33 --- /dev/null +++ b/html/math/reg_783dab.html @@ -0,0 +1,298 @@ + + + + + + + + + + + 10. Regularization — Learning Apache Spark with Python documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + +
+ +
+ + + + + + + + + + + + + + + + + +
+ +
    + +
  • Docs »
  • + +
  • 10. Regularization
  • + + +
  • + + + +
  • + +
+ + +
+
+
+
+ +
+

10. Regularization

+

In mathematics, statistics, and computer science, particularly in the fields of machine learning and inverse problems, +regularization is a process of introducing additional information in order to solve an ill-posed problem or to prevent +overfitting (Wikipedia Regularization).

+

Due to the sparsity within our data, our training sets will often be ill-posed (singular). Applying regularization +to the regression has many advantages, including:

+
    +
  1. Converting ill-posed problems to well-posed by adding additional information via the +penalty parameter \lambda

  2. +
  3. Preventing overfitting

  4. +
  5. Variable selection and the removal of correlated variables (Glmnet Vignette). The Ridge method +shrinks the coefficients of correlated variables while the LASSO method picks one variable and discards +the others. The elastic net penalty is a mixture of these two; if variables are correlated in groups then +\alpha=0.5 tends to select the groups as in or out. If \alpha is close to 1, the elastic +net performs much like the LASSO method and removes any degeneracies and wild behavior caused by extreme +correlations.

  6. +
+
+

10.1. Ordinary least squares regression

+
+

\min _{\Bbeta\in \mathbb {R} ^{n}}{\frac {1}{n}}\|{\X}\Bbeta -{\y}\|^{2}

+

When \lambda=0 (i.e. regParam =0), then there is no penalty.

+
LinearRegression(featuresCol="features", labelCol="label", predictionCol="prediction", maxIter=100,
+regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, standardization=True, solver="auto",
+weightCol=None, aggregationDepth=2)
+
+
+
+
+

10.2. Ridge regression

+
+

\min _{\Bbeta\in \mathbb {R} ^{n}}{\frac {1}{n}}\|{\X}\Bbeta-{\y}\|^{2}+\lambda \|\Bbeta\|_{2}^{2}

+

When \lambda>0 (i.e. regParam >0) and \alpha=0 (i.e. elasticNetParam =0) , then the penalty is an L2 penalty.

+
LinearRegression(featuresCol="features", labelCol="label", predictionCol="prediction", maxIter=100,
+regParam=0.1, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, standardization=True, solver="auto",
+weightCol=None, aggregationDepth=2)
+
+
+
+
+

10.3. Least Absolute Shrinkage and Selection Operator (LASSO)

+
+

\min _{\Bbeta\in \mathbb {R} ^{n}}{\frac {1}{n}}\|{\X}\Bbeta-{\y}\|^{2}+\lambda\|\Bbeta\|_{1}

+

When \lambda>0 (i.e. regParam >0) and \alpha=1 (i.e. elasticNetParam =1), then the penalty is an L1 penalty.

+
LinearRegression(featuresCol="features", labelCol="label", predictionCol="prediction", maxIter=100,
+regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, standardization=True, solver="auto",
+weightCol=None, aggregationDepth=2)
+
+
+
+
+

10.4. Elastic net

+
+

\min _{\Bbeta\in \mathbb {R} ^{n}}{\frac {1}{n}}\|{\X}\Bbeta-{\y}\|^{2}+\lambda (\alpha \|\Bbeta\|_{1}+(1-\alpha )\|\Bbeta\|_{2}^{2}),\alpha \in (0,1)

+

When \lambda>0 (i.e. regParam >0) and elasticNetParam \in (0,1) (i.e. \alpha\in (0,1)) , then the penalty is an L1 + L2 penalty.

+
LinearRegression(featuresCol="features", labelCol="label", predictionCol="prediction", maxIter=100,
+regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, standardization=True, solver="auto",
+weightCol=None, aggregationDepth=2)
+
+
+
+
+ + +
+ +
+ + +
+
+ +
+ +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/html/math/rmarkdown_4b0a34.html b/html/math/rmarkdown_4b0a34.html new file mode 100644 index 0000000..fecd34e --- /dev/null +++ b/html/math/rmarkdown_4b0a34.html @@ -0,0 +1,754 @@ + + + + + + + + Escritura de libros con bookdown + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+ +
+
+ + +
+
+ +
+
+

A R Markdown

+
+

A.1 Introducción

+

Este documento se ha generado empleando Markdown y R. RMarkdown es recomendable para difundir análisis realizados con R en formato HTML, PDF y DOCX (Word), entre otros.

+

Markdown se diseñó inicialmente para la creación de páginas web a partir de documentos de texto de forma sencilla y rápida. Es lo que se conoce como un lenguaje de marcado ligero, tiene unas reglas sintácticas muy simples y se busca principalmente la facilidad de lectura. Posteriormente se fueron añadiendo funcionalidades, por ejemplo para incluir opciones de publicación en muchos otros formatos. La implementación original de Markdown es de John Gruber, pero actualmente están disponibles múltiples dialectos (sobre todo para publicar en gestores de contenido). RMarkdown utiliza las extensiones de la sintaxis proporcionada por Pandoc (ver Apendice B), y adicionalmente permite la inclusión de código R.

+

Al renderizar un fichero RMarkdown se generará un documento que incluye el código R y los resultados incrustados en el documento8. En RStudio basta con hacer clic en el botón Knit. En R se puede emplear la funcion render del paquete rmarkdown (por ejemplo render("Informe.Rmd")). También se puede abrir directamente el informe generado:

+
library(rmarkdown)
+browseURL(url = render("Informe.Rmd"))
+

A continuación se darán algunos detalles sobre RMarkdown (y las extensiones Markdown de Pandoc que admite: notas al pie de página, tablas, citas, ecuaciones LaTeX, …). Para más información (incluyendo introducciones a Markdown y RMarkdown), se recomienda consultar alguna de las numerosas fuentes disponibles, comenzando por la web oficial http://rmarkdown.rstudio.com/.

+

También se dispone de información en la ayuda de RStudio:

+ +

Otras fuentes permiten obtener documentación más detallada, como por ejemplo:

+ +
+
+

A.2 Sintaxis de Markdown

+

Como ya se comentó la sintaxis de Markdown es muy secilla. El texto no marcado se renderiza como texto normal aunque es necesario dejar una línea en blanco para insertar un salto de línea. Las principales reglas de Markdown se sumarizan en la siguiente tabla:

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Escribiro alternativamentepara obtener …
# Título 1
+ 
+## Título 2
+ 
+### Título 3
Título 1
+========
+Título 2
+--------
+### Título 3
Los distintos niveles de encabezados
*Cursiva*
_Cursiva_
Cursiva
**Negrita**
__Negrita__
Negrita
[Enlace](http://url.gz)
+ 
+ 
[Enlace][1]
+Más adelante...
+[1]: http://url.gz
Enlace
![Imagen](rmarkdown.png)
+ 
+ 
![Imagen][1]
+Más adelante...
+[1]:http://url/b.jpg
Imagen
> Blockquote
+>
+> --- El Autor
+

Blockquote

+

— El Autor

+
* Lista
+* Lista
+   + Sub-lista
-  Lista
+-  Lista
+   - Sub-lista
    +
  • Lista
  • +
  • Lista +
      +
    • Sub-lista
    • +
  • +
1. Uno
+2. Dos
+   a. A
1) Uno
+2) Dos
+   a) A
    +
  1. Uno
  2. +
  3. Dos +
      +
    1. A
    2. +
  4. +
Regla horizontal
+
+---
Regla horizontal
+
+***

Regla horizontal

+
`código en línea` entre
+comillas invertidas
código en línea entre comillas invertidas
```
+# bloque de código
+3 comillas invertidas
+o sangría de 4 espacios
+```
[····]# bloque de código
+[····]3 comillas invertidas
+[····]o sangría de 4 espaci
+os
# bloque de código
+3 comillas invertidas
+o sangría de 4 espacios
+

Es muy recomendable dejar siempre una linea de separación entre elementos distintos consecutivos.

+
+
+

A.3 Inclusión de código R

+

Se puede incluir código R entre los delimitadores ```{r} y ```. Por defecto, se mostrará el código, se evaluará y se mostrarán los resultados justo a continuación. Por ejemplo el siguiente código:

+
```{r}
+head(mtcars[1:3])
+summary(mtcars[1:3])
+```
+

produce:

+
head(mtcars[1:3])
+
##                    mpg cyl disp
+## Mazda RX4         21.0   6  160
+## Mazda RX4 Wag     21.0   6  160
+## Datsun 710        22.8   4  108
+## Hornet 4 Drive    21.4   6  258
+## Hornet Sportabout 18.7   8  360
+## Valiant           18.1   6  225
+
summary(mtcars[1:3])
+
##       mpg             cyl             disp      
+##  Min.   :10.40   Min.   :4.000   Min.   : 71.1  
+##  1st Qu.:15.43   1st Qu.:4.000   1st Qu.:120.8  
+##  Median :19.20   Median :6.000   Median :196.3  
+##  Mean   :20.09   Mean   :6.188   Mean   :230.7  
+##  3rd Qu.:22.80   3rd Qu.:8.000   3rd Qu.:326.0  
+##  Max.   :33.90   Max.   :8.000   Max.   :472.0
+

En RStudio pulsando “Ctrl + Alt + I” o en el icono correspondiente se incluye un trozo de código.

+

También se puede incluir código en línea empleando `r código`, por ejemplo `r 2 + 2` produce 4.

+
+

A.3.1 Gráficos

+

Si el código genera un gráfico, este se incluirá en el documento justo después de donde fué generado (por defecto). Por ejemplo el siguiente gráfico:

+

+

se generó empleando:

+
```{r figura1, echo=FALSE}
+hist(mtcars$mpg)
+```
+

aunque no se mostró previamente el código al haber establecido la opción ```{r, echo=FALSE}.

+
+
+

A.3.2 Opciones de bloques de código

+

Los trozos de código pueden tener nombre y opciones, se establecen en la cabecera de la forma ```{r nombre, op1, op2}. Para un listado de las opciones disponibles ver http://yihui.name/knitr/options (en la Sección 2.6 del libro de RMarkdown se incluye un resumen). En RStudio se puede pulsar en los iconos en la parte superior derecha del bloque de código para establecer opciones, ejecutar todo el código anterior o sólo el correspondiente trozo.

+

Algunas opciones sobre evaluación y resultados:

+
    +
  • eval: si =FALSE no se evalúa el código.
  • +
  • echo: si =FALSE no se muestra el código.
  • +
  • include: si =FALSE no se muestra el código ni ningún resultado.
  • +
  • message, warning, error: oculta el correspondiente tipo de mensaje de R (los errores o warnings se mostrarán en la consola).
  • +
  • cache: si se activa, guarda los resultados de la última evaluación y se reutilizan si no cambió el bloque de código (más detalles aquí). Puede ser de utilidad durante la redacción del documento para reducir el tiempo de renderizado (usándolo con cuidado y desactivándolo al terminar).
  • +
+

Algunas opciones sobre resultados gráficos:

+
    +
  • fig.width, fig.height, fig.dim: dimensiones del dispositivo gráfico de R (no confundir con el tamaño del resultado), e.g. fig.width = 5.
  • +
  • out.width, out.heigh: tamaño del gráfico, e.g. ='80%'.
  • +
  • fig.align: ='left', 'center', 'right', establece la alineación.
  • +
  • fig.cap: leyenda de la figura9.
  • +
  • dev: dispositivo gráfico de R, por defecto ='pdf' para LaTeX y 'png' para HTML. Otras opciones son 'svg' o 'jpeg'.
  • +
+

Para establecer valores por defecto para todos los bloques de código se suele incluir uno de configuración al principio del documento, por ejemplo:

+
```{r, setup, include=FALSE}
+knitr::opts_chunk$set(comment=NA, prompt=TRUE, dev='svg', fig.dim=c(5, 7), collapse=TRUE)
+```
+
+
+
+

A.4 Tablas

+

Las tablas en Markdown son de la forma:

+
| First Header  | Second Header |
+| ------------- | ------------- |
+| Row1 Cell1    | Row1 Cell2    |
+| Row2 Cell1    | Row2 Cell2    |
+

Por ejemplo:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
VariableDescripción
mpgMillas / galón (EE.UU.)
cylNúmero de cilindros
dispDesplazamiento (pulgadas cúbicas)
hpCaballos de fuerza bruta
dratRelación del eje trasero
wtPeso (miles de libras)
qsecTiempo de 1/4 de milla
vsCilindros en V/Straight (0 = cilindros en V, 1 = cilindros en línea)
amTipo de transmisión (0 = automático, 1 = manual)
gearNúmero de marchas (hacia adelante)
carbNúmero de carburadores
+

Para convertir resultados de R en tablas de una forma simple se puede emplear la función ktable del paquete knitr. Por ejemplo la Tabla A.1 se obtuvo mediante el siguiente código:

+
knitr::kable(
+  head(mtcars), 
+  caption = "Una kable knitr"
+)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tabla A.1: Una kable knitr
mpgcyldisphpdratwtqsecvsamgearcarb
Mazda RX421.061601103.902.62016.460144
Mazda RX4 Wag21.061601103.902.87517.020144
Datsun 71022.84108933.852.32018.611141
Hornet 4 Drive21.462581103.083.21519.441031
Hornet Sportabout18.783601753.153.44017.020032
Valiant18.162251052.763.46020.221031
+

Otros paquetes proporcionan opciones adicionales: xtable, stargazer, pander, tables y ascii.

+
+
+

A.5 Cabecera YAML

+

En un fichero RMarkdown se puede incluir metadatos en una cabecera en formato YAML (YAML Ain’t Markup Language, https://en.wikipedia.org/wiki/YAML), comenzando y terminando con tres guiones ---. Los metadatos de YAML son típicamente opciones de renderizado consitentes en pares de etiquetas y valores separados por dos puntos. Por ejemplo:

+
---
+title: "Creación de contenidos con RMarkdown"
+author: "Fernández-Casal, R. y Cotos-Yáñez, T.R."
+date: "`r Sys.Date()`"
+output: html_document
+---
+

Aunque no siempre es necesario, se recomienda que los valores de texto se introduzcan entre comillas (se puede incluir código R en línea, como por ejemplo `r Sys.Date()` para obtener la fecha actual). Para valores lógicos se puede emplear yes/true y no/false para verdadero y falso, respectivamente.

+

Los valores pueden ser vectores, por ejemplo las siguientes opciones son equivalentes:

+
bibliography: [book.bib, packages.bib]
+
bibliography:
+- book.bib
+- packages.bib
+

También pueden ser listas, añadiendo una sangría de dos espacios (importante):

+
output:
+  html_document:
+    toc: yes
+    toc_float: yes
+  pdf_document:
+    toc: yes
+

El campo output permite especificar el formato y las opciones de salida (por defecto se empleará la primera). Empleando este campo también se pueden especificar opciones gráficas para los bloques de código, por ejemplo:

+
output:
+  html_document:
+    fig_width: 7
+    fig_height: 6
+    fig_caption: true
+

La mayoría de los campos YAML son opciones que el paquete rmarkdown le pasa a Pandoc (ver documentación en el Apéndice B).

+

Un ejemplo adicional10:

+
---
+title: "Creación de contenidos con RMarkdown"
+subtitle: "Curso de introducción a R"
+author:
+- name: "Rubén Fernández Casal (ruben.fcasal@udc.es)"
+  affiliation: "Universidade da Coruña"
+- name: "Tomás R. Cotos Yáñez (tcotos@uvigo.es)"
+  affiliation: "Universidade de Vigo"
+date: "2018-10-28"
+logo: rmarkdown.png
+output:
+  html_document:
+    toc: yes                  # incluir tabla de contenido
+    toc_float: yes            # toc flotante a la izquierda
+    number_sections: yes      # numerar secciones y subsecciones
+    code_folding: hide        # por defecto el código aparecerá oculto
+    mathjax: local            # emplea una copia local de MathJax, hay que establecer:
+    self_contained: false     # las dependencias se guardan en ficheros externos
+    lib_dir: libs             # directorio para librerías (Bootstrap, MathJax, ...)
+  pdf_document:
+    toc: yes
+    toc_depth: 2
+    keep_tex: yes             # conservar fichero latex
+    
+---
+

Como se puede deducir del ejemplo anterior, en el formato YAML podemos incluir comentarios con el carácter # (por ejemplo para no emplear alguna de las opciones sin borrarla del encabezado).

+

En el Capítulo 3 del libro de RMarkdown se tiene información detallada sobre las opciones de los distintos formatos de salida (sobre ficheros HTML aquí y sobre PDF/LaTeX aquí).

+
+
+

A.6 Extracción del código R

+

Para generar un fichero con el código R se puede emplear la función purl del paquete knitr. Por ejemplo:

+
purl("Informe.Rmd")
+

Si se quiere además el texto RMarkdown como comentarios tipo spin, se puede emplear:

+
purl("Informe.Rmd", documentation = 2)
+
+
+

A.7 Spin

+

Una forma rápida de crear este tipo de informes a partir de un fichero de código R es emplear la funcion spin del paquete knitr (ver p.e. http://yihui.name/knitr/demo/stitch).

+

Para ello se debe comentar todo lo que no sea código R de una forma especial:

+
    +
  • El texto RMarkdown se comenta con #'. Por ejemplo:

    +
    #' # Este es un título de primer nivel
    +#' ## Este es un título de segundo nivel
  • +
  • Las opciones de un trozo de código se comentan con #+. Por ejemplo:

    +
    #+ setup, include=FALSE
    +opts_chunk$set(comment=NA, prompt=TRUE, dev='svg', fig.height=6, fig.width=6)
  • +
+

Para generar el informe se puede emplear la funcion spin del paquete knitr. Por ejemplo: spin("Ridge_Lasso.R"). También se podría abrir directamente el informe generado:

+
browseURL(url = knitr::spin("Ridge_Lasso.R"))
+

Pero puede ser recomendable renderizarlo con rmarkdown:

+
library(rmarkdown)
+browseURL(url = render(knitr::spin("Ridge_Lasso.R", knit = FALSE)))
+

En RStudio basta con pulsar “Ctrl + Shift + K” o seleccionar File > Knit Document (en las últimas versiones también File > Compile Notebook o hacer clic en el icono correspondiente).

+

Por ejemplo, si se quiere convertir la salidas de un fichero de código de R a formato LaTeX (para añadirlas fácilmente a un documento en este formato), bastaría con incluir una cabecera de la forma:

+
#' ---
+#' title: "Título"
+#' author: "Autor"
+#' date: "Fecha"
+#' output:
+#'   pdf_document:
+#'      keep_tex: true
+#' ---
+
+
+

A.8 Extensiones RMarkdown de pandoc

+

Como ya se comentó, RMarkdown utiliza la sintaxis extendida proporcionada por Pandoc. Por ejemplo, se pueden añadir subíndices y superíndices con sub~índices~ y super^índices^,
+y notas al pie con ^[texto].

+

Podemos incluir expresiones matemáticas en formato LateX:

+
    +
  • En linea escribiendo la expresión latex entre dos símbolos de dolar, por ejemplo $\alpha, \beta, \gamma, \delta$ resultaría en \(\alpha, \beta, \gamma, \delta\).

  • +
  • En formato ecuación empleando dos pares de símbolos de dolar. Por ejemplo:

    +
    $$\Theta = \begin{pmatrix}\alpha & \beta\\
    +\gamma & \delta
    +\end{pmatrix}$$
    +

    resultaría en: \[\Theta = \begin{pmatrix}\alpha & \beta\\ +\gamma & \delta +\end{pmatrix}\]

  • +
+

También admite bibliografía, ver p.e. https://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html. Lo más cómodo puede ser emplear un archivo de bibliografía en formato BibTeX, lo que se describe con detalle aquí. Será necesario añadir un campo bibliography en la cabezera YAML, por ejemplo:

+
bibliography: bibliografia.bib
+csl: apa.csl  # opcional
+

Suponiendo que en el directorio de trabajo están los ficheros de bibliografía bibliografia.bib y de estilo apa.csl (ver http://citationstyles.org/, desde donde se pueden descargar distintos archivos de estilo).

+

Las referencias en el texto RMarkdown se incluyen con @referencia o [@referencia]. Pandoc generará el listado de referencias al final del documento, por lo que nos puede interesar insertar una última sección # Bibliografía {-} al generar documentos HTML (en PDF se hará automáticamente al emplear LaTeX). En RStudio se puede instalar el “Addincitr para insertar citas a referencias bibliográficas en formato BibTeX.

+

Para más detalles de las extensiones de Pandoc ver por ejemplo https://rmarkdown.rstudio.com/authoring_pandoc_markdown.html%23raw-tex o el manual de Pandoc https://pandoc.org/MANUAL.html.

+ +
+
+

Bibliografía

+
+
+

Xie, Yihui. 2018b. Knitr: A General-Purpose Package for Dynamic Report Generation in R. https://CRAN.R-project.org/package=knitr.

+
+
+

Xie, Yihui, JJ Allaire, and Garrett Grolemund. 2018. R Markdown: The Definitive Guide. CRC Press. https://bookdown.org/yihui/rmarkdown/.

+
+
+
+
+
    +
  1. Se llama al paquete knitr para “tejer” el código de R y los resultados en un fichero Markdown, que posteriormente es procesado con pandoc

  2. +
  3. Si se genera un documento en PDF/LaTeX el gráfico se mostrará en un entorno flotante y se puede ajustar la posición empleando la opción fig.pos (por ejemplo, fig.pos = '!htb').

  4. +
  5. Puede ser interesante ejecutar str(rmarkdown::html_document()) para ver un listado de todas las opciones disponibles de html_document

  6. +
+
+
+ +
+
+
+ + +
+
+ + + + + + + + + + + + + + diff --git a/html/math/sample_5da28a.html b/html/math/sample_5da28a.html new file mode 100644 index 0000000..3b1d1de --- /dev/null +++ b/html/math/sample_5da28a.html @@ -0,0 +1,117 @@ + + + +MathJax Test Page + + + + + + + + + + + + + + +

Sample MathJax Equations

+ +
+ +

The Lorenz Equations

+ +

+\begin{align} +\dot{x} & = \sigma(y-x) \\ +\dot{y} & = \rho x - y - xz \\ +\dot{z} & = -\beta z + xy +\end{align} +

+ +

The Cauchy-Schwarz Inequality

+ +

\[ +\left( \sum_{k=1}^n a_k b_k \right)^{\!\!2} \leq + \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right) +\]

+ +

A Cross Product Formula

+ +

\[ + \mathbf{V}_1 \times \mathbf{V}_2 = + \begin{vmatrix} + \mathbf{i} & \mathbf{j} & \mathbf{k} \\ + \frac{\partial X}{\partial u} & \frac{\partial Y}{\partial u} & 0 \\ + \frac{\partial X}{\partial v} & \frac{\partial Y}{\partial v} & 0 \\ + \end{vmatrix} +\]

+ +

The probability of getting \(k\) heads when flipping \(n\) coins is:

+ +

\[P(E) = {n \choose k} p^k (1-p)^{ n-k} \]

+ +

An Identity of Ramanujan

+ +

\[ + \frac{1}{(\sqrt{\phi \sqrt{5}}-\phi) e^{\frac25 \pi}} = + 1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}} + {1+\frac{e^{-8\pi}} {1+\ldots} } } } +\]

+ +

A Rogers-Ramanujan Identity

+ +

\[ + 1 + \frac{q^2}{(1-q)}+\frac{q^6}{(1-q)(1-q^2)}+\cdots = + \prod_{j=0}^{\infty}\frac{1}{(1-q^{5j+2})(1-q^{5j+3})}, + \quad\quad \text{for $|q|<1$}. +\]

+ +

Maxwell's Equations

+ +

+\begin{align} + \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\ + \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\ + \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\ + \nabla \cdot \vec{\mathbf{B}} & = 0 +\end{align} +

+ +

In-line Mathematics

+ +

Finally, while display equations look good for a page of samples, the +ability to mix math and text in a paragraph is also important. This +expression \(\sqrt{3x-1}+(1+x)^2\) is an example of an inline equation. As +you see, MathJax equations can be used this way as well, without unduly +disturbing the spacing between lines.

+ + +
+ + + diff --git a/html/math/scipy_stats_norm_60d729.html b/html/math/scipy_stats_norm_60d729.html new file mode 100644 index 0000000..23daef9 --- /dev/null +++ b/html/math/scipy_stats_norm_60d729.html @@ -0,0 +1,777 @@ + + + + + + + + + + + scipy.stats.norm — SciPy v1.18.0 Manual + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + +
+ +
+ + + + + +
+
+ + + + +
+ + + + + + + + + + + +
+ +
+ + +
+
+ +
+
+ +
+ +
+ + +
+ +
+ + +
+
+ + + + + +
+ +
+

scipy.stats.norm#

+
+
+scipy.stats.norm = <scipy.stats._continuous_distns.norm_gen object>[source]#
+

A normal continuous random variable.

+

The location (loc) keyword specifies the mean. +The scale (scale) keyword specifies the standard deviation.

+

As an instance of the rv_continuous class, norm object inherits from it +a collection of generic methods (see below for the full list), +and completes them with details specific for this particular distribution.

+

Methods

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

rvs(loc=0, scale=1, size=1, random_state=None)

Random variates.

pdf(x, loc=0, scale=1)

Probability density function.

logpdf(x, loc=0, scale=1)

Log of the probability density function.

cdf(x, loc=0, scale=1)

Cumulative distribution function.

logcdf(x, loc=0, scale=1)

Log of the cumulative distribution function.

sf(x, loc=0, scale=1)

Survival function (also defined as 1 - cdf, but sf is sometimes more accurate).

logsf(x, loc=0, scale=1)

Log of the survival function.

ppf(q, loc=0, scale=1)

Percent point function (inverse of cdf — percentiles).

isf(q, loc=0, scale=1)

Inverse survival function (inverse of sf).

moment(order, loc=0, scale=1)

Non-central moment of the specified order.

stats(loc=0, scale=1, moments=’mv’)

Mean(‘m’), variance(‘v’), skew(‘s’), and/or kurtosis(‘k’).

entropy(loc=0, scale=1)

(Differential) entropy of the RV.

fit(data)

Parameter estimates for generic data. See scipy.stats.rv_continuous.fit for detailed documentation of the keyword arguments.

expect(func, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)

Expected value of a function (of one argument) with respect to the distribution.

median(loc=0, scale=1)

Median of the distribution.

mean(loc=0, scale=1)

Mean of the distribution.

var(loc=0, scale=1)

Variance of the distribution.

std(loc=0, scale=1)

Standard deviation of the distribution.

interval(confidence, loc=0, scale=1)

Confidence interval with equal areas around the median.

+
+

Notes

+

The probability density function for norm is:

+
+\[f(x) = \frac{\exp(-x^2/2)}{\sqrt{2\pi}}\]
+

for a real number \(x\).

+

The probability density above is defined in the “standardized” form. To shift +and/or scale the distribution use the loc and scale parameters. +Specifically, norm.pdf(x, loc, scale) is identically +equivalent to norm.pdf(y) / scale with +y = (x - loc) / scale. Note that shifting the location of a distribution +does not make it a “noncentral” distribution; noncentral generalizations of +some distributions are available in separate classes.

+

Examples

+
+
+
>>> import numpy as np
+>>> from scipy.stats import norm
+>>> import matplotlib.pyplot as plt
+>>> fig, ax = plt.subplots(1, 1)
+
+
+

Get the support:

+
>>> lb, ub = norm.support()
+
+
+

Calculate the first four moments:

+
>>> mean, var, skew, kurt = norm.stats(moments='mvsk')
+
+
+

Display the probability density function (pdf):

+
>>> x = np.linspace(norm.ppf(0.01),
+...                 norm.ppf(0.99), 100)
+>>> ax.plot(x, norm.pdf(x),
+...        'r-', lw=5, alpha=0.6, label='norm pdf')
+
+
+

Alternatively, the distribution object can be called (as a function) +to fix the shape, location and scale parameters. This returns a “frozen” +RV object holding the given parameters fixed.

+

Freeze the distribution and display the frozen pdf:

+
>>> rv = norm()
+>>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+
+

Check accuracy of cdf and ppf:

+
>>> vals = norm.ppf([0.001, 0.5, 0.999])
+>>> np.allclose([0.001, 0.5, 0.999], norm.cdf(vals))
+True
+
+
+

Generate random numbers:

+
>>> r = norm.rvs(size=1000)
+
+
+

And compare the histogram:

+
>>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2)
+>>> ax.set_xlim([x[0], x[-1]])
+>>> ax.legend(loc='best', frameon=False)
+>>> plt.show()
+
+
+
+../../_images/scipy-stats-norm-1.png +
+
+
+
+ +
+ + +
+ + + + + + + +
+ + + + +
+ + +
+ + +
+
+
+ + + + + + + + \ No newline at end of file diff --git a/jats/math/10_21105_joss_01816_736f75.jats b/jats/math/10_21105_joss_01816_736f75.jats new file mode 100644 index 0000000..ccb71ba --- /dev/null +++ b/jats/math/10_21105_joss_01816_736f75.jats @@ -0,0 +1,277 @@ + + +
+ + + + +Journal of Open Source Software +JOSS + +2475-9066 + +Open Journals + + + +1816 +10.21105/joss.01816 + +OnlineStats.jl: A Julia package for statistics on data +streams + + + +0000-0002-7490-6986 +Josh Day + + + +0000-0003-1320-7118 +Hua Zhou + + + + +Loon Analytics, LLC + + + + +UCLA Biostatistics + + + + +2 +9 +2019 + +5 +46 +1816 + +Authors of papers retain copyright and release the +work under a Creative Commons Attribution 4.0 International License (CC +BY 4.0) +2021 +The article authors + +Authors of papers retain copyright and release the work under +a Creative Commons Attribution 4.0 International License (CC BY +4.0) + + + +statistics +big data +online algorithms +streaming data + + + + + + Summary +

The growing prevalence of big and streaming data requires a new + generation of tools. Data often has infinite size in the sense that + new observations are continually arriving daily, hourly, etc. In + recent years, several new technologies such as Kafka + (Apache + Software Foundation, n.d.-a) and Spark Streaming + (Apache + Software Foundation, n.d.-b) have been introduced for + processing streaming data. Statistical tools for data streams, + however, are under-developed and offer only basic functionality. The + majority of statistical software can only operate on finite batches + and require re-loading possibly large datasets for seemingly simple + tasks such as incorporating a few more observations into an + analysis.

+

OnlineStats is a Julia + (Bezanson + et al., 2017) package for high-performance online algorithms. + The OnlineStats framework is easily extensible, + includes a large catalog of algorithms, provides primitives for + parallel computing, and offers a weighting mechanism that allows new + observations have a higher relative influence over the value of the + statistic/model/visualization.

+
+ + Interface +

Each algorithm is associated with its own type + (e.g. Mean, Variance, + etc.). The OnlineStats interface is built on + several key functions from the OnlineStatsBase + package. A new type must provide implementations of these functions in + order to use the rest of the OnlineStats + framework.

+ + Updating + OnlineStatsBase._fit!(stat, y) +

The _fit! method determines how the + statistic stat is updated with a single + observation y. Each OnlineStat is a concrete + subtype of OnlineStat{T}, where + T is the type of a single observation. The + fit!(stat::OnlineStat{T}, y::T) method simply + calls _fit!. When + fit!(stat::OnlineStat{T}, y::S) is called + (where S is not a subtype of + T), y is iterated + through and fit! is called on each + element.

+ + Update Weights +

Many OnlineStats incorporate a weight function that determines + the influence of the next observation. For example, the online + update for a mean + + μ(t) + given its current state + + μ(t1) + and new observation + + yt + is

+

+ + μ(t)=(1t1)μ(t1)+t1yt.

+

OnlineStats generalizes this update to + use weights that are a function of + + t:

+

+ + μ(t)=[1w(t)]μ(t1)+w(t)yt.

+

Therefore, for example, + + w(t)=t1 + returns the analytical mean and + + w(t)=λ(0<λ<1) + returns an exponentially weighted mean.

+
+
+ + Merging + OnlineStatsBase._merge!(stat1, stat2) +

The _merge! function merges the state of + stat2 into stat1 and + facilitates parallel computation. This function is optional to + implement, as merging is not guaranteed to be well-defined for a + given statistic/algorithm. The default definition prints out a + warning that no merging occurred.

+
+ + Returning the State + OnlineStatsBase.value(stat, args...; kw...) +

The value function returns the value of + the estimator (optionally determined by positional arguments + args and keyword arguments + kw). Depending on the type, this may need to + be calculated from its state. By default, this returns the first + field of the type.

+ OnlineStatsBase.nobs(stat) +

The nobs function returns the number of + observations that the statistic has seen. By default this returns + the n field from the algorithm’s type + (stat.n).

+
+
+ + Example +

The Mean type provides an easy-to-understand + full example of how to implement a new algorithm. The update formula, + as previously stated, is:

+

+ + μ(t)=[1w(t)]μ(t1)+w(t)yt.

+

The merge formula for two means, + + μ1(t) + and + + μ2(s), + generalizes the above equation to:

+

+ + μmerged(t+s)=[1s/(t+s)]μ1(t)+[s/(t+s)]μ2(s).

+

Converting these formulas into Julia code, + we get the following implementation. Note that + Mean is parameterized by the data type that + stores the mean value so that non-standard types such as complex + numbers can be used.

+ mutable struct Mean{T,W} <: OnlineStat{Number} + m::T + weight::W + n::Int +end + +function Mean(T::Type{<:Number} = Float64; weight = inv) + Mean(zero(T), weight, 0) +end + +function _fit!(o::Mean{T}, x) where {T} + o.n += 1 + w = T(o.weight(o.n)) + o.m += w * (x - o.m) +end + +function _merge!(o::Mean, o2::Mean) + o.n += o2.n + o.m += (o2.n / o.n) * (o2.m - o.m) +end +
+ + + + + + + + BezansonJeff. + EdelmanAlan. + KarpinskiStefan. + ShahViral B. + + Julia: A fresh approach to numerical computing + SIAM Review + 2017 + 59 + 1 + https://doi.org/10.1137/141000671 + 10.1137/141000671 + + + + + + Apache Software Foundation + + Kafka + https://kafka.apache.org + + + + + + Apache Software Foundation + + Spark streaming + https://spark.apache.org/streaming/ + + + + + +
diff --git a/jats/math/10_21105_joss_06105_a7ce1e.jats b/jats/math/10_21105_joss_06105_a7ce1e.jats new file mode 100644 index 0000000..b2c0197 --- /dev/null +++ b/jats/math/10_21105_joss_06105_a7ce1e.jats @@ -0,0 +1,377 @@ + + +
+ + + + +Journal of Open Source Software +JOSS + +2475-9066 + +Open Journals + + + +6105 +10.21105/joss.06105 + +sectionproperties: A Python package for the analysis of +arbitrary cross-sections using the finite element method + + + +https://orcid.org/0009-0004-8056-3977 + +van Leeuwen +Robbie + + + + +https://orcid.org/0009-0005-0861-2428 + +Ferster +Connor + + + + + +Independent Researcher, Australia + + + + +Independent Researcher, Canada + + + + +13 +10 +2023 + +9 +96 +6105 + +Authors of papers retain copyright and release the +work under a Creative Commons Attribution 4.0 International License (CC +BY 4.0) +2022 +The article authors + +Authors of papers retain copyright and release the work under +a Creative Commons Attribution 4.0 International License (CC BY +4.0) + + + +python +computational mechanics +finite element method +cross-section +stress analysis +engineering + + + + + + Summary +

Properties of plane cross-sections are often required in + engineering research, analysis, and design. For example, + cross-sectional properties are used to determine the displacements, + natural frequencies, and stresses within beams under complex loading. + sectionproperties is a Python package for the + analysis of arbitrary cross-sections using the finite + element method. sectionproperties can be used + to determine geometric and warping properties, as well as visualising + cross-sectional stresses resulting from combinations of applied loads. + sectionproperties aims to provide a + pre-processor, analysis engine, and post-processor, in a single open + source and accessible package, that can be used by researchers, + practising engineers, and students.

+
+ + Statement of Need +

Obtaining the geometric properties of simple shapes is a classical + engineering problem with well-defined analytical solutions. However, + obtaining warping properties, e.g. for torsion and shear analyses, + involves solving partial differential equations + (Pilkey, + 2002). While some analytical solutions exist for a small subset + of geometries, the method for obtaining these results is not able to + be generalised to shapes commonly used in engineering pratice. + Further, the analysis of arbitrary composite geometries, in which a + cross-section could consist of any shape with any number of internal + holes, and be made from any number of materials, complicates both + geometric and warping computations.

+

To the best of our knowledge, there is no open source software + available for the computation of both geometric and warping propreties + for composite, arbitary cross-sections. While there are several + commercial solutions available, e.g. + RSECTION 1, + ShapeDesigner SaaS, + or + CADRE Profiler, + none of these are open source or provide an application programming + interface (API) that would enable these programs to be used for + research. As a result, sectionproperties + supports both engineering practice and research, by implementing an + open source solution to the complex modelling problem that is + arbitrary composite geometric and warping analyses.

+
+ + Implementation +

sectionproperties harnesses the power of + Shapely + (Gillies + et al., 2023) to streamline geometry generation, and triangle + (Rufat, + 2023) (a python port of Triangle + (Shewchuk, + 2002)) to produce a triangular mesh of six-noded quadratic + elements. The finite element method is used to solve for the geometric + and warping properties, the latter involving the solution of partial + differential equations and boundary value problems + (Pilkey, + 2002). For example, the Saint-Venant torsion constant + ( + + J) + is obtained by solving for the warping function, + + + ω + (Pilkey, + 2002):

+

+ + 2ω=0

+

subject to the boundary condition:

+

+ + ωxnx+ωyny=ynxxny

+

Using the finite element method, this problem is reduced to a set + of linear equations of the form:

+

+ + 𝐊𝛚=𝐅

+

where the stiffness matrix and load vector at the element level are + defined as:

+

+ + 𝐤e=i=16wi𝐁iT𝐁iJi

+

+ + 𝐟e=i=16wi𝐁iT[𝐍i𝐲e𝐍i𝐱e]Ji

+

In the above, + + 𝐍 + and + + 𝐁 + are the shape functions and their derivatives, and + + + wi + and + + Ji + are the weights and Jacobians of the current integration point. The + boundary conditions neccesitate the inversion of a nearly singular + global stiffness matrix. As such, the Lagrangian multiplier method is + used to solve the set of linear equations of the form + + + 𝐊𝐮=𝐅 + by introducing an extra constraint on the solution vector, whereby the + mean value is equal to zero + (Larson + & Bengzon, 2013).

+

+ + [𝐊𝐂T𝐂0][𝐮λ]=[𝐅0]

+

where + + 𝐂 + is the assembly of + + iwi𝐍iJi, + and + + λ + may be though of as a relatively small force acting to enforce the + constraints. Once the warping function has been evaluated, the + Saint-Venant torsion constant can be calculated as follows:

+

+ + J=Ixx+Iyy𝛚T𝐊𝛚

+

The calculation of plastic properties is meshless, and is conducted + using an iterative method to enforce plastic equilibrium, yielding the + plastic centroids. A full description of the theoretical background + underpinning sectionproperties can be found in + the + documentation.

+

An example of some of the visualisation generated by + sectionproperties can be seen in + [fig:example] + below.

+ +

Plot of the centroids and torsion stress distribution + for a bulb-section modelled in + sectionproperties.

+ +
+
+ + Software Development +

The sectionproperties package is available + on + GitHub, + where the source code, issue tracker, CI workflow, and discussion + board can be found. Pre-commit hooks are used to ensure code quality + and style is consistent across all contributions. There is an + extensive testing and validation suite used to ensure that the output + produced by sectionproperties is verified and + repeatable, including a set of benchmarking tests. + sectionproperties has an actively maintained + and complete + documentation, + including + installation + instructions, a detailed + user + guide, a list of + examples, + and an + API + reference.

+
+ + Conclusion +

In this paper we have described + sectionproperties, a Python package that + calculates the section properties of arbitrary sections. It is our + hope that this project is used by researchers and practising engineers + to improve their experimental and analysis workflows.

+
+ + Acknowledgements +

We acknowledge the contributions from all the + contributors + to sectionproperties.

+
+ + + + + + + PilkeyW. D. + + Analysis and design of elastic beams: Computational methods + Wiley + New York + 2002 + 9780471381525 + 10.1002/9780470172667 + + + + + + LarsonM. G. + BengzonF. + + The finite element method: Theory, implementation, and applications + Springer Berlin, Heidelberg + Netherlands + 2013 + 10 + 1 + 9783642332869 + 10.1007/978-3-642-33287-6 + + + + + + GilliesSean + WelCasper van der + Van den BosscheJoris + TavesMike W. + ArnottJoshua + WardBrendan C. + others + + Shapely + 202310 + https://github.com/shapely/shapely + 10.5281/zenodo.5597138 + + + + + + RufatD. + + Triangle + GitHub repository + GitHub + 2023 + https://github.com/drufat/triangle + + + + + + ShewchukJ. R. + + Delaunay refinement algorithms for triangular mesh generation + Computational Geometry + Elsevier B.V + 2002 + 22 + 1 + 10.1016/S0925-7721(01)00047-5 + 21 + 74 + + + + +
diff --git a/jupyter/math/07_sympy_7d5b08.ipynb b/jupyter/math/07_sympy_7d5b08.ipynb new file mode 100644 index 0000000..2c8951a --- /dev/null +++ b/jupyter/math/07_sympy_7d5b08.ipynb @@ -0,0 +1,1681 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Symbolic Python" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In standard mathematics we routinely write down abstract variables or concepts and manipulate them without ever assigning specific values to them. An example would be the quadratic equation\n", + "\n", + "$$ a x^2 + b x + c = 0 $$\n", + "\n", + "and its roots $x_{\\pm}$: we can write down the solutions of the equation and discuss the existence, within the real numbers, of the roots, without specifying the particular values of the parameters $a, b$ and $c$.\n", + "\n", + "In a standard computer programming language, we can write *functions* that encapsulate the solutions of the equation, but calling those functions requires us to specify values of the parameters. In general, the value of a variable must be given before the variable can be used.\n", + "\n", + "However, there *do* exist *Computer Algebra Systems* that can perform manipulations in the \"standard\" mathematical form. Through the university you will have access to Wolfram Mathematica and Maple, which are commercial packages providing a huge range of mathematical tools. There are also freely available packages, such as SageMath and `sympy`. These are not always easy to use, as all CAS have their own formal languages that rarely perfectly match your expectations.\n", + "\n", + "Here we will briefly look at `sympy`, which is a pure Python CAS. `sympy` is not suitable for complex calculations, as it's far slower than the alternatives. However, it does interface very cleanly with Python, so can be used inside Python code, especially to avoid entering lengthy expressions." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# sympy" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Setting up" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Setting up `sympy` is straightforward:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import sympy\n", + "sympy.init_printing()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "The standard `import` command is used. The `init_printing` command looks at your system to find the clearest way of displaying the output; this isn't necessary, but is helpful for understanding the results." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To do *anything* in `sympy` we have to explicitly tell it if something is a variable, and what name it has. There are two commands that do this. To declare a single variable, use" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "x = sympy.Symbol('x')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To declare multiple variables at once, use" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "y, z0 = sympy.symbols(('y', 'z_0'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that the \"name\" of the variable does not need to match the symbol with which it is displayed. We have used this with `z0` above:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAABIAAAAMBAMAAACdPPCPAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMARN3vMmYQu3aZIqtU\nic3QRwAsAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAZklEQVQIHWNgYFQWcGUAg/SOmQUMvb1AdgLD\ncgbWCzwbgEyWMgYmAYZvQJY0A0O+A4MNAwNI3H8BgyoDw0kGhg3+CQwaDCyqV5sEgGIWDJwMwQ9B\n6j6CjYTpBXI4JoDNAwnfvJkAADBRFs6uZjB6AAAAAElFTkSuQmCC\n", + "text/latex": [ + "$$z_{0}$$" + ], + "text/plain": [ + "z₀" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "z0" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Once we have variables, we can define new variables by operating on old ones:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a=x + y. b=y*z_0.\n" + ] + } + ], + "source": [ + "a = x + y\n", + "b = y * z0\n", + "print(\"a={}. b={}.\".format(a, b))" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAADAAAAARBAMAAABp3DInAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEHarIkSJZt3NVLsy\nme8Q6PJIAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAu0lEQVQYGWNgIAJwKeBQRKyEkLKrGsQMmA6h\nSwwsDxkYE9ibOCaADYdJJKxjYPrAwCbA9pHLAVmCZcFNBu4NDIwMnBtAwmwzZ854OXOmAQNQ5BED\nvwJQCEyA5GBGsX5kOH8AyAcTyBK8Exj0gMoE9BmYBEDicB3cBgybGRjiF+xncAeLwyV4N7B+Z2AQ\nVhK6XoAqwWim+wUiAiVhljMwAG1BBowOEJ4lg3wAsjic3c6wCc5GYQTpHmBgAABmTiJzFz7aNwAA\nAABJRU5ErkJggg==\n", + "text/latex": [ + "$$x + y$$" + ], + "text/plain": [ + "x + y" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In addition to variables, we can also define general functions. There is only one option for this:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "f = sympy.Function('f')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## In-built functions" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We have seen already that mathematical functions can be found in different packages. For example, the $\\sin$ function appears in `math` as `math.sin`, acting on a single number. It also appears in `numpy` as `numpy.sin`, where it can act on vectors and arrays in one go. `sympy` re-implements many mathematical functions, for example as `sympy.sin`, which can act on abstract (`sympy`) variables.\n", + "\n", + "Whenever using `sympy` we should use `sympy` functions, as these can be manipulated and simplified. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "c = sympy.sin(x)**2 + sympy.cos(x)**2" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAJ4AAAAZBAMAAAAyHoooAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAMnZUZs0Qu91E7yKJ\nmaurDqYVAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACRElEQVQ4EY2UPWgUQRiG3/Uu6523YBTSJkss\njfHQIpImR8BOQYsFRZAlIDYiFopgQEMsRNJcKUEwESxExCvEaEC8xkJi4ArRJkIEFUQsIiEhmrh+\n8/NtZvb2mCzczvfzvO/OzO4NYF7Bp49m6oqd+AK+uTzMvhOfQl/DFDhiJ34Xb+oOD7O9A3wkNgXO\n2IlPSotKTTkVXavPx72HPJGgJaM5zn9ykD92wL1Nxk+q4BznFzjIH114uVnuJmVRzZKiIFRGBT2q\njO8dcQZ6jg7FFJfSbfNnVCvfrxNe2adUeJYkInqpUxrOqjDfLw/3DoyemvuHnqf7B0O2OUTB2OCr\nASp8VjX285cWq7jU/w5ClotfBCZwHrgTVv4ycBXwm8XJEimO237zVe+JN4XdoZRp3sKnY4S4CdwA\nVtnvNr2IOFgr0DYes/0iFFZKTXgrUqZ5Cy+tH4Twuwb8Zr/HND90XRFpH/2CKDrzKIqWqbolSlVg\nU8ooEZeF+2+TlvC7bvsBe0PBCj+69P6VxSNH6sC6lMmW9NvGX6C4kfWjBZBTt7jfE7fUL53flpSp\nHiz8CPA160cbXIgPY1fc9j4i6uxpobwhZdrPwodjjIvFmutdBB5Ub+E58UtKw9/LfA0L3iy6mlKm\n/Sz8/uiJem/yvTf5MvRnWQO0yMv9Yx9qlJ5WJfbzfw008Pr9DwiZpsWeZHDu6HH7/1aZUCX2y4Aq\nbcczWPt54DcyiJm242ZXxONccJxXGnPi6XmakvyA3NGJ7/i8V/YG/h/xYKmJCV3AuwAAAABJRU5E\nrkJggg==\n", + "text/latex": [ + "$$\\sin^{2}{\\left (x \\right )} + \\cos^{2}{\\left (x \\right )}$$" + ], + "text/plain": [ + " 2 2 \n", + "sin (x) + cos (x)" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAPBAMAAAArJJMAAAAAHlBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAACGjDitAAAACXRSTlMAVO8Qq5l2zWYZcMvdAAAACXBIWXMAAA7EAAAOxAGV\nKw4bAAAAHUlEQVQIHWNgAANGZQYGk5DJQDYbqQSr03QPsBkAJYgIYEZbtZEAAAAASUVORK5CYII=\n", + "text/latex": [ + "$$1$$" + ], + "text/plain": [ + "1" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.simplify()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note the steps taken here. `c` is an object, something that `sympy` has created. Once created it can be manipulated and simplified, using the methods on the object. It is useful to use tab completion to look at the available commands. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "d = sympy.cosh(x)**2 - sympy.sinh(x)**2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now type `d.` and then tab, to inspect all the available methods. As before, we could do" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAPBAMAAAArJJMAAAAAHlBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAACGjDitAAAACXRSTlMAVO8Qq5l2zWYZcMvdAAAACXBIWXMAAA7EAAAOxAGV\nKw4bAAAAHUlEQVQIHWNgAANGZQYGk5DJQDYbqQSr03QPsBkAJYgIYEZbtZEAAAAASUVORK5CYII=\n", + "text/latex": [ + "$$1$$" + ], + "text/plain": [ + "1" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d.simplify()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "but there are many other options." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Solving equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let us go back to our quadratic equation and check the solution. To define an *equation* we use the `sympy.Eq` function:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAALwAAAAyBAMAAAAU3awwAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMA74lUMhCZRN0iZrur\nzXa0OFAHAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADmklEQVRYCe2YTUhUURSAj+/55k8dg5IKkWY1\niyBU2tSmDAxqEfOECCJ/pogWZThFi3ZORFEQMquSWvhW0aaaTUIrjWiRhAr9bZyaJFyF2ZiJmk33\nnHvfzJvhzvtRgxZe8Nx7/r6578yd854PduVzwIYWRblB40GCQM35H7C1/TCuL93eIDRiQis6Tsfb\nW2EbLiBEl0DLjRCDNzjlkMAPpe2paoO9v8wb/F2Kn6CrKQsqqp29C0XFzaqvjaLM3a865IQ94vsN\nK14TF1PxQ7zih+L/FN8zuomnCsjEZnFkVRG2/6o4vherY4W93i+sJItQiowed28BBdNwaodFL1u+\nXie+ju1vqoxpUbvWiX/I8uctPLY8YFGVLCqlxan2cDdhtzV/Wf+04rUtiK9PowTRkEOLpLkRwSSA\nwv6sw4qHj+ipow8x8YEkRd+NftFxcYc0uQjHWfL4TAt0f7s3neUxJl6Z/QpwDm3qMnnE7ptTqPl3\nwmectSaUFUaNwSr7XlvSIqGBwCQPEvjgdcgAPCbbBBE5XtlOpg4DLvB4GxloATioQ07RlQWVGIWv\ntioCLwH2UXItIQmvTelk6tNhoAjuuoXjHUC+OJi3KgFwEbScBnVpCt6TyVzLZPCosnw2YmSF1iyb\nOf4mxzeC9pP7bCTiP4CfHc16BNAQxWkkReCPZJnGi+Ojhx0tB+ocRdgJLM4y+NjRjLWZcRzP8nFc\nJekrFgfgdIrZtHmomdxPTpmIDutoxq92EToMVf8OYbIUas9Oi2p+tc1tGMx3D/wIfIJHoxFmlJ4c\nJVU7iRlKHGAMhqG/ZQTM5iaK0wvaWYAzGOX/g9LEhxdR6Zw+Op7AhezcB1LVS+jzJwFOzBjQOdt9\n3kADGwKv7H7CFHYY2DXOoTTxLppCIBGkPYDkWVfgiRhM4lRPV2ritV/kshcq7zTY0srGSYsua2mO\nT2mYH8gSpSZFUyWx5oYc5UR2O7Ebz8nZM0qTODludh+KUwYUzotQS6c13Ax5b7wMV0pJdpqH3fPe\nWP127zM7YKnPA573xqp8np/lUk4FzQO+0BsroGRmD3hrb5ShZDZP+GJvlKFkNg94a2+UoWQ2D3hr\nb5ShZLaeOFnd/KysvVGGktlK/3UDu2cDWbqTLRahCLF7GNGdErz5+c3KbMgQi3tLd4jWVniAufsw\nv3k5ZLl2DzaYePHC5ekr17nOgWoT1RpfuJivi944Z7mOOGZQKHtd9Be+uw4jQeoQ6QAAAABJRU5E\nrkJggg==\n", + "text/latex": [ + "$$\\left [ \\left \\{ a : - \\frac{1}{x^{2}} \\left(b x + c\\right)\\right \\}\\right ]$$" + ], + "text/plain": [ + "⎡⎧ -(b⋅x + c) ⎫⎤\n", + "⎢⎪a: ───────────⎪⎥\n", + "⎢⎨ 2 ⎬⎥\n", + "⎢⎪ x ⎪⎥\n", + "⎣⎩ ⎭⎦" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a, b, c, x = sympy.symbols(('a', 'b', 'c', 'x'))\n", + "quadratic_equation = sympy.Eq(a*x**2+b*x+c, 0)\n", + "sympy.solve(quadratic_equation)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What happened here? `sympy` is not smart enough to know that we wanted to solve for `x`! Instead, it solved for the first variable it encountered. Let us try again:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAd0AAAAyBAMAAADrdhy+AAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMA74lUMhCrmXbNZiK7\nRN38cqFhAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAH6klEQVRoBe1aa4iUVRh+Z2a/ncu3M7uZSqXo\nJMGWRG0XMvCHAxn+6IdjPzSpnIFoM6FcKryE5RiVdsON0pwK/exXGuQEmXTBnaASI3CNCOrPTlpS\nFLqtl8xL0/uey/edM/Pddt3FZDvgd97L877vec453+WMC9PrQzBOWrRe74DL5945TuiCMfeODpg4\nXtgSzxaF7035/wDzMR6Ew9d4aPnF5zvmg3D4Amy8+HzHfBDefHeO+uZeGCajNukpK0xIGIxR5ChP\nvoneMGmGhUmHSanxfWFY+X3BP3CvJ9+DY7C5n/cdEXeqfNOTQgSEhCSKDOjF1wj1lorXh9MGk1bw\n4FS+C3J++LXDqV2HN1kuL76tRb9S0veZFML15slgnMq32w9uVv28zb4+tmG9+M6vNEc0Wx5pNvla\nfAnwSIVvy1m/ZK39ft5mH19BL76bmwOaLWZvs83XMp/NsS9E4Zss+iE/9nO6+FrY5vLga/pOrcwW\nDz/FnfuIarIkQz17hW9fxROFjqf8nLqPF99CRg++8Ro5g9riIIDtj1Zae1FJddgWL0Hh+7QXhuwG\n5QvXRPHthFb4rpi+2ZIJIiUp+fWP+zk1X6bCb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vv1rNcAAAAABJRU5ErkJggg==\n", + "text/latex": [ + "$$\\left [ \\frac{1}{2 a} \\left(- b + \\sqrt{- 4 a c + b^{2}}\\right), \\quad - \\frac{1}{2 a} \\left(b + \\sqrt{- 4 a c + b^{2}}\\right)\\right ]$$" + ], + "text/plain": [ + "⎡ _____________ ⎛ _____________⎞ ⎤\n", + "⎢ ╱ 2 ⎜ ╱ 2 ⎟ ⎥\n", + "⎢-b + ╲╱ -4⋅a⋅c + b -⎝b + ╲╱ -4⋅a⋅c + b ⎠ ⎥\n", + "⎢─────────────────────, ────────────────────────⎥\n", + "⎣ 2⋅a 2⋅a ⎦" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.solve(quadratic_equation, x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is our expectation: multiple solutions, returned as a list. We can access and manipulate these results:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "roots = sympy.solve(quadratic_equation, x)\n", + "xplus, xminus = sympy.symbols(('x_{+}', 'x_{-}'))\n", + "xplus = roots[0]\n", + "xminus = roots[1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can substitute in specific values for the parameters to find solutions:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAFYAAAAWBAMAAACoIHaoAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMlTvq5l2Zoki\nRLvZ+6rzAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABOklEQVQoFY2RsUrDUBSG/zSGJPYKwQ7FqRAd\nhSo+gH0DM7o2gnNEcHBpEMS6uTo1sy5dBNEl6gt0chP7BIK6VFTivefatOEGcg/k8N///zj3JAGq\nig0yUVUY5fZICyPoUR/FqT5rbOizTqDPNgDWf+sA9hh5Wd1czos7oIn6L2eT3G6evf9r6yI3AbHu\nAbA/Z3HplrJuAuwBvU4BVtkXnpv8aXuVrBty7lLO2/ZWzqWirsx9GIwAvi6vpW8Mn0nJprBojbE4\npNCMWHACLG+JWpu+W933V0PfjwTi/MD0iO3DwBcp2dS5bIJrytwYsKafSTgqi563SewuWFqL5BVk\nlLA7N7GIFmK4aSuQqwujbG4tpFlP97eHeGUJYaI5Rx/H8jD7x9aEnHaWfcK+kmmxz1isFxP1ZKSq\nR84fnlVKBHESW7oAAAAASUVORK5CYII=\n", + "text/latex": [ + "$$-1 + \\sqrt{2} i$$" + ], + "text/plain": [ + " ___ \n", + "-1 + ╲╱ 2 ⋅ⅈ" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "xplus_solution = xplus.subs([(a,1), (b,2), (c,3)])\n", + "xplus_solution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We have a list of substitutions. Each substitution is given by a tuple, containing the variable to be replaced, and the expression replacing it. We do not have to substitute in numbers, as here, but could use other variables:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAQkAAAAqBAMAAABSCbN7AAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMlTvq5l2ZiK7\niUTiBfEGAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEgUlEQVRYCc1WW2gcVRj+Zje73fsuFRpENOta\nFFFMwEsp1XTRF0EhCyJVVJJWEaxRVwVD6oNbfDBCYhcfagUvg4LoQ3FrQSUvCb6ItA+LiNQbLBQU\nfDH1CrZ1/f8zc66z2RjJhhzYmf/7vv//55szs+cMsPVG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9sqQ9afQUX/5Fgbf2wpDsMI29u9PkpLXF0mYK5letUvFZgre9ey0g/xutFsJt9\nbdBPA48aMBH5NJZi4S9+WP9t5MwLWyX5hcO0zAhqlyE8DLxQ1dj7W8dOtNdIcyQX0iLZb5xi0brS\naMlygc9XLX9jVSUqLEYpzWTETCXOa4ajvSW9AeI9WxscSpWt3oWLxgbIK8/mjKRvXSdeNzfRdNkS\nBweO2q3n1AYo+EdsdWDooNU53TA3wPALxMoYCHDm/D5kTxibKG0GA7mq2/Rja0kZaiB9wthE4d3k\nFgwCezdbXU/+cOZZYwMk7aTl0kreOMCfpsYY7XZ/MzdR+pCuGvKgwiu48b/2ZVTw8TqViQAAAABJ\nRU5ErkJggg==\n", + "text/latex": [ + "$$- \\frac{1}{2 a} \\left(a + \\sqrt{a^{2} - 4 a \\left(a + z_{0}\\right)}\\right)$$" + ], + "text/plain": [ + " ⎛ ___________________⎞ \n", + " ⎜ ╱ 2 ⎟ \n", + "-⎝a + ╲╱ a - 4⋅a⋅(a + z₀) ⎠ \n", + "──────────────────────────────\n", + " 2⋅a " + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "xminus_solution = xminus.subs([(b,a), (c,a+z0)])\n", + "xminus_solution" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAPcAAAAqBAMAAACdAtCRAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMlTvq5l2ZiK7\niUTiBfEGAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEgUlEQVRYCc1WXYgbVRT+Jtlkk0yyO7TQIv5s\nXMQiSg2oXVstzWPRh0QEfxDZFVSwrhp8WVcfDPjQFbZuUKgWXTsoFPHFqKDLVtlUBB/60FBEltLi\ngFDB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dp36btY\nFoDcoA6WurRzYoyO17D1kjzF3e3uYfiR1Qs3Gvje6cHSRM9n7+oAFlduDnzp0GAJWy/JU/JN3nbu\nYPlORA9ayE70cCb6dumJQ39QfowV2zFkmFpeput1R+qY0OgRGhQvEMZZoenurqqOPWR2YukY8ihz\nWoPUqtYc38RkudQ76yiL6/BhuqBuUeaczqdXxRg7pGuJo1xZL3mmi94YowPmklrW1suPyTGWL+ti\n0mi/XjDXhD/GWHhcV5NGe/SCb2ljzD2A9YgEUejG0ol9WIwxOtgT7BUp9Zna8gG9G3hbjDEYtwdS\n8o5xh1bT3Hlqb0WMMeBT/cdp0RcL1Btfr0iK3qMqYozRq2u1pybtXccF/wGL00NZdTkP2wAAAABJ\nRU5ErkJggg==\n", + "text/latex": [ + "$$- \\frac{1}{2 a} \\left(a + \\sqrt{- a \\left(3 a + 4 z_{0}\\right)}\\right)$$" + ], + "text/plain": [ + " ⎛ _________________⎞ \n", + "-⎝a + ╲╱ -a⋅(3⋅a + 4⋅z₀) ⎠ \n", + "───────────────────────────\n", + " 2⋅a " + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "xminus_solution.simplify()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use similar syntax to solve *systems* of equations, such as\n", + "\n", + "$$ \\begin{aligned} x + 2 y &= 0, \\\\ xy & = z_0. \\end{aligned} $$" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAhgAAAA/BAMAAABQnKyEAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMARM1UEHbdIu8yibtm\nq5lTG27OAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAJcUlEQVR4Ab1cTYwjxRV+tttu22OPzQVxIeMQ\nxM9p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8T33Ooitc/yqwP9Y4D7xR8DBKMigzix0n5Y/iOnd6HKZzga+WOAe/4PUwT3\nz3GFOWgAAAAASUVORK5CYII=\n", + "text/latex": [ + "$$\\left [ \\left ( - \\sqrt{2} \\sqrt{- z_{0}}, \\quad \\frac{\\sqrt{2}}{2} \\sqrt{- z_{0}}\\right ), \\quad \\left ( \\sqrt{2} \\sqrt{- z_{0}}, \\quad - \\frac{\\sqrt{2}}{2} \\sqrt{- z_{0}}\\right )\\right ]$$" + ], + "text/plain": [ + "⎡⎛ ___ _____⎞ ⎛ ___ _____ ⎞⎤\n", + "⎢⎜ ___ _____ ╲╱ 2 ⋅╲╱ -z₀ ⎟ ⎜ ___ _____ -╲╱ 2 ⋅╲╱ -z₀ ⎟⎥\n", + "⎢⎜-╲╱ 2 ⋅╲╱ -z₀ , ─────────────⎟, ⎜╲╱ 2 ⋅╲╱ -z₀ , ───────────────⎟⎥\n", + "⎣⎝ 2 ⎠ ⎝ 2 ⎠⎦" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "eq1 = sympy.Eq(x+2*y, 0)\n", + "eq2 = sympy.Eq(x*y, z0)\n", + "sympy.solve([eq1, eq2], [x, y])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Differentiation and integration" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Differentiation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There is a standard function for differentiation, `diff`:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAARAAAAAUBAMAAAC3wn+EAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIpm7MhCriUTv3c12\nVGZoascqAAAACXBIWXMAAA7EAAAOxAGVKw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v3B4S8oXckta9qN3YHWAVK2utUCyo2Dl52va4SCwi8OcxK8A7LYs14X/A+Xe\ngqD2JCNB/sycxGyLz6USluv6T5B8ncv7CCnJN7y8UolQduVtkZIA/QNzXD11A2h55wAAAABJRU5E\nrkJggg==\n", + "text/latex": [ + "$$2 x \\sin{\\left (\\log{\\left (x \\right )} \\right )} + x \\cos{\\left (\\log{\\left (x \\right )} \\right )}$$" + ], + "text/plain": [ + "2⋅x⋅sin(log(x)) + x⋅cos(log(x))" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "expression = x**2*sympy.sin(sympy.log(x))\n", + "sympy.diff(expression, x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A parameter can control how many times to differentiate:" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAASgAAAAqBAMAAADyltuVAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAVO8Qq5l2zWYiRInd\nuzLEnmxuAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAFAElEQVRYCe1XXWhcRRT+NjfZzd1/FESlJS21\nKn2QJcSKRGlQ0EaLrj+VSkGutF2VRcyDEPqj3ZemFhWviFK0wVX8eVDMoiZqI7q+tAb/NhKqFYpL\nCRVFmqRp/Ulp13Nm7sxcdzebPCV5yIHvzjnfOTPn7JnZnbvA0pTAmqVXV8f900uvKASXi5rnrix3\nap6NWj5T823UcqeWOzXvDswzsOWWvzfKUDs315SDtQGKOkAuRmOpk0JRrS6g4Fuk3+ivDY96Rvxq\nw9ql+O0FY7Jmlzy7mdZkNJZ+jO+uitBZu8mhYGJ2atVOoy0nrfh5zSLkor3LmKwRJcXqARiNZSes\nq6oidNYbyKGgY1rTWg1OIVHUllb2AbEubQmF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KWJJ68Uj5DIU3w4Keo65GjVVpezTdqBEh4gAQ/FlzGCxXDlWP30p\nVpLveYKh1GXMo5HjRq2viXMhXNb3dLySpGqKX1sYjcWkuKkMjHKwptRrC49G+o1aX9NvdHR9DWUf\n4iBNcXW6wvrTiTUprOHMYJnjNMXVKbBDinoxVXbtyN+RKlHUAeIZjaVOCkWpV2Ee4V3RjRdbYK+6\nohc4beN06opuHLXAXnVFL3DaudIlnLkiFsEvr+hFSDx7SnVFzx6xCB51RS9C6tlTqit69oiF9/wH\n3sx3bS/twOUAAAAASUVORK5CYII=\n", + "text/latex": [ + "$$\\frac{1}{x} \\left(- 3 \\sin{\\left (\\log{\\left (x \\right )} \\right )} + \\cos{\\left (\\log{\\left (x \\right )} \\right )}\\right)$$" + ], + "text/plain": [ + "-3⋅sin(log(x)) + cos(log(x))\n", + "────────────────────────────\n", + " x " + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.diff(expression, x, 3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Partial differentiation with respect to multiple variables can also be performed by increasing the number of arguments:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAqcAAAAcBAMAAACuWQuoAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAMpndu3bvImbNiRBU\nq0Qb3U6NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAIVUlEQVRoBeVYe2xTZRQ/XbferbctE2WJRl0x\nQwUkThSfUapxGmMMzZL5AA2TgI+AWAlBosY1GokxMS4BTeqzEgmKUa8PYlxCaAyiiQ+mEd9I/QP+\nIJoBgooD6jnf+5bv3rZL//PL1ntev3N+59zvu7cbQN0r3jOz7lge2DgivMD6a7zQgAnUmwDESmGi\ne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/mZ+DFZt+ZXkxsG3Ql04O1f2p\nX27Q9kGRT5byNUC+LdM2gjPjrXLq9VvfJr1xirB+ViduFsRHdh97d/ex0+fdh3kCuBmtMm6yX0RM\np/JqVzHF/OBu0yJkuQ+FqjoVCdHcI1xyQEK1X9S3UO7WGHyq8tWSEYIuxQyBDKub0jgFqY9iIDeV\nh3GTyZLDLr4uccXK7FL1odxVdlKrEB/yEBPxrEC57CwIJfCy3OeRmB9ha1k4OrJCEKWYZtYTbn1p\nGkUrN7M04yb7jeZbOdWWouaiJeXWJiXVRLjyLyAFCRVmWL2XQp+0b/WkZFzDGELTKFq5maWJm+o3\nNTCVM4wMGkyVqNzKooWaiPZRHVyH1GWN2dPfKe1PS8G8hjGEplG0cjNLEzdLv7+YVOuSayGiahx1\npUuWaoRdUMNvcTeLYl3cLP1+ZOEUbqqFeCocXu11h6stfr296Nfr0ZpFsS5uln4T6XpYmjE1EE7G\nDK5D/jg8ZmW42+ptGsU6uFn7/cpKK8wYjmjxwrAWX6JsMWrTTC3WLzWLYh3cGu63/i7+35H/AQls\n+Pp3bDD7AAAAAElFTkSuQmCC\n", + "text/latex": [ + "$$4 y \\left(- 2 x y^{2} \\sin{\\left (x + y^{2} \\right )} + 3 x \\cos{\\left (x + y^{2} \\right )} + 4 y^{2} \\cos{\\left (x + y^{2} \\right )} + 6 \\sin{\\left (x + y^{2} \\right )}\\right)$$" + ], + "text/plain": [ + " ⎛ 2 ⎛ 2⎞ ⎛ 2⎞ 2 ⎛ 2⎞ ⎛ 2⎞\n", + "4⋅y⋅⎝- 2⋅x⋅y ⋅sin⎝x + y ⎠ + 3⋅x⋅cos⎝x + y ⎠ + 4⋅y ⋅cos⎝x + y ⎠ + 6⋅sin⎝x + y ⎠\n", + "\n", + "⎞\n", + "⎠" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "expression2 = x*sympy.cos(y**2 + x)\n", + "sympy.diff(expression2, x, 2, y, 3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There is also a function representing an *unevaluated* derivative:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAANMAAAAzCAMAAAA6nc1pAAAAM1BMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADxgEwMAAAAEHRSTlMAZnaJIhC7RM0y\n75ndVKsgyGZyxgAAAAlwSFlzAAAOxAAADsQBlSsOGwAABM9JREFUaAXdWQmT6yAI9owx1/r/f+0D\nFWLM0cZ9O5PWmd2SFAQ84IMK8Xr4xRspX/N9EocLISyfZPAbtrrZ2zfYPorFuY8y99JYqbQ2wOFG\npcbv2Cn0x3awRwb+ZHfp/od8KXs01A/JXB9wxz59jMmbIMUC586GL7pU0ygG2CITvuNCeTkLETqh\nwR09fvq5Q/t9L63RPoAzWo/6G1xyg0c3uqC+wZvog8m+TF8UG5YcE4Ycyx+5WXrs7mCBELMThPAH\nXyQEBUuy850ltxgaYKi7Idw3prEWuQl8iliArzwTRz5auk43t8k3QqgmuQlxG953R5UQE0c+iS6y\nLXdN7Bszc6ucmONB0lSxMnHklJkgO413E+14uflHetK7VjkhpqRxorVk4lDZrOVd2NoKoFrlVnij\naPWZOPSp4WUrgGqVE5JcMSGby0SD+YciA+DDlnEpN5+fZwcRzEW4Iya6UUy0GLKX8XcDf57iWu7c\nJ9/P89ylmzRSNGNib1/LG9mIOa7lzn0aoJ8V8qFTpJuJFg/2MmPO6VapxTil6dDYEYA9HkurldKY\nlL2apWIEcCaXNFQ+WRWDpBko0iUuR2eEifT+t/+7tP8WTrmEGDtlow1eFw+FpcfELzoFXQ5UNZG+\nE7n8deWTFjNuiaKgkLl8SPcKgEUmaPbfffYpnccSEpZtzqmgR99mUDVFUAJKXVxk2kZxIpeN2fpk\nZhG3Na8DGxzxBD4hEc/kr/7xvFDm48BD0dOVxU5GDrg+pLAIsHgKnVqT37EcJJ8exzTEjwx/YPIB\nF6Mu60yeHHxqDL5o+n7k9cYvCpWO6DmXYtANsLoP5CosAMG1jRzNv90nCN54c3YnbLNPJPofPlfb\nSpX7fRoNbqXkavNYjgyqfYpHbxfduFfHBMlvPl9VXFqN2CVbR0a8s003WOUv432CGyWGeAhdcMnM\nhdLkiVyeuPYpousEsVfVaffw+TLuvaq4RjBpm+DS4jk40B1EJUMmmwEpmM7HFkePkQvd7ehGncih\nhTBqn1Cng67jdnCOW4ncGS/5uOLCl9Q6LxiwlSQ3ETUtkV2UgiRS/GBll1HhCgkDiWrBekdLJWOi\nivOdySVltU92gQOy6wrz6hKBCmNnvDBZcMUFLw8Z4D1NkOUGzKcN41Ku9gnnpyy96uopM2Ri2xlf\n+TCrxDtxxmBTv4wlWruAl3KWjmhSgw2IfaPbEowgYu2Ms3WZyBXXCYPixcns9INBPc2r5ztyiLsB\nilRDUjpgIjHk1FdwV3XNnqE6e2JpzHc35Bz8FrZHPxO9YkJQZ7zwB0iuuCDH5db5lgFS39YJy7i0\nYnzx2CpH08qIuuCJiaIzXkLqteLaMGRY/IN3ydQxdabCk7S9+dkql6Y3hMSYKDrjJaReK66CQayw\nGGO9rBA/RJXG0NcqF53iZiwRZWe8hNRccZUMBSz2WullG5Pe3JS/Zys74xi5C0idlFcMh7D47828\npaHujBOM5km2DMewmJkfQRBsps54CamjgRXDMSx+hCtsxKYzXkNq5NowQL7D7LaDxTzdM4hkX8T7\nO0gdLSwY4BnT7B4WP8MVtqLojO8hNXIVDPB0DIt5tqcQLzvjNcMeFj/FlSY7jmFx01SPETqGxY8x\nr8mQY1jcNNWfCf0DhT0mZT1jGeAAAAAASUVORK5CYII=\n", + "text/latex": [ + "$$\\frac{\\partial^{5}}{\\partial x^{2}\\partial y^{3}} \\left(x \\cos{\\left (x + y^{2} \\right )}\\right)$$" + ], + "text/plain": [ + " 5 \n", + " ∂ ⎛ ⎛ 2⎞⎞\n", + "───────⎝x⋅cos⎝x + y ⎠⎠\n", + " 3 2 \n", + "∂y ∂x " + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.Derivative(expression2, x, 2, y, 3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "These can be useful for display, building up a calculation in stages, simplification, or when the derivative cannot be evaluated. It can be explicitly evaluated using the `doit` function:" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAqcAAAAcBAMAAACuWQuoAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAMpndu3bvImbNiRBU\nq0Qb3U6NAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAIVUlEQVRoBeVYe2xTZRQ/XbferbctE2WJRl0x\nQwUkThSfUapxGmMMzZL5AA2TgI+AWAlBosY1GokxMS4BTeqzEgmKUa8PYlxCaAyiiQ+mEd9I/QP+\nIJoBgooD6jnf+5bv3rZL//PL1ntev3N+59zvu7cbQN0r3jOz7lge2DgivMD6a7zQgAnUmwDESmGi\neTbCj9Z8wcbGEcG50BPPJYdDAyZQbwIQK4XwPGdaMWS8BLpzNmc4os0GCbNFykHeaC7yN2SDvGgP\nYgjNohjMjZUmbrZ+I5lA0lfBUNnirIFIjVowYaZTAp3RsnMc/gh0AwQwhKZRDObGShM3W78dXgjp\nHTZnLcTrIQltrhdsRmFLjEM8H+IHK0NoGsUwbliacRP9TjZoTtPyip6rtcKkOUKPLDEcBsKwChER\n0eo74Wx6rXRipLS0ZKVkuUbRecWJdt2AZOiPaZgixDe8KlJ0GXxCuVFp4ib6vUhTcMaV7I7CO2Wl\nkRBPCzXyrxDwYiC0UUqEaMNf31oBiX98Bp8yVH0PTO96VPpNA5dVA4qhL6Zxiu7LMF2k6C7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S8G8hjGEplG0cjNLEzdLv7+YVOuSayGiahx1\npUuWaoRdUMNvcTeLYl3cLP1+ZOEUbqqFeCocXu11h6stfr296Nfr0ZpFsS5uln4T6XpYmjE1EE7G\nDK5D/jg8ZmW42+ptGsU6uFn7/cpKK8wYjmjxwrAWX6JsMWrTTC3WLzWLYh3cGu63/i7+35H/AQls\n+Pp3bDD7AAAAAElFTkSuQmCC\n", + "text/latex": [ + "$$4 y \\left(- 2 x y^{2} \\sin{\\left (x + y^{2} \\right )} + 3 x \\cos{\\left (x + y^{2} \\right )} + 4 y^{2} \\cos{\\left (x + y^{2} \\right )} + 6 \\sin{\\left (x + y^{2} \\right )}\\right)$$" + ], + "text/plain": [ + " ⎛ 2 ⎛ 2⎞ ⎛ 2⎞ 2 ⎛ 2⎞ ⎛ 2⎞\n", + "4⋅y⋅⎝- 2⋅x⋅y ⋅sin⎝x + y ⎠ + 3⋅x⋅cos⎝x + y ⎠ + 4⋅y ⋅cos⎝x + y ⎠ + 6⋅sin⎝x + y ⎠\n", + "\n", + "⎞\n", + "⎠" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.Derivative(expression2, x, 2, y, 3).doit()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Integration" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Integration uses the `integrate` function. This can calculate either definite or indefinite integrals, but will *not* include the integration constant." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAO4AAAAaBAMAAABCw30eAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEHarIkSJZt3NVLsy\nme8Q6PJIAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAD10lEQVRIDbVWXYgbVRT+Jpl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+6vI9Xq0bmO0uc4Ne/c9QlmuLZhx\nVNVrSCvO9WZweOFGYKX3b4d42lylzBm0+7zS6/2lEwfmAR9j15miYpvvyb53kJJbvN90bj9OqBcp\n5TYk0uerxBafb9GzpJ+xkd8FLRjwb1P2OP0Svgu7BgoTEuc5etRNJfxIouHvoBYM+KvavF1kHyo8\n/B1UPMHvni9/Z2H73bc3YKmEwFko1duMH1LS3oAC2/V80tmOGbfN6zb+z/kP9lzyp+P2rN8AAAAA\nSUVORK5CYII=\n", + "text/latex": [ + "$$x \\log^{2}{\\left (x \\right )} - 2 x \\log{\\left (x \\right )} + 2 x$$" + ], + "text/plain": [ + " 2 \n", + "x⋅log (x) - 2⋅x⋅log(x) + 2⋅x" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "integrand=sympy.log(x)**2\n", + "sympy.integrate(integrand, x)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAARQAAAAaBAMAAACEI76OAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMiKZu6uJRO92\nVGZ6zyUAAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEL0lEQVRIDcVWXWgcVRT+JrvT7Uyy27WlYomQ\nNCi0hWJB86C2OvgDAR+yUNAXbUaR1LQg+1Lig5W1sYI+mKVoMBLKYn3wrRGLiCLdJ3Uh0IWCFa1k\n8aGlVJBgaZtUXb9z753Jnd2pRIT0wN455zvnO/ebe29uBlh/8w6+uP6Tps/4AY6lJ9YfHcZoaf1n\nTZ3xEYzVUhN3Alws3olZU+fcm4quCTxgVRX+/z57oerntlbb2l3d8ckAzsSVAMgeq67WiOeWTXz3\nyfeB48mkie5tHErDFQMjOxO5Szp6zoCdXe+Bt4KepjPMfH/F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JI7NGxPhJsOPK3zTVeFj/+dFKJRIeodG1PZ3ZhJohLo08n\nBay164GYzi1LLJGV+M9uxwflP9x/SR6zRszCAAAAAElFTkSuQmCC\n", + "text/latex": [ + "$$- 20 \\log{\\left (10 \\right )} + 18 + 10 \\log^{2}{\\left (10 \\right )}$$" + ], + "text/plain": [ + " 2 \n", + "-20⋅log(10) + 18 + 10⋅log (10)" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.integrate(integrand, (x, 1, 10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The definite integral is specified by passing a tuple, with the variable to be integrated (here `x`) and the lower and upper limits (which can be expressions).\n", + "\n", + "Note that `sympy` includes an \"infinity\" object `oo` (two `o`'s), which can be used in the limits of integration:" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAPBAMAAAArJJMAAAAAHlBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAACGjDitAAAACXRSTlMAVO8Qq5l2zWYZcMvdAAAACXBIWXMAAA7EAAAOxAGV\nKw4bAAAAHUlEQVQIHWNgAANGZQYGk5DJQDYbqQSr03QPsBkAJYgIYEZbtZEAAAAASUVORK5CYII=\n", + "text/latex": [ + "$$1$$" + ], + "text/plain": [ + "1" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.integrate(sympy.exp(-x), (x, 0, sympy.oo))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Multiple integration for higher dimensional integrals can be performed:" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAA0EAAAArBAMAAABMVJ5LAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAA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52gSVTy3wP0OXyVi9XFMY4NeLh9VMuuTVJqhLfP8P07UMfA8/p503\nXIzGPgAAAABJRU5ErkJggg==\n", + "text/latex": [ + "$$- \\frac{e^{- x}}{4} e^{- y} \\sin{\\left (x \\right )} \\sin{\\left (y \\right )} - \\frac{e^{- x}}{4} e^{- y} \\sin{\\left (x \\right )} \\cos{\\left (y \\right )} + \\frac{e^{- x}}{4} e^{- y} \\sin{\\left (y \\right )} \\cos{\\left (x \\right )} + \\frac{e^{- x}}{4} e^{- y} \\cos{\\left (x \\right )} \\cos{\\left (y \\right )}$$" + ], + "text/plain": [ + " -x -y -x -y -x -y -x \n", + " ℯ ⋅ℯ ⋅sin(x)⋅sin(y) ℯ ⋅ℯ ⋅sin(x)⋅cos(y) ℯ ⋅ℯ ⋅sin(y)⋅cos(x) ℯ ⋅\n", + "- ───────────────────── - ───────────────────── + ───────────────────── + ────\n", + " 4 4 4 \n", + "\n", + " -y \n", + "ℯ ⋅cos(x)⋅cos(y)\n", + "─────────────────\n", + " 4 " + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.integrate(sympy.exp(-(x+y))*sympy.cos(x)*sympy.sin(y), x, y)" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAI4AAAArBAMAAABcAq1mAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAVO8Qq5l2zWYy3bsi\niUSr8q8rAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACEUlEQVRIDWNgoDYQMiBgIk4FjMoIncyu/vjN\nwa3AJOQzwhwGhnz85uBRwDZqDiggcQbgaPiA0xl9wydEv6QBbC0uAqcCVqfvHrg0DUZxxgS8riIg\njdBLQCEB6VFzUKPhPxYADCPe8vIq9fJyB1BwoatAleYHS4PU4QAEIoSANMJQAgpxS1/dilJl4FYI\ntgunNO8BlgKEaxgYcCqEKMIpzXWA8w9F5kyF6OZ6wPMPuzlHo3ciS0DYSO7hDAALrYYpYvzMU///\n/08ol/kAjOHAcP8BmI1VmoGBawNIlk0brAZIcCWwzkwORglskBSLAQOTAojBgFWagSEJbM6JarAa\nIHGVwYDtQACMB6eZFjCwQByJVZqBpx1szgWYORxAI7h5MM1h/wwzB6s0Ay87yByOA0BzmK+lHmB4\ny/CS4TSfA9wdSAyuzxAlWKV7wOaYMQDNeXWA5wJnoeBmhghOBSTtcOb7C2AlWKWZE8DmXACaw6PI\nYDqB6f//DwxrGBbDNSMxlkCUYJXmZQCZwzgBaA6LRlozki4MJmsAHiWSYHNsGYDm8DtgaEURSGXA\nrYT5AtgcEReXT278F1C0oXMYAxjO4FTC6OLir5IA0qLNwAQ0B8wEcTEBMOPk4FPCBIp3BobfDGwF\nDKYHwGxsBM/auyEL8CnhB5tz+78HQ2pGAzYTIGLswJJzAR4lvPu/4NGN21xsMgClwcIux+i3tgAA\nAABJRU5ErkJggg==\n", + "text/latex": [ + "$$\\frac{1}{4 e^{2 \\pi}} + \\frac{1}{2 e^{\\pi}} + \\frac{1}{4}$$" + ], + "text/plain": [ + " -2⋅π -π \n", + "ℯ ℯ 1\n", + "───── + ─── + ─\n", + " 4 2 4" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.integrate(sympy.exp(-(x+y))*sympy.cos(x)*sympy.sin(y), \n", + " (x, 0, sympy.pi), (y, 0, sympy.pi))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Again, there is an unevaluated integral:" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAHQAAAAuBAMAAAALoSCFAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAA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uaM3agC\nNdVGIA6HIzgTLgpWLOoXgwPh9NGJqPv9B1boo+M9lsVhAAAAAElFTkSuQmCC\n", + "text/latex": [ + "$$\\int \\log^{2}{\\left (x \\right )}\\, dx$$" + ], + "text/plain": [ + "⌠ \n", + "⎮ 2 \n", + "⎮ log (x) dx\n", + "⌡ " + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.Integral(integrand, x)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAHQAAABKBAMAAACYxG3JAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAMs2Zq91U7yJ2iWZE\nELuNX9C8AAAACXBIWXMAAA7EAAAOxAGVKw4bAAADSklEQVRYCe1VPWgUQRT+9v5/sruHItrlQLCw\nkBMUISIcQsBYmFMsRIRcYdRCScBGsHBBLdQiJ9okGLMhpjhBciCCaOHGRrS56yJpsigYLCQXCTFq\n4vl2Z3Y3uT3M3ljqg9t573vft29m9s0cQLYFSJZ1y2vXtnYDL3C2XZnN7wfOQK2JaPshLyJeFJNK\nK4hWBKVriJYEpSuIC0ppraohVlV4h88D98S+6/W+HqS6DonM91/ThB8Ldb+1Tfdn8oK7Ja+KtTCV\nS9YFawJRU1g6JHRs7HJjhnDVBeFPg28tik58DPI+ackvTWmRrB/1IcnvPghRje66zU1Z9XOiRqIF\n6uOpaz6IgFhLtInZWWgC7DBQb77Kt5JOMPAOzz1vxUGv3UzSYX19Np2zo4TJwYjGHGmeJVjUZ9jj\nxoP3DtMWGtLsHCBnuaMWuUOD3KjZgZL3MEi7zn2xwqcuVuZelbHtKMabaYM03mjUrewpLgBmuDfp\nIkDqFws2SHk+UXCJIYO5O12ElvODBSSVyyMGOo4eHDZ5PpmjBQ0feUuzDZOLRNfdZQegUF1mPJJu\n0/AZ1Vq0UuJSpQLM4lnpBJDOEvZGU9YcgMIh3qwkPQ10ZroRKXAlokXgCaZqF6i7CJSvIpx1AOIM\n1BlRyUtUX9UPrJPGDaCGPRZBIlqY/sN1ByBsKksPMiUfo45XzaHMTNEG6GFJAftkWdK4iTnDAWhc\nyNGDjFfN3SqPM4Ce1oQhLVpxRwGY0zHgAuRcK9KDjNZ6GagaF1nIsApwie7aUbZNc0V8iGkc8JoJ\niontGezG6+kdrjiVQ8eyUk/QG8I6fcdS+mTKAWgivJmk3iUt0fXIQKjRoOrMaJZyz+i9lxSFMlSm\nZ/zGAwegq7/5ZvqE9/0lR+s14k0H8sbIT8+3vJhJ66IfM3/7Oxkao/b+eYB8nHas6MSKxj0560De\nqNY93/ZmyyN7Xcg96u473BR1nrku8Lt/umDGdD8/INJrBCT6aX1+KCjyNSjRx5P4HeFLbA6kmz7r\n5gqXERl03XYdVW9X4fKrdCCEbBLHhHQkmpeuiEpvPxSdr2jFv9VJWdE3SPsKolL7n0RQbP0JCdp/\naaCNiw0GorUgJfYvlVrAAaDftrjPkt1IQLoAAAAASUVORK5CYII=\n", + "text/latex": [ + "$$\\int_{1}^{10} \\log^{2}{\\left (x \\right )}\\, dx$$" + ], + "text/plain": [ + "10 \n", + "⌠ \n", + "⎮ 2 \n", + "⎮ log (x) dx\n", + "⌡ \n", + "1 " + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.Integral(integrand, (x, 1, 10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Again, the `doit` method will explicitly evaluate the result where possible." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Differential equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Defining and solving differential equations uses the pattern from the previous sections. We'll use the same example problem as in the `scipy` case, \n", + "\n", + "$$ \\frac{\\text{d} y}{\\text{d} t} = e^{-t} - y, \\qquad y(0) = 1. $$\n", + "\n", + "First we define that $y$ is a function, currently unknown, and $t$ is a variable." + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "y = sympy.Function('y')\n", + "t = sympy.Symbol('t')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`y` is a general function, and can be a function of anything at this point (any number of variables with any name). To use it consistently, we *must* refer to it explicitly as a function of $t$ everywhere. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAUBAMAAAAevyJ8AAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEHaZIu+JVM27RDKr\nZt2dj8xZAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAA8ElEQVQYGT2QsUoDQRCGv425i3fqcWWKoIs+\ngAFBIgq5RkKKwD2CWFnaC5paGwsbwSJP4D2CIjZ2BzY2QgqxFju18Z/LJT/M7rf/7g4zA7VGtq9l\n9Qma1xU+L4xl3a1ntBfGq+gCQj93PgQ9cHltNKeCT8UlbstzmDa6xC8/T7BD2MrZJiqh9aUXbwyW\nxtySnIIAzkkDzzfBBJIj4AGKdOWPYAIbCjN6NPLqS4GDe7gjeqySnnBmSdmjKAm7cOA87ELnuJ8R\nT2H4rhxXCisZK11Sxatj9yuy5iQ1l5SRF0WZFqz9eHPfqB7QjfFM8xH+A2BeLPY/vHjEAAAAAElF\nTkSuQmCC\n", + "text/latex": [ + "$$y{\\left (t \\right )}$$" + ], + "text/plain": [ + "y(t)" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "y(t)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We then define the differential equation. `sympy.Eq` defines the equation, and `diff` differentiates:" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAL0AAAArBAMAAADfxpRdAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAMrvvmVREEIndzSJ2\nZqtw62vAAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADH0lEQVRYCbVWz2sTQRT+ml+7zTZN/oMGPQhq\nqxf1YiEHD7UUiXgSBAM9FaQt2Iu1kBV6aekhIIKlKAkUDxEk9OZBSTF4UulBEBQheBLtIQjag4i+\nN/M27G4nPTkPdubNe9988/vtA1iGjpdUba3Il61RK+KFRbv8a3bpsW2T35va/WmTf7aVOLDI70wi\nVbfInzrAsG+RP1lEtWKRv+rjpiX6BvNWyziZbtkYwVHXJtvOPXZt0CNdY1pn/97L1yF+b48bn0IW\ns/qCzbkjFu5d3i4Yuu4o2+gRHRXAK6rquyrNRbZssj+lJW3BqZt8IVuWJnCnheWQKa7mTXPMlYB0\nD9iIo2Pt99Sme+e2xX4j5E8fIzmB2ZCprw7ToPyeb/ctZmWLzNO01LPiDvOL6Z1jWMBzcvJ7zlYE\nZa68Gtkf0vdE/Ab+mei1XJmBdwEdYP7MRBupknSMVxo2UkLmy4994FKM39noBLOe34309a9hpIdx\nsvF7ztXZ6TaVlFgX0bDEnj4mfBRzMP+5lucH0EjtlaeRKOIBGWlf5XFEEKohsOGyPiZcF4jwe+ew\nVDjciywOLiLfxnlSeV+HejHU8iZLQ2DJij4mjDFsvdm832w+I2108s0HtgTyN5AeMgcYKzC/84u8\nh/iDHhqWrFDkok/zUy3zz3dJNwvdylfg/cn0sIhMjVGumvRmN9RDw3h/FmjNmBNXwO+HoFE10cUE\n+Hzderog5xtFqJaG8fmu4yri55v0gbahF5lSxcwfYJWU7goVPplMomFuCbjitIEpwcj8R+pYapm6\n0bZ/7fxW6/XGaXLZghklMN6+nc8EaUT50XlLnQcIbS04PrDwOx4gDAPHBxL1jlmR+bMakyC7/aYu\nBMc3loHxTcPA8Y2kH9/u6rappOyWIi0e4TR7TynI4PgssIRe51HxORiLsluOCLc6Bbbo/4t0DyCh\nWmDyf9GzCbkN6pqOCOL5b//H/kiU3XJEsCOc3epIa4dfZbf8Q7QjOrtVN9rKADq7tZfg6uy2WrEy\neSKtquxWRVorQ+jsVkVaK/w6u1WR1gq/zm5VpLXB/w8+d8o2RW/FAgAAAABJRU5ErkJggg==\n", + "text/latex": [ + "$$\\frac{d}{d t} y{\\left (t \\right )} = - y{\\left (t \\right )} + e^{- t}$$" + ], + "text/plain": [ + "d -t\n", + "──(y(t)) = -y(t) + ℯ \n", + "dt " + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ode = sympy.Eq(y(t).diff(t), sympy.exp(-t) - y(t))\n", + "ode" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we have used `diff` as a method applied to the function. As `sympy` can't differentiate $y(t)$ (as it doesn't have an explicit value), it leaves it unevaluated.\n", + "\n", + "We can now use the `dsolve` function to get the solution to the ODE. The syntax is very similar to the `solve` function used above:" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAKgAAAAYBAMAAACcr6vyAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEHaZIu+JVM27RDKr\nZt2dj8xZAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACs0lEQVQ4EbVVz2sTQRT+NrvJJps2LP5CQXSp\nCHoQi7+oWDQgVTzU5uTV2FNPWvQkgi54MKhgD14KEXPxJibgH2CoehAUgnrwIqwQxYPYIKKoFXzv\nZXZ2ktRb+mDffO/7Zl/m7ZuZAEO3bGPoKYHt/hokvboGOY9/PqKzTjMaLeo4AaIkYR962xcDNzTj\nLAh8pgkNRLF2v3zllDVngJGiEQj8roksaduK2KwJDVjBzhbcgy3NxcBqwwrjAJcXyXyvpIk3hK4B\nmUAzMWBlywdyx4oxhYsKuR1gVrNdkGpuiJk2gQnASn7GVO74FD2IGeikdghsTGhBdlBWjBMR+ETP\nTUXogRX7J4ePNaeTFspAtpbwjLylBqwdAab81Di8F7+WgP29MwBSMBMxq6vSK314vxrApgnAprED\nPCjLuCXsRa4F8AfCO6HnKmzXGbNyIRAW+bA76pVSFzDKpNfGCaXxcJK+yyIK81RkSOHAcWBlucEz\nkZ+MZNQr5S7AjchNzVvJlgf8dIBvSNcA/kB4Qk+PpWvAWZ8pH25EA6iMj5XKbYbchXyH3PPXe2QO\nk2x1P/8H6RpdBPSsnnSZBLgNuBGNbGpLWb8JS9IVoRM3gVRJyq/DAh6JcP4r2xfGXL7sUFtVyqRK\n6nVo+V5ExA9mDasi15R2zOFK3ChD5kbNlIk4N5g0E9LypVFnaJsYL+Ew6i1kxoFJKwAOmRJjVty/\nwCV/MKndXEf9LdOsXbDMLYWts1Qd13DqPam36OkxqW599WmNWDcix6bKd+5RGdkGEal9/LJpvDH4\nmJLJyerC2CuFQzcix6aSCj4tvteNhNJDvjbI/nOhdEXQOemacbgGLhSeUWjlAhpyRXJY7epTConO\n0ZWAJ/WYcfUlvDcmR8FZEOpuIsRIKXHYPya/2a9QPM3cUP5OgH+lSJKdA/dqngAAAABJRU5ErkJg\ngg==\n", + "text/latex": [ + "$$y{\\left (t \\right )} = \\left(C_{1} + t\\right) e^{- t}$$" + ], + "text/plain": [ + " -t\n", + "y(t) = (C₁ + t)⋅ℯ " + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sympy.dsolve(ode, y(t))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is simple enough to solve, but we'll use symbolic methods to find the constant, by setting $t = 0$ and $y(t) = y(0) = 1$." + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAADsAAAARBAMAAACRPMnQAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAVO8Qq5l2zWaJ3bsi\nRDIczTGXAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAsklEQVQoFWNgwAaYs108eCaAZRiVMRUkNTAw\nBjWAxE1CPmNIWy8GCsUfAIuzYUrXGwBlLoFlGTClWT+CZJ7ikj6/ACRjgyI9vRwESkFi8xMgMnwF\nQBrT8PUPwNJ8IQuwSuuDXMZgwMCIXXo9SJbxAYr0rFUgsAQkA/YxK1DFAiAH0+7zoOCcjFOa8QcD\ngyjQfpBuVqfvHkDFKMB0i+sFoADYcBQJFA4haQUU1WgcnqgvCQDOGDHf2N3daQAAAABJRU5ErkJg\ngg==\n", + "text/latex": [ + "$$1 = C_{1}$$" + ], + "text/plain": [ + "1 = C₁" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "general_solution = sympy.dsolve(ode, y(t))\n", + "value = general_solution.subs([(t,0), (y(0), 1)])\n", + "value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We then find the specific solution of the ODE." + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAJoAAAAYBAMAAADwqfn3AAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEHaZIu+JVM27RDKr\nZt2dj8xZAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACZUlEQVQ4Ea1UPWsUURQ9M7M7szvJLoOoWAQd\nksZGXFQkYsABiZIisjYWVktsUkmwE0EXFFzUwsImkOD+AHH3H7gEU1gIg1rYCFvEj0JkFRG/Cu99\nc+fte8laZS+8ueee++a8z/uA8VmpOz4t4FA0TrWb4xQ7++m0lltkVEl0rEEh1dACb6yIg7uaKTxU\n8LkmNFjQyAaTiR0D3zVRotzBBAc0ocEdwNnSUQaCi0Q2NXl9lSwK65p4TegW4MeaEVCpAcFAgmuZ\nn5r7SmBJyNy5vb055NFnacChvmSqCeA1JRA1uKy2T8jceXFDYKFP4AO1e0Jod4FQtSGhpVZqCysu\n3OjCmYkxH7k1hC9+bQDH7R7ADPDk8Vqc0ZaaR3sA7J8+keXU1w/qOIpyKrvzVpHLLbbbjNep0YZm\nZqlVmkSGWzgnSXbnaVNWUV2R3dlxnz9SH9rQzCy1oE/k/IozvLNAVIzxDcW27M4z6mHZZYp4QwGa\n8PtW6wFDdQoTA0Kbr45EzOTWiSb+oNimoqWGUWrOb0oos+am1P7mKfGzcOtqpR04wFPFXv3C9pkx\nrTQcQMa31MI+pX9wH8PWUO6pU1jGDSA7BSNNp+A3g27GWGrqFC7Rso3eOIVOCr8GzDkxcNJMMb5C\nx9PbI6yl5jWIPQzHvCGYWjqTgGe98I6y96lZRksvrKdCiZq3+fMloJ5a9xj/ZRpfAKlrVRNmDlxZ\n2vK5KYKrZLtNNtWRcdWT+bFyxoerXpsua2a2Vz1z1bQckysn9MGoF+mRSuz8GC/SMBlOq7ssr+WI\nX//3Wsr4QyUTLXKwu5cc+Af49YD1LJzQSgAAAABJRU5ErkJggg==\n", + "text/latex": [ + "$$y{\\left (t \\right )} = \\left(t + 1\\right) e^{- t}$$" + ], + "text/plain": [ + " -t\n", + "y(t) = (t + 1)⋅ℯ " + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ode_solution = general_solution.subs([(value.rhs,value.lhs)])\n", + "ode_solution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Plotting" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`sympy` provides an interface to `matplotlib` so that expressions can be directly plotted. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "collapsed": true, + "nbconvert": { + "hide_code": true + } + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "from matplotlib import rcParams\n", + "rcParams['figure.figsize']=(12,9)" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAArwAAAISCAYAAAAurBzdAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xl0Xld57/Hf0eRBnmPZsi1bkuU5djxkMBmaGyhJTchA\n2t6uAAUKpYQh7WWxOtDe3gW09FJoe1eH0N6UUtqGXlKg0ACZQ+IkhBDjOLbj2bJsy/IgeZIdeZJl\nnfvHzhtPr6R3OOfsffb5ftbScmxL7/tE1jn7Oc9+9t5BGIYCAAAAfFVhOwAAAAAgTiS8AAAA8BoJ\nLwAAALxGwgsAAACvkfACAADAayS8AAAA8BoJLwAAALxGwgsAAACvVdkOAADiEATBJEk3Spoq6ZSk\nDZJWh2HYbzUwAEDiAk5aA+CTIAjeLumzkiZIek1Sl6ThkuZIapH0XUl/FYbhcWtBAgASRcILwCtB\nEPyFpL8Lw7A9z99VSbpDUmUYhv9Zxnt8/c3X6QzD8KoBPudvJb1L0glJvxGG4dpS3w8AUB4SXgAo\nUhAEN0nqkfRv+RLeIAjeJen+MAzfHQTBckl/E4bh25KOEwBgsGgNgJeCIHgoCIKxF/y+KQiCH0fx\n2mEY/kTS0UE+5W5J//bm574iaWwQBJOjeG8AQPFIeAH46ieSXgmC4PYgCH5L0lOS/jqh954mac8F\nv9/75p8BACxglwYAXgrD8MEgCDZKek7SIUlLwzA8YDksAIAFUSa8NAMjNXp7pU9/Wnrl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/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "sympy.plot(sympy.sin(x));" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can explicitly set limits, for example" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAt0AAAIqCAYAAAD4oPZTAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xuc12P+//HHVVg5s1jfcj4t68zKITItVsjmlC3nMz+b\n82KX3ZXFWmdZS0KWdikkhaSDooOoLedyakWJRNhETc31++OaGHaqaZr3vD+Hx/12m1vzmc/nPT1n\nb7PT0zWv93WFGCOSJEmSstMk7wCSJElSqbN0S5IkSRmzdEuSJEkZs3RLkiRJGbN0S5IkSRmzdEuS\nJEkZs3RLkiRJGbN0S5IkSRlbri4vCiGsC7QCmgNfA68B42KMVRlmkyRJkkpCWNyJlCGENsDvgLWA\nCcAMYEVgS2Az4BHgxhjjl9lHlSRJkorTkkr39cDfYozv1/LcckA7oGmMsc9iPkdb4BbSKMs9McZr\nf/D8r4ArgSqgEjg/xjiq+rn3gC8WPhdjbLlUX50kSZJUABZbupf5k4fQBHgL2Bf4EBgLdIwxTqrx\nmpVijHOq398OeCjGuHX148nALjHGWZmFlCRJkjJWpxspQwg9Qwir13i8cQhhaB0ubQm8HWOcEmOs\nBHoB7Wu+YGHhrrYKaVX727+qrhklSZKkQlXXQjsSeCGEcFAI4TRgEGlkZElaAB/UeDy1+mPfE0I4\nNIQwEXgcOLnGUxEYHEIYW/33SpIkSUWnTruXxBjvDCG8DgwDZgI7xRg/aqgQMcbHgMdCCHsBVwH7\nVz/VKsY4PYSwDql8T4wxjmyov1eSJElqDHXdMvA44I/A8cD2wIAQwkkxxpeXcOk0YMMaj9ev/lit\nYowjQwibhhDWijF+FmOcXv3xT0IIfUnjKv9Tuk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0l+BPYDnyT5AzgFLPCOmdPNcSRJkqTGZmV5iSRJ\nkjSzDN2SJElSY4ZuSZIkqTFDtyRJktSYoVuSJElqzNAtSZIkNWboliRJkhozdEuSJEmNGbolSZKk\nJSTZneR2koUk65LcTbJjqnu4I6UkSZK0tCTfAWvHx6OqOjPV9YZuSZIkaWlJ1gC/AM+BvTVliHZ5\niSRJkjTZRuBjYD3w4bQXO9MtSZIkTZDkEvATsBX4tKpOTHP96iZVSZIkSXMiyVHgZVVdTPIBcCPJ\n/qq61vkeznRLkiRJbbmmW5IkSWrM0C1JkiQ1ZuiWJEmSGjN0S5IkSY0ZuiVJkqTGDN2SJElSY4Zu\nSZIkqTFDtyRJktTYa+S1zSu6SqMfAAAAAElFTkSuQmCC\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "sympy.plot(sympy.exp(-x)*sympy.sin(x**2), (x, 0, 1));" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can plot the solution to the differential equation computed above:" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAt0AAAIRCAYAAACWHQE9AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XeUVeXZ9/HvTRNpgqBEQBAFKSolNFGiY0EQW8QS1Kig\nEWM0ap4krzEaxViiMfrE2I29IBobRMVggSiEpiKggqAgImCvsTwI3O8fe5ARBxiG2bNP+X7WYs2c\nc/Y+59rLs/TnxbXvO8QYkSRJkpSeGlkXIEmSJBU6Q7ckSZKUMkO3JEmSlDJDtyRJkpQyQ7ckSZKU\nMkO3JEmSlDJDtyRJkpQyQ7ckSZKUsloVOSiEsDWwO9AC+Ap4GXg+xrgqxdokSZKkghDWtyNlCGEv\n4HfAlsAM4D2gLrAjsAPwAHBFjPGz9EuVJEmS8tOGQvflwNU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ilpd7p7A/NjjItijN8Ao4BD\n1nP8UcC9lTxXkiRJyklph+6WwOIyj98ufe57QgibAwOBBzf2XEmSJCmX5dKNlAcBE2OMn2RdiCRJ\nklSVaqX8/kuA1mUetyp9rjxDWDNasrHnEkK4oMzDCTHG/9++HZsoFAVRAL2PLcAGLGrTrcDEigQL\n0cjYBsTE1BKMZAy+JgYLPxgQOSd9MzDhZXhzmDUpAAA06T6k/ElyznQMeU1yTPJXVae3ukWSS5Jl\nVd3m9AIAwKdr3XRX1X2MsU6yz/SVZVtVpzHGanquzbP0N8nuFbj/6+2cFwAAOrRuugEAgM86pAQA\ngK8kdAMAQDOhGwAAmgndAADQTOgGAIBmQjcAADQTugEAoJnQDQAAzR7/Cpcx8mldmwAAAABJRU5E\nrkJggg==\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "sympy.plot(ode_solution.rhs, xlim=(0, 1), ylim=(0.7, 1.05));" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This can be *visually* compared to the previous result. However, we would often like a more precise comparison, which requires numerically evaluating the solution to the ODE at specific points." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## lambdify" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "At the end of a symbolic calculation using `sympy` we will have a result that is often long and complex, and that is needed in another part of another code. We could type the appropriate expression in by hand, but this is tedious and error prone. A better way is to make the computer do it.\n", + "\n", + "The example we use here is the solution to the ODE above. We have solved it symbolically, and the result is straightforward. We can also solve it numerically using `scipy`. We want to compare the two.\n", + "\n", + "First, let us compute the `scipy` numerical result:" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from numpy import exp\n", + "from scipy.integrate import odeint\n", + "import numpy\n", + "\n", + "def dydt(y, t):\n", + " \"\"\"\n", + " Defining the ODE dy/dt = e^{-t} - y.\n", + " \n", + " Parameters\n", + " ----------\n", + " \n", + " y : real\n", + " The value of y at time t (the current numerical approximation)\n", + " t : real\n", + " The current time t\n", + " \n", + " Returns\n", + " -------\n", + " \n", + " dydt : real\n", + " The RHS function defining the ODE.\n", + " \"\"\"\n", + " \n", + " return exp(-t) - y\n", + "\n", + "t_scipy = numpy.linspace(0.0, 1.0)\n", + "y0 = [1.0]\n", + "\n", + "y_scipy = odeint(dydt, y0, t_scipy)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We want to evaluate our `sympy` solution at the same points as our `scipy` solution, in order to do a direct comparison. In order to do that, we want to construct a function that computes our `sympy` solution, without typing it in. That is what `lambdify` is for: it creates a function from a sympy expression.\n", + "\n", + "First let us get the expression explicitly:" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAFoAAAAYBAMAAACIFvdWAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIma7zZnddlTvRIkQ\nqzLsm4+cAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABeUlEQVQ4EWNgIB6wPCBeLQPD+QOkqG4jRbFo\nShwDA6MCdi2KGMIeQBFhDFGIAK8AusRHoIAjAwNPIpoExxygoANcsNkYCA5wTWBgYApgYOD4AJHg\nKIDQZ2P/ABnb4aohDPYLBxnYBBgYWB0gfJhqBnaQ6pMQQTjJWrCBQQzIY9sAEUJVzbIArhDM4Lr+\ngKGUgWGtvS3ECaiqWQNAik6XByJpMgKy+6F8VNVMDkBhrkQGaagsiMoA4hAoH1U1RwJQWLKBBxgn\ncDALyMoG8bhdXNymuLhcALHBvuT7AGTdVC86ABKBAqBqnl9QNqrZYNV/YeogNNAlXB8YDoA5qKq5\nEoCCv8EScALoS24HjgdgPqpqJgeg4Gygs8ByEGIrMHIuHIewUVWzbgCKljDwIIfgMmAqNFJAVc16\n88slBgZwVmEPV4LIQUhQzMMA3GywACiW0QEoVcEAD5JOzFQFVmUIU4tGI6VYJBlcuYEZxSKYBkYF\nGAuVxsxpDAwAkL5H0/W7iQ4AAAAASUVORK5CYII=\n", + "text/latex": [ + "$$\\left(t + 1\\right) e^{- t}$$" + ], + "text/plain": [ + " -t\n", + "(t + 1)⋅ℯ " + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ode_expression = ode_solution.rhs\n", + "ode_expression" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Then we construct the function using `lambdify`:" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from sympy.utilities.lambdify import lambdify\n", + "\n", + "ode_function = lambdify((t,), ode_expression, modules='numpy')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The first argument to `lambdify` is a tuple containing the arguments of the function to be created. In this case that's just `t`, the time(s) at which we want to evaluate the expression. The second argument to `lambdify` is the expression that we want converted into a function. The third argument, which is optional, tells `lambdify` that where possible it should use `numpy` functions. This means that we call the function using `numpy` arrays, it will calculate using `numpy` array expressions, doing the whole calculation in a single call.\n", + "\n", + "We now have a function that we can directly call:" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "sympy solution at t=0: 1.0\n", + "sympy solution at t=0.5: 0.9097959895689501\n" + ] + } + ], + "source": [ + "print(\"sympy solution at t=0: {}\".format(ode_function(0.0)))\n", + "print(\"sympy solution at t=0.5: {}\".format(ode_function(0.5)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And we can directly apply this function to the times at which the `scipy` solution is constructed, for comparison:" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "y_sympy = ode_function(t_scipy)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we can use `matplotlib` to plot both on the same figure:" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAt4AAAInCAYAAACvCV6OAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XmclvP+x/HXd6Z937RvKktRIqXtMCkRUWlVKp0jhKOy\nHBzHMc4vS86xZJedUMmeKFKUSklpUUrUpJJIyNYy1++P6fSLX9IyM9d9z7yej8c8HnPf93Xd93s8\nwrvvfK7vFaIoQpIkSVLOSok7gCRJkpQfWLwlSZKkXGDxliRJknKBxVuSJEnKBRZvSZIkKRdYvCVJ\nkqRckOPFO4TwcAhhfQhhwR6OuTOEsDyEMD+E0HiX508JISwNISwLIVyZ01klSZKknJIbK96PAif/\n3oshhA5A3SiKDgHOB+7f8XwKcPeOc48AzgohHJ7zcSVJkqTsl+PFO4qi6cA3ezikE/DEjmPfA0qH\nECoBzYDlURStiqJoKzB6x7GSJElS0kmEGe9qwOpdHn++47nfe16SJElKOolQvH8rxB1AkiRJym4F\n4g4ArAFq7PK4+o7nCgE1d/P8boUQohxJJ0mSJO0iiqL9WijOreId+P2V7JeBi4AxIYTmwKYoitaH\nEL4C6oUQagHrgF7AWXv6kCjKvu4dRfDdd/D11/DRR6v58MPFrF27kS+++Io1a9aybt0qChY8mZ9+\nOoevvoKqVaFWrayvEKYBy2jQoBZHH12Lpk1rUKZMkWzLpr2Tnp5Oenp63DGUYPxzod3xz4V2xz8X\n2p0Q9n84I8eLdwjhaSANKB9CyACuI2s1O4qiaGQURRNCCKeGED4BfgAGkPXi9hDCxcAkskZiHo6i\naElO5/2/3FC6dNZXnTo16Nixxu8eu2ULrF4Nq1Zlfb3xxrfMnj2Nl156is2bV7Ft2+ekpJTn8MNv\npU2bszjiCGjQAI44AipUyK2fSJIkSXHK8eIdR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RdvABsy8xPgk4h4HDgCsHj3X7WMi5nAlQCZuSoiVgMjgKeKJFQj6lHn7EtTTZYA\nB0fEARExCDgb+PIX5H3An8EXu16+m5ntZWOqsC2Oi4jYH5gHnJuZqyrIqPK2OC4y88DOf39Axzzv\nCy3d/V4t3yPzgZaI2C4idgb+GHD/iP6tlnGxBjgJoHMe7yF03Liv/i34+r+G9qhz9pkr3rVsxJOZ\nCyPitIhYCXxIx/+hqh+rcYOmvwOGAf/aeXXzs8wcVV1q1dtWbNz1xSnFQ6q4Gr9HXoqIB4DngE3A\nDZn5QoWxVWc1/r64Ari1y9Jyl2Tmxooiq4CIuBMYB3wjIl4DLgMGsY2d0w10JEmSpAL60lQTSZIk\nqc+yeEuSJEkFWLwlSZKkAizekiRJUgEWb0mSJKkAi7ckSZJUgMVbkiRJKsDiLUmSJBVg8ZakJhUR\nIyLi0qpzSFKzsHhLUvM6EVhadQhJahYWb0lqQhHRCpwHfCsi9q46jyQ1g8jMqjNIkioQEfdl5qSq\nc0hSs/CKtyQ1oc6r3OurziFJzcTiLUnNaRTwZEQcGxE7VR1GkpqBxVuSmtObwH7AkMz8uOowktQM\nnOMtSZIkFeAVb0mSJKkAi7ckSZJUgMVbkiRJKsDiLUmSJBVg8ZYkSZIKsHhLkiRJBVi8JUmSpAIs\n3pIkSVIB/wu1ZHHOUURaMAAAAABJRU5ErkJggg==\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "from matplotlib import pyplot\n", + "pyplot.plot(t_scipy, y_scipy[:,0], 'b-', label='scipy')\n", + "pyplot.plot(t_scipy, y_sympy, 'k--', label='sympy')\n", + "pyplot.xlabel(r'$t$')\n", + "pyplot.ylabel(r'$y$')\n", + "pyplot.legend(loc='upper right')\n", + "pyplot.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We see good visual agreement everywhere. But how accurate is it?\n", + "\n", + "Now that we have `numpy` arrays explicitly containing the solutions, we can manipulate these to see the differences between solutions:" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAtwAAAIpCAYAAACR9u/DAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XecVNX9//H3oSoWQEUs2AFRFBsgtoglYq8xscSCFRON\nhdiSGMdf1NhiwxJjbCEaW+y9Zewl0RgVCwoKuBCwIYqUZff8/vjsfFkJLDOzc+659+7r+XjMY2HL\nvZ/VZfe9n/mcc5z3XgAAAADCaBe7AAAAACDPCNwAAABAQARuAAAAICACNwAAABAQgRsAAAAIiMAN\nAAAABETgBgAAAAIicAMAAAABdYhdwKI457aWdLCsxvW891tHLgkAAAComEv7SZPOub0krei9vz52\nLQAAAEClgo+UOOducM5Ndc69tcDrd3bOve+cG+ucO72FSxwk6bawVQIAAABhJDHDfZOkYc1f4Zxr\nJ+mqptf3l3Sgc65f09sOcc5d6pxb2Tm3mqTp3vuZCdQJAAAA1FzwwO29f0HSVwu8erCkD733E7z3\n9ZJul7RX0/uP9t6f4r2fIulIWWAHAAAAMinWoslVJU1q9vdPZSH8e7z3hcVdyDmX7iF0AAAA5Ib3\n3lX6MandpaQSaV/4ieQVCgUVCoXYZSBl+LrAwvB1gYXh6wIL41zFWVtSvH246ySt3uzvvZpeBwAA\nAORKUoHbNT1K/impt3NuDedcJ0kHSHogoVoAAACAxCSxLeBtkl6S1Nc5N9E5N9x73yDpBElPSBoj\n6Xbv/Xuha0HbMXTo0NglIIX4usDC8HWBheHrArWU+oNvFsc557P+OQAAACD9nHNVLZqMNcMNAAAA\ntAkEbgAAACAgAjcAAAAQEIEbAAAACIjADQAAAASUi8BdKBRULBZjlwEAAIAcKhaLrTp5lG0BAQAA\ngDKwLSAAAACQQgRuAAAAICACNwAAABAQgRsAAAAIiMANAAAABETgBgAAAAIicAMAAAABEbgBAACA\ngAjcAAAAQEAEb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ftJ1OgJJqO9wEbgAAkDqPP247kLz+urTMMsnee9486YADLHzf\neafUoUOy90d6temRkkKhoGKxGLsMAABQAw0N0mmnSRdckHzYlixg33qr9N130hFHWPBG21YsFlUo\nFKr+eDrcAAAgVW6+Wbr+eumFFyRXcS+xdr77Tho2zGbIR42KWwvSgZESAACQebNm2WmQd9whbbll\n7Gqkr7+Wtt/ethA899zY1SC2agM3U0kAACA1Lr/cjmtPQ9iWpK5dpcces91LunaVTj01dkXIIgI3\nAABIhc8+syPbX345diXf16OH9NRT0jbbSMsua3uCA5UgcAMAgFT43e+kAw+U+vSJXcn/WnVV6ckn\npW23tdB94IGxK0KWELgBAEB0H34o3Xab9N57sStZtHXWse0Kd9hBWnppaY89YleErMjFtoAAACDb\nfvUr6ZRTbHwjzfr3twNxjjxSeuaZ2NUgK9ilBAAARPXyy9KPfyx98IHUpUvsasrz7LPS/vtb+N58\n89jVIClsCwgAADLHe1uMeNRR0uGHx66mMo88Ig0fLv3739Iqq8SuBklo0ydNAgCAbLrvPmnGDOmQ\nQ2JXUrldd5UOPli68MLYlSDt6HADAIAo6uttJnrUKDvRMYv++19p/fWlMWOklVeOXQ1Co8MNAAAy\n5frrpTXWkHbaKXYl1VtpJemww+hyo2V0uAEAQOJmzLAj3B99VNpkk9jVtM6UKdapp8udf3S4AQBA\nZlx8sXW2sx62JQvZhxxinxOwMHS4AQBAourqpAEDbHeP1VePXU1tTJ4sbbCBHdzTs2fsahAK2wIC\nAIBMOOooaYUVpAsuiF1Jbf3iF1KnTtIll8SuBKEQuAEAQOq9844djf7BB1K3brGrqa26OmnDDely\n5xkz3AAAIPVOO82Occ9b2JakVVeVDjqIDjf+Fx1uAACQiKeflo45xjrAnTrFriaMTz+1+fT335dW\nXDF2Nag1OtwAACC1GhulU0+Vfv/7/IZtSerVSzrwQOkPf4hdCdKEDjcAAAju1lulK6+UXnlFchX3\nB7Nl0iRp442ty92jR+xqUEssmgQAAKk0e7bUr580erS0zTaxq0nGccdJXbvmbye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UKhao/vqWRkgZJ\nMxf2JklLeO9T0eVmpAQAAABJqPk+3N779q0rCQAAAECL2wICAAAAaB0CNwAAABAQgRsAAAAIiMAN\nAAAABETgBgAAAAIicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACAgAjcAAAAQEIEbAAAACIjADQAA\nAARE4AYAAAACInADAAAAARG4AQAAgIAI3AAAAEBABG4AAAAgoFwE7kKhoGKxGLsMAAAA5FCxWFSh\nUKj64533vnbVROCc81n/HAAAAJB+zjl5712lH5eLDjcAAACQVgRuAAAAICACNwAAABAQgRsAAAAI\niMANAAAABETgBgAAAAIicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACAgAjcAAAAQEIEbAAAACIjA\nDQAAAARE4AYAAAACInADAAAAARG4AQAAgIAI3AAAAEBABG4AAAAgIAI3AAAAEBCBGwAAAAiIwA0A\nADgn9P4AAAo9SURBVAAEROAGAAAAAiJwAwAAAAHlInAXCgUVi8XYZQAAACCHisWiCoVC1R/vvPe1\nqyYC55zP+ucAAACA9HPOyXvvKv24XHS4AQAAgLQicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACAg\nAjcAAAAQEIEbAAAACIjADQAAAARE4AYAAAACInADAAAAARG4AQAAgIAI3AAAAEBABG4AAAAgIAI3\nAAAAEBCBGwAAAAiIwA0AAAAEROAGAAAAAiJwAwAAAAERuAEAAICACNwAAABAQARuAAAAICACNwAA\nABAQgRsAAAAIiMANAAAABETgBgAAAAIicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACCgXATuQqGg\nYrEYuwwAAADkULFYVKFQqPrjnfe+dtVE4JzzWf8cAAAAkH7OOXnvXaUfl4sONwAAAJBWBG4AAAAg\nIAI3AAAAEBCBGwAAAAiIwA0AAAAEROAGAAAAAiJwAwAAAAERuAEAAICACNwAAABAQARuAAAAICAC\nNwAAABAQgRsAAAAIiMANAAAABETgBgAAAAIicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACAgAjcA\nAAAQEIEbAAAACIjADQAAAARE4AYAAAACInADAAAAARG4AQAAgIAI3AAAAEBABG4AAAAgIAI3AAAA\nEBCBGwAAAAiIwA0AAAAEROAGAAAAAiJwAwAAAAERuAEAAICACNwAAABAQARuAAAAICACNwAAABAQ\ngRsAAAAIiMANAAAABETgBgAAAAIicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACCgXATuQqGgYrEY\nuwwAAADkULFYVKFQqPrjnfe+dtVE4JzzWf8cAAAAkH7OOXnvXaUfl4sONwAAAJBWBG4AAAAgIAI3\nAAAAEBCBGwAAAAiIwA0AAAAEROAGAAAAAiJwAwAAAAERuAEAAICACNwAAABAQARuAAAAICACNwAA\nABAQgRsAAAAIiMANAAAABETgBgAAAAIicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACAgAjcAAAAQ\nEIEbAAAACIjADQAAAARE4AYAAAACInADAAAAARG4AQAAgIAI3AAAAEBABG4AAAAgIAI3AAAAEBCB\nGwAAAAiIwA0AAAAEROAGAAAAAiJwAwAAAAERuAEAAICACNwAAABAQARuAAAAICACNwAAABAQgRsA\nAAAIiMANAAAABETgBgAAAAIicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACAgAjcAAAAQEIEbAAAA\nCIjADQAAAARE4AYAAAACInADAAAAARG4AQAAgIAI3AAAAEBABG4AAAAgIAI3AAAAEBCBGwAAAAiI\nwA0AAAAEROAGAAAAAiJwAwAAAAERuAEAAICACNwAAABAQARuAAAAICACNwAAABAQgRsAAAAIiMAN\nAAAABETgBgAAAAIicAMAAAABEbgBAACAgAjcAAAAQEAEbgAAACAgAjcAAAAQEIEbAAAACIjADQAA\nAASU2sDtnFvPOXeHc+5q59x+sesBAAAAqpHawC1pF0lXeu9/LunQ2MUgW4rFYuwSkEJ8XWBh+LrA\nwvB1gVoKHridczc456Y6595a4PU7O+fed86Ndc6dvpAPHS3pAOfcRZKWC10n8oVvlFgYvi6wMHxd\nYGH4ukAtJdHhvknSsOavcM61k3RV0+v7SzrQOdev6W2HOOculdTBe3+CpD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62XQeu5J7kIOAhc2/ZkbxFp9Q2Z\niUuBe5MEeC9wXZKjbV2adH0NmYuXgFfavg68nuSnwMWAhXt9DZmLA8A3Ado+l+T3wAXALydJqFPV\njjvnqlxSMmTd7kPAjQBJrgBebfvHaWNqYtvORZI9wP3ADW2fmyGjprXtTLR9/+JxLlvXcX/Bsr32\nhhxDfghcmeTtSd4FfBRwudr1NmQungeuAVhco7uXrQ/ja/2deA+ZZTvunCtxhrvtsSRfYmvd7rcB\n3237dJKbt77dg21/lOQTSZ4F/sHWf6VaY0PmAvg6cAZw5+KM5tG2l8+XWmMaOBNv+pHJQ2pyA48h\nv03yIPBr4BhwsO1vZoytkQ3cX9wCfH9pebivtv3LTJE1kcU9ZK4CzkzyAvAN4DT+h86Z1uONJEmS\nNJZVuaREkiRJWkkWbkmSJGlEFm5JkiRpRBZuSZIkaUQWbkmSJGlEFm5JkiRpRBZuSZIkaUQWbkmS\nJGlEFm5J2jBJLkjytblzSNKmsHBL0ubZBxyeO4QkbQoLtyRtkCTXAjcB5yQ5a+48krQJ0nbuDJKk\nCSU51PZTc+eQpE3hGW5J2iCLs9p/mDuHJG0SC7ckbZbLgV8kuTTJO+cOI0mbwMItSZvlZWA3sKvt\na3OHkaRN4DXckiRJ0og8wy1JkiSNyMItSZIkjcjCLUmSJI3Iwi1JkiSNyMItSZIkjcjCLUmSJI3I\nwi1JkiSN6J+2JGttmR834gAAAABJRU5ErkJggg==\n", + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "pyplot.semilogy(t_scipy, numpy.abs(y_scipy[:,0]-y_sympy))\n", + "pyplot.xlabel(r'$t$')\n", + "pyplot.ylabel('Difference in solutions');" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The accuracy is around $10^{-8}$ everywhere - by modifying the accuracy of the `scipy` solver this can be made more accurate (if needed) or less (if the calculation takes too long and high accuracy is not required)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Further reading" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`sympy` has [detailed documentation](http://docs.sympy.org/latest/index.html) and a [useful tutorial](http://docs.sympy.org/dev/tutorial/index.html)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Exercise : systematic ODE solving" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We are interested in the solution of\n", + "\n", + "$$ \\frac{\\text{d} y}{\\text{d} t} = e^{-t} - y^n, \\qquad y(0) = 1, $$\n", + "\n", + "where $n > 1$ is an integer. The \"minor\" change from the above examples mean that `sympy` can only give the solution as a power series." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 1\n", + "\n", + "Compute the general solution as a power series for $n = 2$." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 2\n", + "\n", + "Investigate the help for the `dsolve` function to straightforwardly impose the initial condition $y(0) = 1$ using the `ics` argument. Using this, compute the specific solutions that satisfy the ODE for $n = 2, \\dots, 10$." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 3\n", + "\n", + "Using the `removeO` command, plot each of these solutions for $t \\in [0, 1]$." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python [default]", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.5.2" + }, + "nbconvert": { + "title": "Symbolic Python" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/jupyter/math/Handcalcs_julia_cf3b0c.ipynb b/jupyter/math/Handcalcs_julia_cf3b0c.ipynb new file mode 100644 index 0000000..6efc5af --- /dev/null +++ b/jupyter/math/Handcalcs_julia_cf3b0c.ipynb @@ -0,0 +1,159 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "using Handcalcs, Unitful, UnitfulLatexify, TestHandcalcFunctions\n", + "using Format" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "set_default(fmt = x->format(round(x, digits=4)))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "a = 2\n", + "b = 5\n", + "c = 2;" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\begin{align}\n", + "x_{1} &= \\frac{ - b + \\sqrt{b^{2} - 4 \\cdot a \\cdot c}}{2 \\cdot a} = \\frac{ - 5 + \\sqrt{5^{2} - 4 \\cdot 2 \\cdot 2}}{2 \\cdot 2} = -0.5\n", + "\\end{align}$" + ], + "text/plain": [ + "L\"$\\begin{align}\n", + "x_{1} &= \\frac{ - b + \\sqrt{b^{2} - 4 \\cdot a \\cdot c}}{2 \\cdot a} = \\frac{ - 5 + \\sqrt{5^{2} - 4 \\cdot 2 \\cdot 2}}{2 \\cdot 2} = -0.5\n", + "\\end{align}$\"" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "@handcalcs x_1 = (-b + sqrt(b^2 - 4*a*c))/(2*a)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\begin{align}\n", + "x_{1} &= \\frac{ - b + \\sqrt{b^{2} - 4 \\cdot a \\cdot c}}{2 \\cdot a} = \\frac{ - 5 + \\sqrt{5^{2} - 4 \\cdot 2 \\cdot 2}}{2 \\cdot 2} = -0.5\n", + "\\\\x_{2} &= \\frac{ - b - \\sqrt{b^{2} - 4 \\cdot a \\cdot c}}{2 \\cdot a} = \\frac{ - 5 - \\sqrt{5^{2} - 4 \\cdot 2 \\cdot 2}}{2 \\cdot 2} = -2\n", + "\\end{align}$" + ], + "text/plain": [ + "L\"$\\begin{align}\n", + "x_{1} &= \\frac{ - b + \\sqrt{b^{2} - 4 \\cdot a \\cdot c}}{2 \\cdot a} = \\frac{ - 5 + \\sqrt{5^{2} - 4 \\cdot 2 \\cdot 2}}{2 \\cdot 2} = -0.5\n", + "\\\\x_{2} &= \\frac{ - b - \\sqrt{b^{2} - 4 \\cdot a \\cdot c}}{2 \\cdot a} = \\frac{ - 5 - \\sqrt{5^{2} - 4 \\cdot 2 \\cdot 2}}{2 \\cdot 2} = -2\n", + "\\end{align}$\"" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "@handcalcs begin \n", + " x_1 = (-b + sqrt(b^2 - 4*a*c))/(2*a)\n", + " x_2 = (-b - sqrt(b^2 - 4*a*c))/(2*a)\n", + "end" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "15" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "b = 5\n", + "h = 15" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\begin{align}\n", + "Ix &= \\frac{b \\cdot h^{3}}{12} = \\frac{5 \\cdot 15^{3}}{12} = 1406.25\n", + "\\end{align}$" + ], + "text/plain": [ + "L\"$\\begin{align}\n", + "Ix &= \\frac{b \\cdot h^{3}}{12} = \\frac{5 \\cdot 15^{3}}{12} = 1406.25\n", + "\\end{align}$\"" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "@handfunc I_x = calc_Ix(5, 15)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Julia 1.10.0", + "language": "julia", + "name": "julia-1.10" + }, + "language_info": { + "file_extension": ".jl", + "mimetype": "application/julia", + "name": "julia", + "version": "1.10.0" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/jupyter/math/StatesOperators_4e6d54.ipynb b/jupyter/math/StatesOperators_4e6d54.ipynb new file mode 100644 index 0000000..1a21ca3 --- /dev/null +++ b/jupyter/math/StatesOperators_4e6d54.ipynb @@ -0,0 +1,2420 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#Manipulating States & Operators\n", + "\n", + "###Contents\n", + "- [Introduction](#intro)\n", + "- [State Vectors](#state)\n", + "- [Density Matrices](#density)\n", + "- [Qubit (Two-level) Systems](#qubit)\n", + "- [Expectation Values](#expect)\n", + "- [Super Operators & Vectorized Operators](#super)" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "from qutip import *" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "##Introduction\n", + "\n", + "In the previous guide section [Basic Operations on Quantum Objects](BasicOperations.ipynb), we saw how to create states and operators, using the functions built into QuTiP. In this portion of the guide, we will look at performing basic operations with states and operators. For more detailed demonstrations on how to use and manipulate these objects, see the examples on the [tutorials](http://qutip.org/tutorials.html) web page." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##State Vectors\n", + "\n", + "Here we begin by creating a Fock ground state vector $\\left|0\\right>$ with in a Hilbert space with 5 number states, from 0 to 4 using the `basis` function:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}1.0\\\\0.0\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 1.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "vac = basis(5, 0)\n", + "vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and then create a lowering operator $\\left(\\hat{a}\\right)$ corresponding to 5 number states using the `destroy` function:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = False\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 1.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 1.414 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 1.732 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 2.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = False\n", + "Qobj data =\n", + "[[ 0. 1. 0. 0. 0. ]\n", + " [ 0. 0. 1.41421356 0. 0. ]\n", + " [ 0. 0. 0. 1.73205081 0. ]\n", + " [ 0. 0. 0. 0. 2. ]\n", + " [ 0. 0. 0. 0. 0. ]]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = destroy(5)\n", + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now lets apply the destruction operator to our vacuum state ``vac``," + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " a * vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We see that, as expected, the vacuum is transformed to the zero vector. A more interesting example comes from using the adjoint of the lowering operator, the raising operator $\\hat{a}^\\dagger$:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\1.0\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 1.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " a.dag() * vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The raising operator has in indeed raised the state `vec` from the vacuum to the $\\left| 1\\right>$ state. Instead of using the dagger ``Qobj.dag()`` method to raise the state, we could have also used the built in `create` function to make a raising operator:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\1.0\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 1.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c = create(5)\n", + "c * vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which does the same thing. We can raise the vacuum state more than once by successively apply the raising operator:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\1.414\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0. ]\n", + " [ 0. ]\n", + " [ 1.41421356]\n", + " [ 0. ]\n", + " [ 0. ]]" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c * c * vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or just taking the square of the raising operator $\\left(\\hat{a}^\\dagger\\right)^{2}$:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\1.414\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0. ]\n", + " [ 0. ]\n", + " [ 1.41421356]\n", + " [ 0. ]\n", + " [ 0. ]]" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " c ** 2 * vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Applying the raising operator twice gives the expected $\\sqrt{n + 1}$ dependence. We can use the product of $c * a$ to also apply the number operator to the state vector ``vac``:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c * a * vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or on the $\\left| 1\\right>$ state:" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\1.0\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 1.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c * a * (c * vac)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or the $\\left| 2\\right>$ state:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\2.828\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0. ]\n", + " [ 0. ]\n", + " [ 2.82842712]\n", + " [ 0. ]\n", + " [ 0. ]]" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c * a * (c**2 * vac)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how in this last example, application of the number operator does not give the expected value $n=2$, but rather $2\\sqrt{2}$. This is because this last state is not normalized to unity as $c\\left| n\\right> = \\sqrt{n+1}\\left| n+1\\right>$. Therefore, we should normalize our vector first:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\2.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 0.]\n", + " [ 2.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c * a * (c**2 * vac).unit()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since we are giving a demonstration of using states and operators, we have done a lot more work than we should have. For example, we do not need to operate on the vacuum state to generate a higher number Fock state. Instead we can use the `basis` (or `fock`) function to directly obtain the required state:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\1.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 0.]\n", + " [ 1.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ket = basis(5, 2)\n", + "ket" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how it is automatically normalized. We can also use the built in `num` operator:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 1.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 2.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 3.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 4.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0. 0. 0. 0.]\n", + " [ 0. 1. 0. 0. 0.]\n", + " [ 0. 0. 2. 0. 0.]\n", + " [ 0. 0. 0. 3. 0.]\n", + " [ 0. 0. 0. 0. 4.]]" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "n = num(5)\n", + "n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Therefore, instead of ``c * a * (c ** 2 * vac).unit()`` we have:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\2.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 0.]\n", + " [ 2.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "n * ket" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also create superpositions of states:" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.707\\\\0.707\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.70710678]\n", + " [ 0.70710678]\n", + " [ 0. ]\n", + " [ 0. ]\n", + " [ 0. ]]" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ket = (basis(5, 0) + basis(5, 1)).unit()\n", + "ket" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have used the `Qobj.unit` method to again normalize the state. Operating with the number function again:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.707\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0. ]\n", + " [ 0.70710678]\n", + " [ 0. ]\n", + " [ 0. ]\n", + " [ 0. ]]" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "n * ket" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also create coherent states and squeezed states by applying the `displace` and `squeeze` functions to the vacuum state:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.607\\\\0.606j\\\\-0.430\\\\-0.241j\\\\0.146\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.60655682+0.j ]\n", + " [ 0.00000000+0.60628133j]\n", + " [-0.43038740+0.j ]\n", + " [ 0.00000000-0.24104351j]\n", + " [ 0.14552147+0.j ]]" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "vac = basis(5, 0)\n", + "d = displace(5, 1j)\n", + "s = squeeze(5, 0.25 + 0.25j)\n", + "d * vac" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}(0.659+0.081j)\\\\(0.108+0.516j)\\\\(-0.376-0.013j)\\\\(-0.027-0.238j)\\\\(0.264+0.115j)\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.65893786+0.08139381j]\n", + " [ 0.10779462+0.51579735j]\n", + " [-0.37567217-0.01326853j]\n", + " [-0.02688063-0.23828775j]\n", + " [ 0.26352814+0.11512178j]]" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d * s * vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Of course, displacing the vacuum gives a coherent state, which can also be generated using the built in `coherent` function." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##Density Matrices\n", + "\n", + "One of the main purpose of QuTiP is to explore the dynamics of **open** quantum systems, where the most general state of a system is not longer a state vector, but rather a density matrix. Since operations on density matrices operate identically to those of vectors, we will just briefly highlight creating and using these structures.\n", + "\n", + "The simplest density matrix is created by forming the outer-product $\\left|\\psi\\right>\\left<\\psi\\right|$ of a ket vector:" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 1.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 1. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]]" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ket = basis(5, 2)\n", + "ket * ket.dag()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A similar task can also be accomplished via the `fock_dm` or `ket2dm` functions:" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 1.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 1. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]]" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "fock_dm(5, 2)" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 1.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 1. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]\n", + " [ 0. 0. 0. 0. 0.]]" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ket2dm(ket)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we want to create a density matrix with equal classical probability of being found in the $\\left|2\\right>$ or $\\left|4\\right>$ number states we can do the following:" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.500 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.500\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0. 0. 0. 0. ]\n", + " [ 0. 0. 0. 0. 0. ]\n", + " [ 0. 0. 0.5 0. 0. ]\n", + " [ 0. 0. 0. 0. 0. ]\n", + " [ 0. 0. 0. 0. 0.5]]" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "0.5 * ket2dm(basis(5, 4)) + 0.5 * ket2dm(basis(5, 2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or use ``0.5 * fock_dm(5, 2) + 0.5 * fock_dm(5, 4)``. There are also several other built-in functions for creating predefined density matrices, for example `coherent_dm` and `thermal_dm` which create coherent state and thermal state density matrices, respectively." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.210 & 0.261 & 0.235 & 0.156 & 0.134\\\\0.261 & 0.326 & 0.293 & 0.194 & 0.167\\\\0.235 & 0.293 & 0.263 & 0.174 & 0.150\\\\0.156 & 0.194 & 0.174 & 0.116 & 0.099\\\\0.134 & 0.167 & 0.150 & 0.099 & 0.085\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0.20980701 0.26141096 0.23509686 0.15572585 0.13390765]\n", + " [ 0.26141096 0.32570738 0.29292109 0.19402805 0.16684347]\n", + " [ 0.23509686 0.29292109 0.26343512 0.17449684 0.1500487 ]\n", + " [ 0.15572585 0.19402805 0.17449684 0.11558499 0.09939079]\n", + " [ 0.13390765 0.16684347 0.1500487 0.09939079 0.0854655 ]]" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "coherent_dm(5, 1.25)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.469 & 0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.261 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.145 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.080 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0 & 0.045\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[5], [5]], shape = [5, 5], type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0.46927974 0. 0. 0. 0. ]\n", + " [ 0. 0.26071096 0. 0. 0. ]\n", + " [ 0. 0. 0.14483942 0. 0. ]\n", + " [ 0. 0. 0. 0.08046635 0. ]\n", + " [ 0. 0. 0. 0. 0.04470353]]" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "thermal_dm(5, 1.25)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "QuTiP also provides a set of distance metrics for determining how close two density matrix distributions are to each other. Included are the trace distance `tracedist`, fidelity `fidelity`, Hilbert-Schmidt distance `hilbert_dist`, Bures distance `bures_dist`, and Bures angle `bures_angle`." + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "x = coherent_dm(5, 1.25)\n", + "y = coherent_dm(5, 1.25j) # <-- note the 'j'\n", + "z = thermal_dm(5, 0.125)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1.0000000208397526" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "fidelity(x, x)" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.0" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tracedist(y, y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We also know that for two pure states, the trace distance (T) and the fidelity (F) are related by $T = \\sqrt{1 - F^{2}}$." + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.9771565895267291 0.977156570135\n" + ] + } + ], + "source": [ + "print(tracedist(y, x), np.sqrt(1 - fidelity(y, x) ** 2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For a pure state and a mixed state, $1 - F^{2} \\le T$ which can also be verified:" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.7782890497791632 0.8559028328862591\n" + ] + } + ], + "source": [ + "print(1 - fidelity(x, z) ** 2, tracedist(x, z))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##Qubit (Two-level) Systems\n", + "\n", + "Having spent a fair amount of time on basis states that represent harmonic oscillator states, we now move on to qubit, or two-level quantum systems (for example a spin-1/2). To create a state vector corresponding to a qubit system, we use the same `basis`, or `fock`, function with only two levels:" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "spin = basis(2, 0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now at this point one may ask how this state is different than that of a harmonic oscillator in the vacuum state truncated to two energy levels?" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "vac = basis(2, 0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "At this stage, there is no difference. This should not be surprising as we called the exact same function twice. The difference between the two comes from the action of the spin operators `sigmax`, `sigmay`, `sigmaz`, `sigmap`, and `sigmam` on these two-level states. For example, if ``vac`` corresponds to the vacuum state of a harmonic oscillator, then, as we have already seen, we can use the raising operator to get the $\\left|1\\right>$ state:" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\1.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 1.]]" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c = create(2)\n", + "c * vac" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For a spin system, the operator analogous to the raising operator is the sigma-plus operator `sigmap`. Operating on the ``spin`` state gives:" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 45, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sigmap() * spin" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we see the difference! The `sigmap` operator acting on the ``spin`` state returns the zero vector. Why is this? To see what happened, let us use the `sigmaz` operator:" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}1.0 & 0.0\\\\0.0 & -1.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 1. 0.]\n", + " [ 0. -1.]]" + ] + }, + "execution_count": 46, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sigmaz()" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}1.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\n", + "Qobj data =\n", + "[[ 1.]\n", + " [ 0.]]" + ] + }, + "execution_count": 47, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sigmaz() * spin" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\-1.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [-1.]]" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "spin2 = basis(2, 1)\n", + "sigmaz() * spin2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The answer is now apparent. Since the QuTiP `sigmaz` function uses the standard z-basis representation of the sigma-z spin operator, the ``spin`` state corresponds to the $\\left|\\uparrow\\right>$ state of a two-level spin system while ``spin2`` gives the $\\left|\\downarrow\\right>$ state. Therefore, in our previous example ``sigmap() * spin``, we raised the qubit state out of the truncated two-level Hilbert space resulting in the zero state. \n", + "\n", + "While at first glance this convention might seem somewhat odd, it is in fact quite handy. For one, the spin operators remain in the conventional form. Second, when the spin system is in the $\\left|\\uparrow\\right>$ state:" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\\begin{equation*}\\left(\\begin{array}{*{11}c}1.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket\n", + "Qobj data =\n", + "[[ 1.]\n", + " [ 0.]]" + ] + }, + "execution_count": 49, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sigmaz() * spin" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "the non-zero component is the zeroth-element of the underlying matrix (remember that python uses c-indexing, and matrices start with the zeroth element). The $\\left|\\downarrow\\right>$ state therefore has a non-zero entry in the first index position. This corresponds nicely with the quantum information definitions of qubit states, where the excited $\\left|\\uparrow\\right>$ state is label as $\\left|0\\right>$, and the $\\left|\\downarrow\\right>$ state by $\\left|1\\right>$.\n", + "\n", + "If one wants to create spin operators for higher spin systems, then the `jmat` function comes in handy. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##Expectation Values\n", + "\n", + "Some of the most important information about quantum systems comes from calculating the expectation value of operators, both Hermitian and non-Hermitian, as the state or density matrix of the system varies in time. Therefore, in this section we demonstrate the use of the `expect` function. To begin:\n" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.0" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "vac = basis(5, 0)\n", + "one = basis(5, 1)\n", + "c = create(5)\n", + "N = num(5)\n", + "\n", + "expect(N, vac)" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1.0" + ] + }, + "execution_count": 51, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "expect(N, one)" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.9970555745806599" + ] + }, + "execution_count": 52, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "coh = coherent_dm(5, 1.0j)\n", + "expect(N, coh)" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.9999999999999998j" + ] + }, + "execution_count": 53, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "cat = (basis(5, 4) + 1.0j * basis(5, 3)).unit()\n", + "expect(c, cat)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how in this last example, all of the return values are complex numbers. This is because the `expect` function looks to see whether the operator is Hermitian or not. If the operator is Hermitian, than the output will always be real. In the case of non-Hermitian operators, the return values may be complex. Therefore, the `expect` function will return an array of complex values for non-Hermitian operators when the input is a list/array of states or density matrices.\n", + "\n", + "\n", + "Of course, the `expect` function works for spin states and operators as well:" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1.0" + ] + }, + "execution_count": 54, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "up = basis(2, 0)\n", + "down = basis(2, 1)\n", + "\n", + "expect(sigmaz(), up)" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "-1.0" + ] + }, + "execution_count": 55, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "expect(sigmaz(), down)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "as well as the composite objects discussed in the next section ([Tensor Products & Partial Traces](TensorPtrace.ipynb)):" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1.0" + ] + }, + "execution_count": 56, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "spin1 = basis(2, 0)\n", + "spin2 = basis(2, 1)\n", + "two_spins = tensor(spin1, spin2)\n", + "sz1 = tensor(sigmaz(), qeye(2))\n", + "sz2 = tensor(qeye(2), sigmaz())\n", + "\n", + "expect(sz1, two_spins)" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "-1.0" + ] + }, + "execution_count": 57, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "expect(sz2, two_spins)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "##Super Operators and Vectorized Operators\n", + "\n", + "In addition to state vectors and density operators, QuTiP allows for\n", + "representing maps that act linearly on density operators using the Kraus,\n", + "Liouville supermatrix and Choi matrix formalisms. This support is based on the\n", + "correspondance between linear operators acting on a Hilbert space, and vectors\n", + "in two copies of that Hilbert space,\n", + ":$\\mathrm{vec} : \\mathcal{L}(\\mathcal{H}) \\to \\mathcal{H} \\otimes \\mathcal{H}$.\n", + "\n", + "This isomorphism is implemented in QuTiP by the `operator_to_vector` and \n", + "`vector_to_operator` functions:" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-ket\\begin{equation*}\\left(\\begin{array}{*{11}c}1.0\\\\0.0\\\\0.0\\\\0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-ket\n", + "Qobj data =\n", + "[[ 1.]\n", + " [ 0.]\n", + " [ 0.]\n", + " [ 0.]]" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "rho = fock_dm(2,0)\n", + "vec_rho = operator_to_vector(rho)\n", + "vec_rho" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.0" + ] + }, + "execution_count": 60, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "rho2 = vector_to_operator(vec_rho)\n", + "(rho - rho2).norm()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `Qobj.type` attribute indicates whether a quantum object is\n", + "a vector corresponding to an operator (``operator-ket``), or its Hermitian\n", + "conjugate (``operator-bra``).\n", + "\n", + "Note that QuTiP uses the *column-stacking* convention for the isomorphism\n", + "between $\\mathcal{L}(\\mathcal{H})$ and $\\mathcal{H} \\otimes \\mathcal{H}$:" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isherm = False\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 1.0\\\\2.0 & 3.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isherm = False\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 2. 3.]]" + ] + }, + "execution_count": 61, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A = Qobj(np.arange(4).reshape((2, 2)))\n", + "A" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-ket\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0\\\\2.0\\\\1.0\\\\3.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-ket\n", + "Qobj data =\n", + "[[ 0.]\n", + " [ 2.]\n", + " [ 1.]\n", + " [ 3.]]" + ] + }, + "execution_count": 62, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "operator_to_vector(A)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since $\\mathcal{H} \\otimes \\mathcal{H}$ is a vector space, linear maps\n", + "on this space can be represented as matrices, often called *supermatrices*.\n", + "Using the `Qobj`, the `spre` and `spost` functions, supermatrices\n", + "corresponding to left- and right-multiplication respectively can be quickly\n", + "constructed." + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "X = sigmax()\n", + "S = spre(X) * spost(X.dag()) # Represents conjugation by X." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that this is done automatically by the `to_super` function when given\n", + "``type='oper'`` input." + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.0" + ] + }, + "execution_count": 65, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "S2 = to_super(X)\n", + "(S - S2).norm()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Quantum objects representing superoperators are denoted by ``type='super'``:" + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 0.0 & 0.0 & 1.0\\\\0.0 & 0.0 & 1.0 & 0.0\\\\0.0 & 1.0 & 0.0 & 0.0\\\\1.0 & 0.0 & 0.0 & 0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0. 0. 1.]\n", + " [ 0. 0. 1. 0.]\n", + " [ 0. 1. 0. 0.]\n", + " [ 1. 0. 0. 0.]]" + ] + }, + "execution_count": 66, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "S" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Information about superoperators, such as whether they represent completely\n", + "positive maps, is exposed through the `iscp`, `Qobj.istp`\n", + "and `Qobj.iscptp` attributes:" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(True, True, True)" + ] + }, + "execution_count": 67, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "S.iscp, S.istp, S.iscptp" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In addition, dynamical generators on this extended space, often called\n", + "*Liouvillian superoperators*, can be created using the `liouvillian` function. Each of these takes a Hamilonian along with a list of collapse operators, and returns a ``type=\"super\"`` object that can be exponentiated to find the superoperator for that evolution." + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = False\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 0.0 & 0.0 & 1.0\\\\0.0 & (-0.500+20.0j) & 0.0 & 0.0\\\\0.0 & 0.0 & (-0.500-20.0j) & 0.0\\\\0.0 & 0.0 & 0.0 & -1.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = False\n", + "Qobj data =\n", + "[[ 0.0 +0.j 0.0 +0.j 0.0 +0.j 1.0 +0.j]\n", + " [ 0.0 +0.j -0.5+20.j 0.0 +0.j 0.0 +0.j]\n", + " [ 0.0 +0.j 0.0 +0.j -0.5-20.j 0.0 +0.j]\n", + " [ 0.0 +0.j 0.0 +0.j 0.0 +0.j -1.0 +0.j]]" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "H = 10 * sigmaz()\n", + "c1 = destroy(2)\n", + "L = liouvillian(H, [c1])\n", + "L" + ] + }, + { + "cell_type": "code", + "execution_count": 74, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = False\\begin{equation*}\\left(\\begin{array}{*{11}c}1.0 & 0.0 & 0.0 & 1.000\\\\0.0 & (8.075\\times10^{-04}+0.002j) & 0.0 & 0.0\\\\0.0 & 0.0 & (8.075\\times10^{-04}-0.002j) & 0.0\\\\0.0 & 0.0 & 0.0 & 6.144\\times10^{-06}\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = False\n", + "Qobj data =\n", + "[[ 1.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j\n", + " 9.99993856e-01+0.j ]\n", + " [ 0.00000000e+00+0.j 8.07531120e-04+0.00234352j\n", + " 0.00000000e+00+0.j 0.00000000e+00+0.j ]\n", + " [ 0.00000000e+00+0.j 0.00000000e+00+0.j\n", + " 8.07531120e-04-0.00234352j 0.00000000e+00+0.j ]\n", + " [ 0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j\n", + " 6.14421235e-06+0.j ]]" + ] + }, + "execution_count": 74, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "S = (12 * L).expm()\n", + "S" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Once a superoperator has been obtained, it can be converted between the\n", + "supermatrix, Kraus and Choi formalisms by using the `superop_reps.to_super`,\n", + "`superop_reps.to_kraus` and `superop_reps.to_choi` functions. The `Qobj.superrep`\n", + "attribute keeps track of what reprsentation is a `Qobj` is currently using." + ] + }, + { + "cell_type": "code", + "execution_count": 76, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True, superrep = choi\\begin{equation*}\\left(\\begin{array}{*{11}c}1.0 & 0.0 & 0.0 & (8.075\\times10^{-04}-0.002j)\\\\0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 1.000 & 0.0\\\\(8.075\\times10^{-04}+0.002j) & 0.0 & 0.0 & 6.144\\times10^{-06}\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True, superrep = choi\n", + "Qobj data =\n", + "[[ 1.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j\n", + " 8.07531120e-04-0.00234352j]\n", + " [ 0.00000000e+00+0.j 0.00000000e+00+0.j 0.00000000e+00+0.j\n", + " 0.00000000e+00+0.j ]\n", + " [ 0.00000000e+00+0.j 0.00000000e+00+0.j 9.99993856e-01+0.j\n", + " 0.00000000e+00+0.j ]\n", + " [ 8.07531120e-04+0.00234352j 0.00000000e+00+0.j 0.00000000e+00+0.j\n", + " 6.14421235e-06+0.j ]]" + ] + }, + "execution_count": 76, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "J = to_choi(S)\n", + "J" + ] + }, + { + "cell_type": "code", + "execution_count": 77, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isherm = False\n", + " Qobj data =\n", + " [[ 1.00000000e+00 +1.34376978e-22j 0.00000000e+00 +0.00000000e+00j]\n", + " [ 0.00000000e+00 +0.00000000e+00j 8.07531120e-04 +2.34352424e-03j]],\n", + " Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isherm = False\n", + " Qobj data =\n", + " [[ -1.11923759e-13 +6.02807402e-15j 0.00000000e+00 +0.00000000e+00j]\n", + " [ 0.00000000e+00 +0.00000000e+00j 1.70093171e-11 +4.18976706e-11j]],\n", + " Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isherm = True\n", + " Qobj data =\n", + " [[ 0. 0.]\n", + " [ 0. 0.]],\n", + " Quantum object: dims = [[2], [2]], shape = [2, 2], type = oper, isherm = False\n", + " Qobj data =\n", + " [[ 0. 0.99999693]\n", + " [ 0. 0. ]]]" + ] + }, + "execution_count": 77, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "K = to_kraus(J)\n", + "K" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + "\n", + "\n" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from IPython.core.display import HTML\n", + "def css_styling():\n", + " styles = open(\"../styles/guide.css\", \"r\").read()\n", + " return HTML(styles)\n", + "css_styling()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/jupyter/math/SymPy_9b271e.ipynb b/jupyter/math/SymPy_9b271e.ipynb new file mode 100644 index 0000000..ab6c590 --- /dev/null +++ b/jupyter/math/SymPy_9b271e.ipynb @@ -0,0 +1,670 @@ +{ + "metadata": { + "name": "", + "signature": "sha256:a0f4cda82587c5b8e7a4502192d1210abedac9084077604eb60aea15f262a344" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# SymPy: Open Source Symbolic Mathematics\n", + "\n", + "This notebook uses the [SymPy](http://sympy.org) package to perform symbolic manipulations,\n", + "and combined with numpy and matplotlib, also displays numerical visualizations of symbolically\n", + "constructed expressions.\n", + "\n", + "We first load sympy printing extensions, as well as all of sympy:" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "from IPython.display import display\n", + "\n", + "from sympy.interactive import printing\n", + "printing.init_printing(use_latex='mathjax')\n", + "\n", + "from __future__ import division\n", + "import sympy as sym\n", + "from sympy import *\n", + "x, y, z = symbols(\"x y z\")\n", + "k, m, n = symbols(\"k m n\", integer=True)\n", + "f, g, h = map(Function, 'fgh')" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

Elementary operations

" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "Rational(3,2)*pi + exp(I*x) / (x**2 + y)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$\\frac{3 \\pi}{2} + \\frac{e^{i x}}{x^{2} + y}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 2, + "text": [ + " \u2148\u22c5x \n", + "3\u22c5\u03c0 \u212f \n", + "\u2500\u2500\u2500 + \u2500\u2500\u2500\u2500\u2500\u2500\n", + " 2 2 \n", + " x + y" + ] + } + ], + "prompt_number": 2 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "exp(I*x).subs(x,pi).evalf()" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$-1.0$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 3, + "text": [ + "-1.00000000000000" + ] + } + ], + "prompt_number": 3 + }, + { + "cell_type": "code", + "collapsed": true, + "input": [ + "e = x + 2*y" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 4 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "srepr(e)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "pyout", + "prompt_number": 5, + "text": [ + "\"Add(Symbol('x'), Mul(Integer(2), Symbol('y')))\"" + ] + } + ], + "prompt_number": 5 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "exp(pi * sqrt(163)).evalf(50)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$262537412640768743.99999999999925007259719818568888$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 6, + "text": [ + "262537412640768743.99999999999925007259719818568888" + ] + } + ], + "prompt_number": 6 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

Algebra

" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "eq = ((x+y)**2 * (x+1))\n", + "eq" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$\\left(x + 1\\right) \\left(x + y\\right)^{2}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 7, + "text": [ + " 2\n", + "(x + 1)\u22c5(x + y) " + ] + } + ], + "prompt_number": 7 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "expand(eq)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$x^{3} + 2 x^{2} y + x^{2} + x y^{2} + 2 x y + y^{2}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 8, + "text": [ + " 3 2 2 2 2\n", + "x + 2\u22c5x \u22c5y + x + x\u22c5y + 2\u22c5x\u22c5y + y " + ] + } + ], + "prompt_number": 8 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "a = 1/x + (x*sin(x) - 1)/x\n", + "a" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$\\frac{1}{x} \\left(x \\sin{\\left (x \\right )} - 1\\right) + \\frac{1}{x}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 9, + "text": [ + "x\u22c5sin(x) - 1 1\n", + "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 + \u2500\n", + " x x" + ] + } + ], + "prompt_number": 9 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "simplify(a)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$\\sin{\\left (x \\right )}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 10, + "text": [ + "sin(x)" + ] + } + ], + "prompt_number": 10 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "eq = Eq(x**3 + 2*x**2 + 4*x + 8, 0)\n", + "eq" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$x^{3} + 2 x^{2} + 4 x + 8 = 0$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 11, + "text": [ + " 3 2 \n", + "x + 2\u22c5x + 4\u22c5x + 8 = 0" + ] + } + ], + "prompt_number": 11 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "solve(eq, x)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$\\begin{bmatrix}-2, & - 2 i, & 2 i\\end{bmatrix}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 12, + "text": [ + "[-2, -2\u22c5\u2148, 2\u22c5\u2148]" + ] + } + ], + "prompt_number": 12 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "a, b = symbols('a b')\n", + "Sum(6*n**2 + 2**n, (n, a, b))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$\\sum_{n=a}^{b} \\left(2^{n} + 6 n^{2}\\right)$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 13, + "text": [ + " b \n", + " ___ \n", + " \u2572 \n", + " \u2572 \u239b n 2\u239e\n", + " \u2571 \u239d2 + 6\u22c5n \u23a0\n", + " \u2571 \n", + " \u203e\u203e\u203e \n", + "n = a " + ] + } + ], + "prompt_number": 13 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

Calculus

" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "limit((sin(x)-x)/x**3, x, 0)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$- \\frac{1}{6}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 14, + "text": [ + "-1/6" + ] + } + ], + "prompt_number": 14 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "(1/cos(x)).series(x, 0, 6)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$1 + \\frac{x^{2}}{2} + \\frac{5 x^{4}}{24} + \\mathcal{O}\\left(x^{6}\\right)$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 15, + "text": [ + " 2 4 \n", + " x 5\u22c5x \u239b 6\u239e\n", + "1 + \u2500\u2500 + \u2500\u2500\u2500\u2500 + O\u239dx \u23a0\n", + " 2 24 " + ] + } + ], + "prompt_number": 15 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "diff(cos(x**2)**2 / (1+x), x)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$- \\frac{4 x \\cos{\\left (x^{2} \\right )}}{x + 1} \\sin{\\left (x^{2} \\right )} - \\frac{\\cos^{2}{\\left (x^{2} \\right )}}{\\left(x + 1\\right)^{2}}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 16, + "text": [ + " \u239b 2\u239e \u239b 2\u239e 2\u239b 2\u239e\n", + " 4\u22c5x\u22c5sin\u239dx \u23a0\u22c5cos\u239dx \u23a0 cos \u239dx \u23a0\n", + "- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 - \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n", + " x + 1 2\n", + " (x + 1) " + ] + } + ], + "prompt_number": 16 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "integrate(x**2 * cos(x), (x, 0, pi/2))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$-2 + \\frac{\\pi^{2}}{4}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 17, + "text": [ + " 2\n", + " \u03c0 \n", + "-2 + \u2500\u2500\n", + " 4 " + ] + } + ], + "prompt_number": 17 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "eqn = Eq(Derivative(f(x),x,x) + 9*f(x), 1)\n", + "display(eqn)\n", + "dsolve(eqn, f(x))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$9 f{\\left (x \\right )} + \\frac{d^{2}}{d x^{2}} f{\\left (x \\right )} = 1$$" + ], + "metadata": {}, + "output_type": "display_data", + "text": [ + " 2 \n", + " d \n", + "9\u22c5f(x) + \u2500\u2500\u2500(f(x)) = 1\n", + " 2 \n", + " dx " + ] + }, + { + "latex": [ + "$$f{\\left (x \\right )} = C_{1} \\sin{\\left (3 x \\right )} + C_{2} \\cos{\\left (3 x \\right )} + \\frac{1}{9}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 18, + "text": [ + "f(x) = C\u2081\u22c5sin(3\u22c5x) + C\u2082\u22c5cos(3\u22c5x) + 1/9" + ] + } + ], + "prompt_number": 18 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Illustrating Taylor series\n", + "\n", + "We will define a function to compute the Taylor series expansions of a symbolically defined expression at\n", + "various orders and visualize all the approximations together with the original function" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "%matplotlib inline\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 19 + }, + { + "cell_type": "code", + "collapsed": true, + "input": [ + "# You can change the default figure size to be a bit larger if you want,\n", + "# uncomment the next line for that:\n", + "#plt.rc('figure', figsize=(10, 6))" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 20 + }, + { + "cell_type": "code", + "collapsed": true, + "input": [ + "def plot_taylor_approximations(func, x0=None, orders=(2, 4), xrange=(0,1), yrange=None, npts=200):\n", + " \"\"\"Plot the Taylor series approximations to a function at various orders.\n", + "\n", + " Parameters\n", + " ----------\n", + " func : a sympy function\n", + " x0 : float\n", + " Origin of the Taylor series expansion. If not given, x0=xrange[0].\n", + " orders : list\n", + " List of integers with the orders of Taylor series to show. Default is (2, 4).\n", + " xrange : 2-tuple or array.\n", + " Either an (xmin, xmax) tuple indicating the x range for the plot (default is (0, 1)),\n", + " or the actual array of values to use.\n", + " yrange : 2-tuple\n", + " (ymin, ymax) tuple indicating the y range for the plot. If not given,\n", + " the full range of values will be automatically used. \n", + " npts : int\n", + " Number of points to sample the x range with. Default is 200.\n", + " \"\"\"\n", + " if not callable(func):\n", + " raise ValueError('func must be callable')\n", + " if isinstance(xrange, (list, tuple)):\n", + " x = np.linspace(float(xrange[0]), float(xrange[1]), npts)\n", + " else:\n", + " x = xrange\n", + " if x0 is None: x0 = x[0]\n", + " xs = sym.Symbol('x')\n", + " # Make a numpy-callable form of the original function for plotting\n", + " fx = func(xs)\n", + " f = sym.lambdify(xs, fx, modules=['numpy'])\n", + " # We could use latex(fx) instead of str(), but matploblib gets confused\n", + " # with some of the (valid) latex constructs sympy emits. So we play it safe.\n", + " plt.plot(x, f(x), label=str(fx), lw=2)\n", + " # Build the Taylor approximations, plotting as we go\n", + " apps = {}\n", + " for order in orders:\n", + " app = fx.series(xs, x0, n=order).removeO()\n", + " apps[order] = app\n", + " # Must be careful here: if the approximation is a constant, we can't\n", + " # blindly use lambdify as it won't do the right thing. In that case, \n", + " # evaluate the number as a float and fill the y array with that value.\n", + " if isinstance(app, sym.numbers.Number):\n", + " y = np.zeros_like(x)\n", + " y.fill(app.evalf())\n", + " else:\n", + " fa = sym.lambdify(xs, app, modules=['numpy'])\n", + " y = fa(x)\n", + " tex = sym.latex(app).replace('$', '')\n", + " plt.plot(x, y, label=r'$n=%s:\\, %s$' % (order, tex) )\n", + " \n", + " # Plot refinements\n", + " if yrange is not None:\n", + " plt.ylim(*yrange)\n", + " plt.grid()\n", + " plt.legend(loc='best').get_frame().set_alpha(0.8)" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 21 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With this function defined, we can now use it for any sympy function or expression" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "plot_taylor_approximations(sin, 0, [2, 4, 6], (0, 2*pi), (-2,2))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "display_data", + "png": "iVBORw0KGgoAAAANSUhEUgAAAXoAAAEACAYAAAC9Gb03AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJztnXlYVVX3xz8XcMIBHHEWBRVQEBTFBgvNEYecckpzyLLR\nn2VW5ltmmVNlk75lvjllmmlZaEoO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161atJRlFVlYWsbGxvPTSS8TGxlK2bFmmTZumtSyTyczMZNWqVTz11FOF\nttPU0NeqVYuzZ8/mHZ89e5batWtrqKj4cevWLfr06cPgwYPp2bOn1nLMxs3Nja5du7J7926tpRjF\njh07CA8Pp379+gwcOJDIyEieeeYZrWWZTI0aNQCoWrUqvXr1IiYmRmNFxlG7dm1q165Ny5YtAejb\nty+xsbEaqzKdtWvX0qJFC6pWrVpoO00NfXBwMMeOHSMuLo7MzEyWLVtGjx49tJRUrBBC8Oyzz+Ln\n58eYMWO0lmMyly5dyktIdePGDdavX09QUJDGqoxjypQpnD17llOnTvHjjz/Srl07Fi1apLUsk7h+\n/TppaWkAXLt2jXXr1ukmAq169erUqVOHo0ePAtLP3aRJE41Vmc7SpUsZOHDgA9sVmuvG1ty5oSo7\nO5tnn31WVxuqBg4cyObNm7l8+TJ16tThgw8+YPjw4VrLMprt27ezePHivPA4gKlTp9K5c2eNlRlH\nYmIiQ4cOJScnh5ycHIYMGcITTzyhtSyz0KMbMykpiV69egHSFfL000/TsWNHjVUZz1dffcXTTz9N\nZmYmXl5ezJ8/X2tJJnHt2jU2bNhg1NqI2jClUCgUDo5+l/sVCoVCYRTK0CsUCoWDowy9QqFQODjK\n0CsUCoWDowy9QqFQODjK0CsUCoWDowy9QqFQODjK0CsUCoWD8//NvpMqig2bWwAAAABJRU5ErkJg\ngg==\n", + "text": [ + "" + ] + } + ], + "prompt_number": 22 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "plot_taylor_approximations(cos, 0, [2, 4, 6], (0, 2*pi), (-2,2))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "display_data", + "png": "iVBORw0KGgoAAAANSUhEUgAAAXoAAAEACAYAAAC9Gb03AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XlcFdX/x/HXZVMBBU3FBRRBFFAEFMUyDUtcc81KLZU0\ns0VNsyxb3XLL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iQorL55O3t7QHIyclBp9NRo0YNhRPp78KFC2zYsIFXX31V\n1RP6qTH7rVu32L59O8OGDQPk+4lOTk4KpzLMpk2b8PT0LPTM0oMUbejFA1WWIzExkdjYWIKDg5WO\nUir5+fkEBATg4uJCx44d8fX1VTqS3saNG8cXX3xR8IS5Gmk0Gjp16kRQUBALFy5UOo7ezp49S61a\ntXjllVdo2bIlI0aMIDMzU+lYBlm5cmWRzzHdT9HfsIr0QJUly8jIoH///sydOxdHR0el45SKlZUV\ncXFxXLhwgX///Vc1i3isX7+e2rVrExgYqMoe8T07d+4kNjaWyMhI5s+fz/bt25WOpJe8vDwOHDjA\nm2++yYEDB3BwcGDmzJlKxyq1nJwc1q1bx/PPP1/ifoo29PXr1ycpKalgOykpCVdXVwUTVTy5ubk8\n99xzvPzyy/Tp00fpOAZzcnKiR48eqpmzfdeuXYSHh9OoUSMGDhzIli1bGDJkiNKxSq1u3boA1KpV\ni759+xITE6NwIv24urri6upK69atAejfvz8HDhxQOFXpRUZG0qpVK2rVqlXifoo29EFBQZw8eZLE\nxERycnJYtWoVvXr1UjJShSJJEsOHD8fX15exY8cqHafUrl27VjAhVVZWFhs3biQwMFDhVPqZPn06\nSUlJnD17lpUrV/L000+zfPlypWOVSmZmZsEyfLdv3+aff/5RzQi0OnXq4ObmxokTJwC5zt2sWTOF\nU5XeihUrGDhw4CP3U3ThkfsfqNLpdAwfPlxVD1QNHDiQbdu2cf36ddzc3JgyZQqvvPKK0rH0tnPn\nTn755ZeC4XEAM2bMoGvXrgon08/FixcZOnQo+fn55OfnM3jwYJ555hmlYxlEjWXMy5cv07dvX0Au\nhbz00kt07txZ4VT6++6773jppZfIycnB09OTJUuWKB2pVG7fvs2mTZv0ujciHpgSBEEo59R7u18Q\nBEHQi2joBUEQyjnR0AuCIJRzoqEXBEEo50RDLwiCUM6Jhl4QBKGcEw29IAhCOScaekEQhHLu/wGT\ntYbY1r+2UgAAAABJRU5ErkJggg==\n", + "text": [ + "" + ] + } + ], + "prompt_number": 23 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This shows easily how a Taylor series is useless beyond its convergence radius, illustrated by \n", + "a simple function that has singularities on the real axis:" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "# For an expression made from elementary functions, we must first make it into\n", + "# a callable function, the simplest way is to use the Python lambda construct.\n", + "plot_taylor_approximations(lambda x: 1/cos(x), 0, [2,4,6], (0, 2*pi), (-5,5))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "display_data", + "png": "iVBORw0KGgoAAAANSUhEUgAAAXAAAAD7CAYAAABzGc+QAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJztnXl4TdfCxn8nZhKJWQlirMSUENXJbcxKFa22aJUWHVWL\n3t7qZGqrE62i9962hqqW1u3NZ44qTg3lhkpQlCAqg0jMIZJIzv7+WE4ISc4+U/Zeyfo9z3n2GfZe\n67XtvGedd6/BommahkKhUCikw8doAQqFQqFwDWXgCoVCISnKwBUKhUJSlIErFAqFpCgDVygUCklR\nBq5QKBSSUtbbFYSGhrJnzx5vV6NQKBQlinbt2hEbG1vkPl5vge/ZswdN06R9TJo0ya3jJ07UAI2p\nUwvfZ/p0sc8//qG/3Cnx8bwSF+d1/R5/2GxoTz2F9thj4rls+p18mEH/U0+J62vevML3GTNG7PPZ\nZ+bSLvu5d+ehp+Hr9Ra47Bw/ftyt49PSxLZWLfe13MhPaWnMad7c4X7u6vc4X38N//ufeFgsDnc3\nnX4nkUW//fpMTb3+nizaC0N2/XpQBu5l7AZeu7bnyjySkcGp7Gzu9vf3XKHFwc6d8OabsGUL+Poa\nrUZxA/br0369KuRA3cR0wIgRI9w63t6i8WQL/L+nTzOgZk3K6GjBuqvfY5w+DYMGwb/+Bbffrvsw\n0+h3EVn0F9QCl0V7YciuXw/KwB0QERHh1vFeMfC0NB7SWaC7+j1Cbi4MHQqDB8NDDzl1qCn0u4Es\n+u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tasWfj6+hotRzc+Pj7E\nxsaSmJjI5s2bpVrYYdWqVdSuXZuwsDBpW7Hbtm0jJiaGtWvXMnfuXLZs2WK0JN3k5OSwe/duXnjh\nBXbv3k2VKlX44IMPjJblNNnZ2axcuZJHHnmk0H28ZuD169cnISEh73VCQgKBgYHeqk5RAFevXuXh\nhx/miSeeYMCAAUbLcQl/f3/69u3Lrl27jJaim99++40VK1bQuHFjhgwZwsaNG3nyySeNluUUt10b\n6lmrVi0GDhxIdHS0wYr0ExgYSGBgIB07dgRg0KBB7N6922BVzrN27Vo6dOhArSIWv/WagYeHhxMX\nF8fx48fJzs7mhx9+4MEHH/RWdYqb0DSNkSNHEhISwiuvvGK0HKc4ffp03kREV65cYf369YSFhRms\nSj/vv/8+CQkJxMfHs3TpUrp27cqiRYuMlqWbjIyMvOXILl++zM8//yxVb6y6devSoEEDDh8+DIgc\nuVWrVgarcp4lS5YwZMiQIvfx2nzgZcuWZc6cOfTq1Yvc3FxGjhxJcHCwt6rzOEOGDOHXX3/lzJkz\nNGjQgKlTp/LUU08ZLUs327ZtY/HixXldwQCmT59O7969DVbmmJMnTzJ8+HBsNhs2m41hw4bRrVs3\no2W5jGxx4qlTpxg4cCAg4ojHH3+cnj17GqzKOWbPns3jjz9OdnY2TZs2ZcGCBUZLcorLly/zyy+/\nOLz/oIbSKxQKhaTIeYtcoVAoFMrAFQqFQlaUgSsUCoWkKANXKBQKSVEGrlAoFJKiDFyhUCgkRRm4\nQqFQSIoycIVCoZCU/wdDeJclXk9EegAAAABJRU5ErkJggg==\n", + "text": [ + "" + ] + } + ], + "prompt_number": 24 + } + ], + "metadata": {} + } + ] +} \ No newline at end of file diff --git a/jupyter/math/autodiff_cookbook_a09ead.ipynb b/jupyter/math/autodiff_cookbook_a09ead.ipynb new file mode 100644 index 0000000..97c5470 --- /dev/null +++ b/jupyter/math/autodiff_cookbook_a09ead.ipynb @@ -0,0 +1,1685 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "Ic1reB4s6vu1" + }, + "source": [ + "# The Autodiff Cookbook\n", + "\n", + "\n", + "\n", + "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jax-ml/jax/blob/main/docs/notebooks/autodiff_cookbook.ipynb) [![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://kaggle.com/kernels/welcome?src=https://github.com/jax-ml/jax/blob/main/docs/notebooks/autodiff_cookbook.ipynb)\n", + "\n", + "JAX has a pretty general automatic differentiation system. In this notebook, we'll go through a whole bunch of neat autodiff ideas that you can cherry pick for your own work, starting with the basics." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "id": "JTYyZkSO6vuy" + }, + "outputs": [], + "source": [ + "import jax.numpy as jnp\n", + "from jax import grad, jit, vmap\n", + "from jax import random\n", + "\n", + "key = random.key(0)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "YxnjtAGN6vu2" + }, + "source": [ + "## Gradients" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "zqwpfr2vAsvt" + }, + "source": [ + "### Starting with `grad`\n", + "\n", + "You can differentiate a function with `grad`:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "id": "0NLO4Wfknzmk", + "outputId": "ec6f5fe3-3d90-4ec9-a405-f3191b6099da" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.070650935\n" + ] + } + ], + "source": [ + "grad_tanh = grad(jnp.tanh)\n", + "print(grad_tanh(2.0))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "LGcNfDntoBZI" + }, + "source": [ + "`grad` takes a function and returns a function. If you have a Python function `f` that evaluates the mathematical function $f$, then `grad(f)` is a Python function that evaluates the mathematical function $\\nabla f$. That means `grad(f)(x)` represents the value $\\nabla f(x)$.\n", + "\n", + "Since `grad` operates on functions, you can apply it to its own output to differentiate as many times as you like:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "id": "RDGk1GDsoawu", + "outputId": "157bab60-52a8-4ca9-a298-b57561b30032" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "-0.13621889\n", + "0.2526544\n" + ] + } + ], + "source": [ + "print(grad(grad(jnp.tanh))(2.0))\n", + "print(grad(grad(grad(jnp.tanh)))(2.0))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "2rcnpTiinqi8" + }, + "source": [ + "Let's look at computing gradients with `grad` in a linear logistic regression model. First, the setup:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "id": "27TcOT2i6vu5" + }, + "outputs": [], + "source": [ + "def sigmoid(x):\n", + " return 0.5 * (jnp.tanh(x / 2) + 1)\n", + "\n", + "# Outputs probability of a label being true.\n", + "def predict(W, b, inputs):\n", + " return sigmoid(jnp.dot(inputs, W) + b)\n", + "\n", + "# Build a toy dataset.\n", + "inputs = jnp.array([[0.52, 1.12, 0.77],\n", + " [0.88, -1.08, 0.15],\n", + " [0.52, 0.06, -1.30],\n", + " [0.74, -2.49, 1.39]])\n", + "targets = jnp.array([True, True, False, True])\n", + "\n", + "# Training loss is the negative log-likelihood of the training examples.\n", + "def loss(W, b):\n", + " preds = predict(W, b, inputs)\n", + " label_probs = preds * targets + (1 - preds) * (1 - targets)\n", + " return -jnp.sum(jnp.log(label_probs))\n", + "\n", + "# Initialize random model coefficients\n", + "key, W_key, b_key = random.split(key, 3)\n", + "W = random.normal(W_key, (3,))\n", + "b = random.normal(b_key, ())" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "8Wk-Yai7ooh1" + }, + "source": [ + "Use the `grad` function with its `argnums` argument to differentiate a function with respect to positional arguments." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "id": "bpmd8W8-6vu6", + "outputId": "5faafcc6-e9c5-4a2d-fc35-5c23e0be2d6d" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "W_grad [-0.16965576 -0.8774645 -1.4901344 ]\n", + "W_grad [-0.16965576 -0.8774645 -1.4901344 ]\n", + "b_grad -0.29227236\n", + "W_grad [-0.16965576 -0.8774645 -1.4901344 ]\n", + "b_grad -0.29227236\n" + ] + } + ], + "source": [ + "# Differentiate `loss` with respect to the first positional argument:\n", + "W_grad = grad(loss, argnums=0)(W, b)\n", + "print('W_grad', W_grad)\n", + "\n", + "# Since argnums=0 is the default, this does the same thing:\n", + "W_grad = grad(loss)(W, b)\n", + "print('W_grad', W_grad)\n", + "\n", + "# But we can choose different values too, and drop the keyword:\n", + "b_grad = grad(loss, 1)(W, b)\n", + "print('b_grad', b_grad)\n", + "\n", + "# Including tuple values\n", + "W_grad, b_grad = grad(loss, (0, 1))(W, b)\n", + "print('W_grad', W_grad)\n", + "print('b_grad', b_grad)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "MDl5UZl4oyzB" + }, + "source": [ + "This `grad` API has a direct correspondence to the excellent notation in Spivak's classic *Calculus on Manifolds* (1965), also used in Sussman and Wisdom's [*Structure and Interpretation of Classical Mechanics*](https://mitpress.mit.edu/9780262028967/structure-and-interpretation-of-classical-mechanics) (2015) and their [*Functional Differential Geometry*](https://mitpress.mit.edu/9780262019347/functional-differential-geometry) (2013). Both books are open-access. See in particular the \"Prologue\" section of *Functional Differential Geometry* for a defense of this notation.\n", + "\n", + "Essentially, when using the `argnums` argument, if `f` is a Python function for evaluating the mathematical function $f$, then the Python expression `grad(f, i)` evaluates to a Python function for evaluating $\\partial_i f$." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "fuz9E2vzro5E" + }, + "source": [ + "### Differentiating with respect to nested lists, tuples, and dicts" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "QQaPja7puMKi" + }, + "source": [ + "Differentiating with respect to standard Python containers just works, so use tuples, lists, and dicts (and arbitrary nesting) however you like." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "id": "IY82kdAe6vu_", + "outputId": "d4004d2d-97ed-4ddc-bb1d-fc4af21edd23" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'W': Array([-0.16965576, -0.8774645 , -1.4901344 ], dtype=float32), 'b': Array(-0.29227236, dtype=float32)}\n" + ] + } + ], + "source": [ + "def loss2(params_dict):\n", + " preds = predict(params_dict['W'], params_dict['b'], inputs)\n", + " label_probs = preds * targets + (1 - preds) * (1 - targets)\n", + " return -jnp.sum(jnp.log(label_probs))\n", + "\n", + "print(grad(loss2)({'W': W, 'b': b}))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "cJ2NxiN58bfI" + }, + "source": [ + "You can [register your own container types](https://github.com/jax-ml/jax/issues/446#issuecomment-467105048) to work with not just `grad` but all the JAX transformations (`jit`, `vmap`, etc.)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PaCHzAtGruBz" + }, + "source": [ + "### Evaluate a function and its gradient using `value_and_grad`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "CSgCjjo-ssnA" + }, + "source": [ + "Another convenient function is `value_and_grad` for efficiently computing both a function's value as well as its gradient's value:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "id": "RsQSyT5p7OJW", + "outputId": "c2502c2e-091e-4e9c-ca20-1e0c2670fd7a" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "loss value 3.051939\n", + "loss value 3.051939\n" + ] + } + ], + "source": [ + "from jax import value_and_grad\n", + "loss_value, Wb_grad = value_and_grad(loss, (0, 1))(W, b)\n", + "print('loss value', loss_value)\n", + "print('loss value', loss(W, b))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "rYTrH5tKllC_" + }, + "source": [ + "### Checking against numerical differences\n", + "\n", + "A great thing about derivatives is that they're straightforward to check with finite differences:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "id": "R8q5RiY3l7Fw", + "outputId": "4f2ccbe9-da9f-438e-9f3e-ad03e3c3e247" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "b_grad_numerical -0.29563904\n", + "b_grad_autodiff -0.29227236\n", + "W_dirderiv_numerical -0.19788742\n", + "W_dirderiv_autodiff -0.19909099\n" + ] + } + ], + "source": [ + "# Set a step size for finite differences calculations\n", + "eps = 1e-4\n", + "\n", + "# Check b_grad with scalar finite differences\n", + "b_grad_numerical = (loss(W, b + eps / 2.) - loss(W, b - eps / 2.)) / eps\n", + "print('b_grad_numerical', b_grad_numerical)\n", + "print('b_grad_autodiff', grad(loss, 1)(W, b))\n", + "\n", + "# Check W_grad with finite differences in a random direction\n", + "key, subkey = random.split(key)\n", + "vec = random.normal(subkey, W.shape)\n", + "unitvec = vec / jnp.sqrt(jnp.vdot(vec, vec))\n", + "W_grad_numerical = (loss(W + eps / 2. * unitvec, b) - loss(W - eps / 2. * unitvec, b)) / eps\n", + "print('W_dirderiv_numerical', W_grad_numerical)\n", + "print('W_dirderiv_autodiff', jnp.vdot(grad(loss)(W, b), unitvec))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "InzB-iiJpVcx" + }, + "source": [ + "JAX provides a simple convenience function that does essentially the same thing, but checks up to any order of differentiation that you like:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "id": "6Ok2LEfQmOuy" + }, + "outputs": [], + "source": [ + "from jax.test_util import check_grads\n", + "check_grads(loss, (W, b), order=2) # check up to 2nd order derivatives" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "id0DXxwt3VJi" + }, + "source": [ + "### Hessian-vector products with `grad`-of-`grad`\n", + "\n", + "One thing we can do with higher-order `grad` is build a Hessian-vector product function. (Later on we'll write an even more efficient implementation that mixes both forward- and reverse-mode, but this one will use pure reverse-mode.)\n", + "\n", + "A Hessian-vector product function can be useful in a [truncated Newton Conjugate-Gradient algorithm](https://en.wikipedia.org/wiki/Truncated_Newton_method) for minimizing smooth convex functions, or for studying the curvature of neural network training objectives (e.g. [1](https://arxiv.org/abs/1406.2572), [2](https://arxiv.org/abs/1811.07062), [3](https://arxiv.org/abs/1706.04454), [4](https://arxiv.org/abs/1802.03451)).\n", + "\n", + "For a scalar-valued function $f : \\mathbb{R}^n \\to \\mathbb{R}$ with continuous second derivatives (so that the Hessian matrix is symmetric), the Hessian at a point $x \\in \\mathbb{R}^n$ is written as $\\partial^2 f(x)$. A Hessian-vector product function is then able to evaluate\n", + "\n", + "$\\qquad v \\mapsto \\partial^2 f(x) \\cdot v$\n", + "\n", + "for any $v \\in \\mathbb{R}^n$.\n", + "\n", + "The trick is not to instantiate the full Hessian matrix: if $n$ is large, perhaps in the millions or billions in the context of neural networks, then that might be impossible to store.\n", + "\n", + "Luckily, `grad` already gives us a way to write an efficient Hessian-vector product function. We just have to use the identity\n", + "\n", + "$\\qquad \\partial^2 f (x) v = \\partial [x \\mapsto \\partial f(x) \\cdot v] = \\partial g(x)$,\n", + "\n", + "where $g(x) = \\partial f(x) \\cdot v$ is a new scalar-valued function that dots the gradient of $f$ at $x$ with the vector $v$. Notice that we're only ever differentiating scalar-valued functions of vector-valued arguments, which is exactly where we know `grad` is efficient.\n", + "\n", + "In JAX code, we can just write this:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "id": "Ou5OU-gU9epm" + }, + "outputs": [], + "source": [ + "def hvp(f, x, v):\n", + " return grad(lambda x: jnp.vdot(grad(f)(x), v))(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Rb1-5Hpv-ZV0" + }, + "source": [ + "This example shows that you can freely use lexical closure, and JAX will never get perturbed or confused.\n", + "\n", + "We'll check this implementation a few cells down, once we see how to compute dense Hessian matrices. We'll also write an even better version that uses both forward-mode and reverse-mode." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "5A_akvtp8UTu" + }, + "source": [ + "### Jacobians and Hessians using `jacfwd` and `jacrev`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "UP5BbmSm8ZwK" + }, + "source": [ + "You can compute full Jacobian matrices using the `jacfwd` and `jacrev` functions:" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "id": "cbETzAvKvf5I", + "outputId": "7c8d2361-cc68-4139-9f1f-afa2431b3cd2" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "jacfwd result, with shape (4, 3)\n", + "[[ 0.05981756 0.12883782 0.088576 ]\n", + " [ 0.04015914 -0.04928622 0.00684531]\n", + " [ 0.12188289 0.01406341 -0.3047072 ]\n", + " [ 0.00140428 -0.00472522 0.00263777]]\n", + "jacrev result, with shape (4, 3)\n", + "[[ 0.05981756 0.12883782 0.088576 ]\n", + " [ 0.04015914 -0.04928622 0.00684531]\n", + " [ 0.12188289 0.01406341 -0.3047072 ]\n", + " [ 0.00140428 -0.00472522 0.00263777]]\n" + ] + } + ], + "source": [ + "from jax import jacfwd, jacrev\n", + "\n", + "# Isolate the function from the weight matrix to the predictions\n", + "f = lambda W: predict(W, b, inputs)\n", + "\n", + "J = jacfwd(f)(W)\n", + "print(\"jacfwd result, with shape\", J.shape)\n", + "print(J)\n", + "\n", + "J = jacrev(f)(W)\n", + "print(\"jacrev result, with shape\", J.shape)\n", + "print(J)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "iZDL-n_AvgBt" + }, + "source": [ + "These two functions compute the same values (up to machine numerics), but differ in their implementation: `jacfwd` uses forward-mode automatic differentiation, which is more efficient for \"tall\" Jacobian matrices (more outputs than inputs), while `jacrev` uses reverse-mode, which is more efficient for \"wide\" Jacobian matrices (more inputs than outputs). For matrices that are near-square, `jacfwd` probably has an edge over `jacrev`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "zeKlr7Xz8bfm" + }, + "source": [ + "You can also use `jacfwd` and `jacrev` with container types:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "id": "eH46Xnm88bfm", + "outputId": "ab1f5dce-926e-40b9-9664-5bd5e628e0b5" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Jacobian from W to logits is\n", + "[[ 0.05981756 0.12883782 0.088576 ]\n", + " [ 0.04015914 -0.04928622 0.00684531]\n", + " [ 0.12188289 0.01406341 -0.3047072 ]\n", + " [ 0.00140428 -0.00472522 0.00263777]]\n", + "Jacobian from b to logits is\n", + "[0.11503378 0.04563539 0.23439017 0.00189768]\n" + ] + } + ], + "source": [ + "def predict_dict(params, inputs):\n", + " return predict(params['W'], params['b'], inputs)\n", + "\n", + "J_dict = jacrev(predict_dict)({'W': W, 'b': b}, inputs)\n", + "for k, v in J_dict.items():\n", + " print(\"Jacobian from {} to logits is\".format(k))\n", + " print(v)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "yH34zjV88bfp" + }, + "source": [ + "For more details on forward- and reverse-mode, as well as how to implement `jacfwd` and `jacrev` as efficiently as possible, read on!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "K6Mpw_7K8bfp" + }, + "source": [ + "Using a composition of two of these functions gives us a way to compute dense Hessian matrices:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "id": "n155ypD9rfIZ", + "outputId": "69622bc4-9a8d-47f1-aab6-40ab21d450d9" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "hessian, with shape (4, 3, 3)\n", + "[[[ 0.02285465 0.0492254 0.03384246]\n", + " [ 0.0492254 0.10602394 0.07289147]\n", + " [ 0.03384246 0.07289146 0.05011288]]\n", + "\n", + " [[-0.03195214 0.03921399 -0.00544639]\n", + " [ 0.03921399 -0.04812626 0.0066842 ]\n", + " [-0.00544639 0.0066842 -0.00092836]]\n", + "\n", + " [[-0.01583708 -0.00182736 0.03959271]\n", + " [-0.00182736 -0.00021085 0.00456839]\n", + " [ 0.03959271 0.00456839 -0.09898177]]\n", + "\n", + " [[-0.00103522 0.00348336 -0.00194453]\n", + " [ 0.00348336 -0.01172105 0.00654308]\n", + " [-0.00194453 0.00654308 -0.00365256]]]\n" + ] + } + ], + "source": [ + "def hessian(f):\n", + " return jacfwd(jacrev(f))\n", + "\n", + "H = hessian(f)(W)\n", + "print(\"hessian, with shape\", H.shape)\n", + "print(H)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "wvkk82R6uRoM" + }, + "source": [ + "This shape makes sense: if we start with a function $f : \\mathbb{R}^n \\to \\mathbb{R}^m$, then at a point $x \\in \\mathbb{R}^n$ we expect to get the shapes\n", + "\n", + "* $f(x) \\in \\mathbb{R}^m$, the value of $f$ at $x$,\n", + "* $\\partial f(x) \\in \\mathbb{R}^{m \\times n}$, the Jacobian matrix at $x$,\n", + "* $\\partial^2 f(x) \\in \\mathbb{R}^{m \\times n \\times n}$, the Hessian at $x$,\n", + "\n", + "and so on.\n", + "\n", + "To implement `hessian`, we could have used `jacfwd(jacrev(f))` or `jacrev(jacfwd(f))` or any other composition of the two. But forward-over-reverse is typically the most efficient. That's because in the inner Jacobian computation we're often differentiating a function wide Jacobian (maybe like a loss function $f : \\mathbb{R}^n \\to \\mathbb{R}$), while in the outer Jacobian computation we're differentiating a function with a square Jacobian (since $\\nabla f : \\mathbb{R}^n \\to \\mathbb{R}^n$), which is where forward-mode wins out." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "OMmi9cyhs1bj" + }, + "source": [ + "## How it's made: two foundational autodiff functions" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "mtSRvouV6vvG" + }, + "source": [ + "(jacobian-vector-product)=\n", + "\n", + "### Jacobian-Vector products (JVPs, aka forward-mode autodiff)\n", + "\n", + "JAX includes efficient and general implementations of both forward- and reverse-mode automatic differentiation. The familiar `grad` function is built on reverse-mode, but to explain the difference in the two modes, and when each can be useful, we need a bit of math background.\n", + "\n", + "#### JVPs in math\n", + "\n", + "Mathematically, given a function $f : \\mathbb{R}^n \\to \\mathbb{R}^m$, the Jacobian of $f$ evaluated at an input point $x \\in \\mathbb{R}^n$, denoted $\\partial f(x)$, is often thought of as a matrix in $\\mathbb{R}^m \\times \\mathbb{R}^n$:\n", + "\n", + "$\\qquad \\partial f(x) \\in \\mathbb{R}^{m \\times n}$.\n", + "\n", + "But we can also think of $\\partial f(x)$ as a linear map, which maps the tangent space of the domain of $f$ at the point $x$ (which is just another copy of $\\mathbb{R}^n$) to the tangent space of the codomain of $f$ at the point $f(x)$ (a copy of $\\mathbb{R}^m$):\n", + "\n", + "$\\qquad \\partial f(x) : \\mathbb{R}^n \\to \\mathbb{R}^m$.\n", + "\n", + "This map is called the [pushforward map](https://en.wikipedia.org/wiki/Pushforward_(differential)) of $f$ at $x$. The Jacobian matrix is just the matrix for this linear map in a standard basis.\n", + "\n", + "If we don't commit to one specific input point $x$, then we can think of the function $\\partial f$ as first taking an input point and returning the Jacobian linear map at that input point:\n", + "\n", + "$\\qquad \\partial f : \\mathbb{R}^n \\to \\mathbb{R}^n \\to \\mathbb{R}^m$.\n", + "\n", + "In particular, we can uncurry things so that given input point $x \\in \\mathbb{R}^n$ and a tangent vector $v \\in \\mathbb{R}^n$, we get back an output tangent vector in $\\mathbb{R}^m$. We call that mapping, from $(x, v)$ pairs to output tangent vectors, the *Jacobian-vector product*, and write it as\n", + "\n", + "$\\qquad (x, v) \\mapsto \\partial f(x) v$\n", + "\n", + "#### JVPs in JAX code\n", + "\n", + "Back in Python code, JAX's `jvp` function models this transformation. Given a Python function that evaluates $f$, JAX's `jvp` is a way to get a Python function for evaluating $(x, v) \\mapsto (f(x), \\partial f(x) v)$." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "id": "pTncYR6F6vvG" + }, + "outputs": [], + "source": [ + "from jax import jvp\n", + "\n", + "# Isolate the function from the weight matrix to the predictions\n", + "f = lambda W: predict(W, b, inputs)\n", + "\n", + "key, subkey = random.split(key)\n", + "v = random.normal(subkey, W.shape)\n", + "\n", + "# Push forward the vector `v` along `f` evaluated at `W`\n", + "y, u = jvp(f, (W,), (v,))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "m1VJgJYQGfCK" + }, + "source": [ + "In terms of [Haskell-like type signatures](https://wiki.haskell.org/Type_signature),\n", + "we could write\n", + "\n", + "```haskell\n", + "jvp :: (a -> b) -> a -> T a -> (b, T b)\n", + "```\n", + "\n", + "where we use `T a` to denote the type of the tangent space for `a`. In words, `jvp` takes as arguments a function of type `a -> b`, a value of type `a`, and a tangent vector value of type `T a`. It gives back a pair consisting of a value of type `b` and an output tangent vector of type `T b`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "3RpbiasHGD3X" + }, + "source": [ + "The `jvp`-transformed function is evaluated much like the original function, but paired up with each primal value of type `a` it pushes along tangent values of type `T a`. For each primitive numerical operation that the original function would have applied, the `jvp`-transformed function executes a \"JVP rule\" for that primitive that both evaluates the primitive on the primals and applies the primitive's JVP at those primal values.\n", + "\n", + "That evaluation strategy has some immediate implications about computational complexity: since we evaluate JVPs as we go, we don't need to store anything for later, and so the memory cost is independent of the depth of the computation. In addition, the FLOP cost of the `jvp`-transformed function is about 3x the cost of just evaluating the function (one unit of work for evaluating the original function, for example `sin(x)`; one unit for linearizing, like `cos(x)`; and one unit for applying the linearized function to a vector, like `cos_x * v`). Put another way, for a fixed primal point $x$, we can evaluate $v \\mapsto \\partial f(x) \\cdot v$ for about the same marginal cost as evaluating $f$.\n", + "\n", + "That memory complexity sounds pretty compelling! So why don't we see forward-mode very often in machine learning?\n", + "\n", + "To answer that, first think about how you could use a JVP to build a full Jacobian matrix. If we apply a JVP to a one-hot tangent vector, it reveals one column of the Jacobian matrix, corresponding to the nonzero entry we fed in. So we can build a full Jacobian one column at a time, and to get each column costs about the same as one function evaluation. That will be efficient for functions with \"tall\" Jacobians, but inefficient for \"wide\" Jacobians.\n", + "\n", + "If you're doing gradient-based optimization in machine learning, you probably want to minimize a loss function from parameters in $\\mathbb{R}^n$ to a scalar loss value in $\\mathbb{R}$. That means the Jacobian of this function is a very wide matrix: $\\partial f(x) \\in \\mathbb{R}^{1 \\times n}$, which we often identify with the Gradient vector $\\nabla f(x) \\in \\mathbb{R}^n$. Building that matrix one column at a time, with each call taking a similar number of FLOPs to evaluate the original function, sure seems inefficient! In particular, for training neural networks, where $f$ is a training loss function and $n$ can be in the millions or billions, this approach just won't scale.\n", + "\n", + "To do better for functions like this, we just need to use reverse-mode." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PhkvkZazdXu1" + }, + "source": [ + "(vector-jacobian-product)=\n", + "\n", + "### Vector-Jacobian products (VJPs, aka reverse-mode autodiff)\n", + "\n", + "Where forward-mode gives us back a function for evaluating Jacobian-vector products, which we can then use to build Jacobian matrices one column at a time, reverse-mode is a way to get back a function for evaluating vector-Jacobian products (equivalently Jacobian-transpose-vector products), which we can use to build Jacobian matrices one row at a time.\n", + "\n", + "#### VJPs in math\n", + "\n", + "Let's again consider a function $f : \\mathbb{R}^n \\to \\mathbb{R}^m$.\n", + "Starting from our notation for JVPs, the notation for VJPs is pretty simple:\n", + "\n", + "$\\qquad (x, v) \\mapsto v \\partial f(x)$,\n", + "\n", + "where $v$ is an element of the cotangent space of $f$ at $x$ (isomorphic to another copy of $\\mathbb{R}^m$). When being rigorous, we should think of $v$ as a linear map $v : \\mathbb{R}^m \\to \\mathbb{R}$, and when we write $v \\partial f(x)$ we mean function composition $v \\circ \\partial f(x)$, where the types work out because $\\partial f(x) : \\mathbb{R}^n \\to \\mathbb{R}^m$. But in the common case we can identify $v$ with a vector in $\\mathbb{R}^m$ and use the two almost interchangeably, just like we might sometimes flip between \"column vectors\" and \"row vectors\" without much comment.\n", + "\n", + "With that identification, we can alternatively think of the linear part of a VJP as the transpose (or adjoint conjugate) of the linear part of a JVP:\n", + "\n", + "$\\qquad (x, v) \\mapsto \\partial f(x)^\\mathsf{T} v$.\n", + "\n", + "For a given point $x$, we can write the signature as\n", + "\n", + "$\\qquad \\partial f(x)^\\mathsf{T} : \\mathbb{R}^m \\to \\mathbb{R}^n$.\n", + "\n", + "The corresponding map on cotangent spaces is often called the [pullback](https://en.wikipedia.org/wiki/Pullback_(differential_geometry))\n", + "of $f$ at $x$. The key for our purposes is that it goes from something that looks like the output of $f$ to something that looks like the input of $f$, just like we might expect from a transposed linear function.\n", + "\n", + "#### VJPs in JAX code\n", + "\n", + "Switching from math back to Python, the JAX function `vjp` can take a Python function for evaluating $f$ and give us back a Python function for evaluating the VJP $(x, v) \\mapsto (f(x), v^\\mathsf{T} \\partial f(x))$." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "id": "1tFcRuEzkGRR" + }, + "outputs": [], + "source": [ + "from jax import vjp\n", + "\n", + "# Isolate the function from the weight matrix to the predictions\n", + "f = lambda W: predict(W, b, inputs)\n", + "\n", + "y, vjp_fun = vjp(f, W)\n", + "\n", + "key, subkey = random.split(key)\n", + "u = random.normal(subkey, y.shape)\n", + "\n", + "# Pull back the covector `u` along `f` evaluated at `W`\n", + "v = vjp_fun(u)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "oVOZexCEkvv3" + }, + "source": [ + "In terms of [Haskell-like type signatures](https://wiki.haskell.org/Type_signature),\n", + "we could write\n", + "\n", + "```haskell\n", + "vjp :: (a -> b) -> a -> (b, CT b -> CT a)\n", + "```\n", + "\n", + "where we use `CT a` to denote the type for the cotangent space for `a`. In words, `vjp` takes as arguments a function of type `a -> b` and a point of type `a`, and gives back a pair consisting of a value of type `b` and a linear map of type `CT b -> CT a`.\n", + "\n", + "This is great because it lets us build Jacobian matrices one row at a time, and the FLOP cost for evaluating $(x, v) \\mapsto (f(x), v^\\mathsf{T} \\partial f(x))$ is only about three times the cost of evaluating $f$. In particular, if we want the gradient of a function $f : \\mathbb{R}^n \\to \\mathbb{R}$, we can do it in just one call. That's how `grad` is efficient for gradient-based optimization, even for objectives like neural network training loss functions on millions or billions of parameters.\n", + "\n", + "There's a cost, though: though the FLOPs are friendly, memory scales with the depth of the computation. Also, the implementation is traditionally more complex than that of forward-mode, though JAX has some tricks up its sleeve (that's a story for a future notebook!).\n", + "\n", + "For more on how reverse-mode works, see [this tutorial video from the Deep Learning Summer School in 2017](http://videolectures.net/deeplearning2017_johnson_automatic_differentiation/)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Vector-valued gradients with VJPs\n", + "\n", + "If you're interested in taking vector-valued gradients (like `tf.gradients`):" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[6. 6.]\n", + " [6. 6.]]\n" + ] + } + ], + "source": [ + "from jax import vjp\n", + "\n", + "def vgrad(f, x):\n", + " y, vjp_fn = vjp(f, x)\n", + " return vjp_fn(jnp.ones(y.shape))[0]\n", + "\n", + "print(vgrad(lambda x: 3*x**2, jnp.ones((2, 2))))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "MWHcAPqLdJFn" + }, + "source": [ + "### Hessian-vector products using both forward- and reverse-mode" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "YG3g5C3KdW7H" + }, + "source": [ + "In a previous section, we implemented a Hessian-vector product function just using reverse-mode (assuming continuous second derivatives):" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "id": "C70CA-7wdelL" + }, + "outputs": [], + "source": [ + "def hvp(f, x, v):\n", + " return grad(lambda x: jnp.vdot(grad(f)(x), v))(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "zJlJbFKCdfd0" + }, + "source": [ + "That's efficient, but we can do even better and save some memory by using forward-mode together with reverse-mode.\n", + "\n", + "Mathematically, given a function $f : \\mathbb{R}^n \\to \\mathbb{R}$ to differentiate, a point $x \\in \\mathbb{R}^n$ at which to linearize the function, and a vector $v \\in \\mathbb{R}^n$, the Hessian-vector product function we want is\n", + "\n", + "$(x, v) \\mapsto \\partial^2 f(x) v$\n", + "\n", + "Consider the helper function $g : \\mathbb{R}^n \\to \\mathbb{R}^n$ defined to be the derivative (or gradient) of $f$, namely $g(x) = \\partial f(x)$. All we need is its JVP, since that will give us\n", + "\n", + "$(x, v) \\mapsto \\partial g(x) v = \\partial^2 f(x) v$.\n", + "\n", + "We can translate that almost directly into code:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "id": "rq3C0reVfAaI" + }, + "outputs": [], + "source": [ + "from jax import jvp, grad\n", + "\n", + "# forward-over-reverse\n", + "def hvp(f, primals, tangents):\n", + " return jvp(grad(f), primals, tangents)[1]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "XUsye1SwfSFm" + }, + "source": [ + "Even better, since we didn't have to call `jnp.dot` directly, this `hvp` function works with arrays of any shape and with arbitrary container types (like vectors stored as nested lists/dicts/tuples), and doesn't even have a dependence on `jax.numpy`.\n", + "\n", + "Here's an example of how to use it:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "id": "bmpuQa5_f1Al", + "outputId": "20ef2514-0ab7-4071-c2f4-77b59b013ffc" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "def f(X):\n", + " return jnp.sum(jnp.tanh(X)**2)\n", + "\n", + "key, subkey1, subkey2 = random.split(key, 3)\n", + "X = random.normal(subkey1, (30, 40))\n", + "V = random.normal(subkey2, (30, 40))\n", + "\n", + "ans1 = hvp(f, (X,), (V,))\n", + "ans2 = jnp.tensordot(hessian(f)(X), V, 2)\n", + "\n", + "print(jnp.allclose(ans1, ans2, 1e-4, 1e-4))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "aWTii5TyXL5C" + }, + "source": [ + "Another way you might consider writing this is using reverse-over-forward:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "id": "YxwmXZH2XQrw" + }, + "outputs": [], + "source": [ + "# reverse-over-forward\n", + "def hvp_revfwd(f, primals, tangents):\n", + " g = lambda primals: jvp(f, primals, tangents)[1]\n", + " return grad(g)(primals)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "8z-QG_xTXR4I" + }, + "source": [ + "That's not quite as good, though, because forward-mode has less overhead than reverse-mode, and since the outer differentiation operator here has to differentiate a larger computation than the inner one, keeping forward-mode on the outside works best:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "id": "lxfv25qTX5gZ", + "outputId": "b88dae03-7bd1-4836-f994-880c57bc4714" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Forward over reverse\n", + "10 loops, best of 3: 6.75 ms per loop\n", + "Reverse over forward\n", + "10 loops, best of 3: 8.4 ms per loop\n", + "Reverse over reverse\n", + "10 loops, best of 3: 9.98 ms per loop\n", + "Naive full Hessian materialization\n", + "10 loops, best of 3: 15.9 ms per loop\n" + ] + } + ], + "source": [ + "# reverse-over-reverse, only works for single arguments\n", + "def hvp_revrev(f, primals, tangents):\n", + " x, = primals\n", + " v, = tangents\n", + " return grad(lambda x: jnp.vdot(grad(f)(x), v))(x)\n", + "\n", + "\n", + "print(\"Forward over reverse\")\n", + "%timeit -n10 -r3 hvp(f, (X,), (V,))\n", + "print(\"Reverse over forward\")\n", + "%timeit -n10 -r3 hvp_revfwd(f, (X,), (V,))\n", + "print(\"Reverse over reverse\")\n", + "%timeit -n10 -r3 hvp_revrev(f, (X,), (V,))\n", + "\n", + "print(\"Naive full Hessian materialization\")\n", + "%timeit -n10 -r3 jnp.tensordot(hessian(f)(X), V, 2)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "xtqSUJgzwQXO" + }, + "source": [ + "## Composing VJPs, JVPs, and `vmap`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PSL1TciM6vvI" + }, + "source": [ + "### Jacobian-Matrix and Matrix-Jacobian products\n", + "\n", + "Now that we have `jvp` and `vjp` transformations that give us functions to push-forward or pull-back single vectors at a time, we can use JAX's `vmap` [transformation](https://github.com/jax-ml/jax#auto-vectorization-with-vmap) to push and pull entire bases at once. In particular, we can use that to write fast matrix-Jacobian and Jacobian-matrix products." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "id": "asAWvxVaCmsx", + "outputId": "05d3b5f9-f526-42a4-ea2b-6163b267db26" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Non-vmapped Matrix-Jacobian product\n", + "10 loops, best of 3: 291 ms per loop\n", + "\n", + "Vmapped Matrix-Jacobian product\n", + "10 loops, best of 3: 6.85 ms per loop\n" + ] + } + ], + "source": [ + "# Isolate the function from the weight matrix to the predictions\n", + "f = lambda W: predict(W, b, inputs)\n", + "\n", + "# Pull back the covectors `m_i` along `f`, evaluated at `W`, for all `i`.\n", + "# First, use a list comprehension to loop over rows in the matrix M.\n", + "def loop_mjp(f, x, M):\n", + " y, vjp_fun = vjp(f, x)\n", + " return jnp.vstack([jnp.asarray(vjp_fun(mi)) for mi in M])\n", + "\n", + "# Now, use vmap to build a computation that does a single fast matrix-matrix\n", + "# multiply, rather than an outer loop over vector-matrix multiplies.\n", + "def vmap_mjp(f, x, M):\n", + " y, vjp_fun = vjp(f, x)\n", + " outs, = vmap(vjp_fun)(M)\n", + " return outs\n", + "\n", + "key = random.key(0)\n", + "num_covecs = 128\n", + "U = random.normal(key, (num_covecs,) + y.shape)\n", + "\n", + "loop_vs = loop_mjp(f, W, M=U)\n", + "print('Non-vmapped Matrix-Jacobian product')\n", + "%timeit -n10 -r3 loop_mjp(f, W, M=U)\n", + "\n", + "print('\\nVmapped Matrix-Jacobian product')\n", + "vmap_vs = vmap_mjp(f, W, M=U)\n", + "%timeit -n10 -r3 vmap_mjp(f, W, M=U)\n", + "\n", + "assert jnp.allclose(loop_vs, vmap_vs), 'Vmap and non-vmapped Matrix-Jacobian Products should be identical'" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "id": "TDaxsJrlDraK", + "outputId": "99a7591c-643d-4b91-c0fc-c7a3c73b0de6" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Non-vmapped Jacobian-Matrix product\n", + "10 loops, best of 3: 693 ms per loop\n", + "\n", + "Vmapped Jacobian-Matrix product\n", + "10 loops, best of 3: 5.97 ms per loop\n" + ] + } + ], + "source": [ + "def loop_jmp(f, W, M):\n", + " # jvp immediately returns the primal and tangent values as a tuple,\n", + " # so we'll compute and select the tangents in a list comprehension\n", + " return jnp.vstack([jvp(f, (W,), (mi,))[1] for mi in M])\n", + "\n", + "def vmap_jmp(f, W, M):\n", + " _jvp = lambda s: jvp(f, (W,), (s,))[1]\n", + " return vmap(_jvp)(M)\n", + "\n", + "num_vecs = 128\n", + "S = random.normal(key, (num_vecs,) + W.shape)\n", + "\n", + "loop_vs = loop_jmp(f, W, M=S)\n", + "print('Non-vmapped Jacobian-Matrix product')\n", + "%timeit -n10 -r3 loop_jmp(f, W, M=S)\n", + "vmap_vs = vmap_jmp(f, W, M=S)\n", + "print('\\nVmapped Jacobian-Matrix product')\n", + "%timeit -n10 -r3 vmap_jmp(f, W, M=S)\n", + "\n", + "assert jnp.allclose(loop_vs, vmap_vs), 'Vmap and non-vmapped Jacobian-Matrix products should be identical'" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "MXFEFBDz6vvL" + }, + "source": [ + "### The implementation of `jacfwd` and `jacrev`" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ZAgUb6sp8bf7" + }, + "source": [ + "Now that we've seen fast Jacobian-matrix and matrix-Jacobian products, it's not hard to guess how to write `jacfwd` and `jacrev`. We just use the same technique to push-forward or pull-back an entire standard basis (isomorphic to an identity matrix) at once." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "id": "HBEzsDH1U5_4" + }, + "outputs": [], + "source": [ + "from jax import jacrev as builtin_jacrev\n", + "\n", + "def our_jacrev(f):\n", + " def jacfun(x):\n", + " y, vjp_fun = vjp(f, x)\n", + " # Use vmap to do a matrix-Jacobian product.\n", + " # Here, the matrix is the Euclidean basis, so we get all\n", + " # entries in the Jacobian at once.\n", + " J, = vmap(vjp_fun, in_axes=0)(jnp.eye(len(y)))\n", + " return J\n", + " return jacfun\n", + "\n", + "assert jnp.allclose(builtin_jacrev(f)(W), our_jacrev(f)(W)), 'Incorrect reverse-mode Jacobian results!'" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "id": "Qd9gVZ5t6vvP" + }, + "outputs": [], + "source": [ + "from jax import jacfwd as builtin_jacfwd\n", + "\n", + "def our_jacfwd(f):\n", + " def jacfun(x):\n", + " _jvp = lambda s: jvp(f, (x,), (s,))[1]\n", + " Jt = vmap(_jvp, in_axes=1)(jnp.eye(len(x)))\n", + " return jnp.transpose(Jt)\n", + " return jacfun\n", + "\n", + "assert jnp.allclose(builtin_jacfwd(f)(W), our_jacfwd(f)(W)), 'Incorrect forward-mode Jacobian results!'" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "7r5_m9Y68bf_" + }, + "source": [ + "Interestingly, [Autograd](https://github.com/hips/autograd) couldn't do this. Our [implementation](https://github.com/HIPS/autograd/blob/96a03f44da43cd7044c61ac945c483955deba957/autograd/differential_operators.py#L60) of reverse-mode `jacobian` in Autograd had to pull back one vector at a time with an outer-loop `map`. Pushing one vector at a time through the computation is much less efficient than batching it all together with `vmap`." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "9maev0Nd8bf_" + }, + "source": [ + "Another thing that Autograd couldn't do is `jit`. Interestingly, no matter how much Python dynamism you use in your function to be differentiated, we could always use `jit` on the linear part of the computation. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "id": "_5jDflC08bgB", + "outputId": "7d37cca8-3954-40b9-bea8-937ac655387c" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(Array(3.1415927, dtype=float32),)\n" + ] + } + ], + "source": [ + "def f(x):\n", + " try:\n", + " if x < 3:\n", + " return 2 * x ** 3\n", + " else:\n", + " raise ValueError\n", + " except ValueError:\n", + " return jnp.pi * x\n", + "\n", + "y, f_vjp = vjp(f, 4.)\n", + "print(jit(f_vjp)(1.))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "3fPWLrxK8bgD" + }, + "source": [ + "## Complex numbers and differentiation" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "2pZOHvrm8bgE" + }, + "source": [ + "JAX is great at complex numbers and differentiation. To support both [holomorphic and non-holomorphic differentiation](https://en.wikipedia.org/wiki/Holomorphic_function), it helps to think in terms of JVPs and VJPs.\n", + "\n", + "Consider a complex-to-complex function $f: \\mathbb{C} \\to \\mathbb{C}$ and identify it with a corresponding function $g: \\mathbb{R}^2 \\to \\mathbb{R}^2$," + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "id": "OaqZ2MuP8bgF" + }, + "outputs": [], + "source": [ + "def f(z):\n", + " x, y = jnp.real(z), jnp.imag(z)\n", + " return u(x, y) + v(x, y) * 1j\n", + "\n", + "def g(x, y):\n", + " return (u(x, y), v(x, y))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "3XB5oGxl8bgH" + }, + "source": [ + "That is, we've decomposed $f(z) = u(x, y) + v(x, y) i$ where $z = x + y i$, and identified $\\mathbb{C}$ with $\\mathbb{R}^2$ to get $g$." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6fBBMxqpiVjF" + }, + "source": [ + "Since $g$ only involves real inputs and outputs, we already know how to write a Jacobian-vector product for it, say given a tangent vector $(c, d) \\in \\mathbb{R}^2$, namely\n", + "\n", + "$\\begin{bmatrix} \\partial_0 u(x, y) & \\partial_1 u(x, y) \\\\ \\partial_0 v(x, y) & \\partial_1 v(x, y) \\end{bmatrix}\n", + "\\begin{bmatrix} c \\\\ d \\end{bmatrix}$.\n", + "\n", + "To get a JVP for the original function $f$ applied to a tangent vector $c + di \\in \\mathbb{C}$, we just use the same definition and identify the result as another complex number, \n", + "\n", + "$\\partial f(x + y i)(c + d i) =\n", + "\\begin{matrix} \\begin{bmatrix} 1 & i \\end{bmatrix} \\\\ ~ \\end{matrix}\n", + "\\begin{bmatrix} \\partial_0 u(x, y) & \\partial_1 u(x, y) \\\\ \\partial_0 v(x, y) & \\partial_1 v(x, y) \\end{bmatrix}\n", + "\\begin{bmatrix} c \\\\ d \\end{bmatrix}$.\n", + "\n", + "That's our definition of the JVP of a $\\mathbb{C} \\to \\mathbb{C}$ function! Notice it doesn't matter whether or not $f$ is holomorphic: the JVP is unambiguous." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "6SL6dWtFpBUr" + }, + "source": [ + "Here's a check:" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "id": "BGZV__zupIMS" + }, + "outputs": [], + "source": [ + "def check(seed):\n", + " key = random.key(seed)\n", + "\n", + " # random coeffs for u and v\n", + " key, subkey = random.split(key)\n", + " a, b, c, d = random.uniform(subkey, (4,))\n", + "\n", + " def fun(z):\n", + " x, y = jnp.real(z), jnp.imag(z)\n", + " return u(x, y) + v(x, y) * 1j\n", + "\n", + " def u(x, y):\n", + " return a * x + b * y\n", + "\n", + " def v(x, y):\n", + " return c * x + d * y\n", + "\n", + " # primal point\n", + " key, subkey = random.split(key)\n", + " x, y = random.uniform(subkey, (2,))\n", + " z = x + y * 1j\n", + "\n", + " # tangent vector\n", + " key, subkey = random.split(key)\n", + " c, d = random.uniform(subkey, (2,))\n", + " z_dot = c + d * 1j\n", + "\n", + " # check jvp\n", + " _, ans = jvp(fun, (z,), (z_dot,))\n", + " expected = (grad(u, 0)(x, y) * c +\n", + " grad(u, 1)(x, y) * d +\n", + " grad(v, 0)(x, y) * c * 1j+\n", + " grad(v, 1)(x, y) * d * 1j)\n", + " print(jnp.allclose(ans, expected))" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "id": "I2OBU3OGp-CY", + "outputId": "28ae844b-0c25-4255-ca9b-598b0dbeb404" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "True\n", + "True\n" + ] + } + ], + "source": [ + "check(0)\n", + "check(1)\n", + "check(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "XjWMgDOimUcU" + }, + "source": [ + "What about VJPs? We do something pretty similar: for a cotangent vector $c + di \\in \\mathbb{C}$ we define the VJP of $f$ as\n", + "\n", + "$(c + di)^* \\; \\partial f(x + y i) =\n", + "\\begin{matrix} \\begin{bmatrix} c & -d \\end{bmatrix} \\\\ ~ \\end{matrix}\n", + "\\begin{bmatrix} \\partial_0 u(x, y) & \\partial_1 u(x, y) \\\\ \\partial_0 v(x, y) & \\partial_1 v(x, y) \\end{bmatrix}\n", + "\\begin{bmatrix} 1 \\\\ -i \\end{bmatrix}$.\n", + "\n", + "What's with the negatives? They're just to take care of complex conjugation, and the fact that we're working with covectors." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "oRu2VRjmtrgB" + }, + "source": [ + "Here's a check of the VJP rules:" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "id": "4J7edvIBttcU" + }, + "outputs": [], + "source": [ + "def check(seed):\n", + " key = random.key(seed)\n", + "\n", + " # random coeffs for u and v\n", + " key, subkey = random.split(key)\n", + " a, b, c, d = random.uniform(subkey, (4,))\n", + "\n", + " def fun(z):\n", + " x, y = jnp.real(z), jnp.imag(z)\n", + " return u(x, y) + v(x, y) * 1j\n", + "\n", + " def u(x, y):\n", + " return a * x + b * y\n", + "\n", + " def v(x, y):\n", + " return c * x + d * y\n", + "\n", + " # primal point\n", + " key, subkey = random.split(key)\n", + " x, y = random.uniform(subkey, (2,))\n", + " z = x + y * 1j\n", + "\n", + " # cotangent vector\n", + " key, subkey = random.split(key)\n", + " c, d = random.uniform(subkey, (2,))\n", + " z_bar = jnp.array(c + d * 1j) # for dtype control\n", + "\n", + " # check vjp\n", + " _, fun_vjp = vjp(fun, z)\n", + " ans, = fun_vjp(z_bar)\n", + " expected = (grad(u, 0)(x, y) * c +\n", + " grad(v, 0)(x, y) * (-d) +\n", + " grad(u, 1)(x, y) * c * (-1j) +\n", + " grad(v, 1)(x, y) * (-d) * (-1j))\n", + " assert jnp.allclose(ans, expected, atol=1e-5, rtol=1e-5)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "id": "RieNCdXgtzs7" + }, + "outputs": [], + "source": [ + "check(0)\n", + "check(1)\n", + "check(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "7I6A19Myt3qN" + }, + "source": [ + "What about convenience wrappers like `grad`, `jacfwd`, and `jacrev`?\n", + "\n", + "For $\\mathbb{R} \\to \\mathbb{R}$ functions, recall we defined `grad(f)(x)` as being `vjp(f, x)[1](1.0)`, which works because applying a VJP to a `1.0` value reveals the gradient (i.e. Jacobian, or derivative). We can do the same thing for $\\mathbb{C} \\to \\mathbb{R}$ functions: we can still use `1.0` as the cotangent vector, and we just get out a complex number result summarizing the full Jacobian:" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "id": "xz_9lK61wGdm", + "outputId": "96693583-2a36-48fd-d811-cd1a0f1a50c5" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Array(6.-8.j, dtype=complex64)" + ] + }, + "execution_count": 31, + "metadata": { + "tags": [] + }, + "output_type": "execute_result" + } + ], + "source": [ + "def f(z):\n", + " x, y = jnp.real(z), jnp.imag(z)\n", + " return x**2 + y**2\n", + "\n", + "z = 3. + 4j\n", + "grad(f)(z)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jqCvEE8qwGw7" + }, + "source": [ + "For general $\\mathbb{C} \\to \\mathbb{C}$ functions, the Jacobian has 4 real-valued degrees of freedom (as in the 2x2 Jacobian matrices above), so we can't hope to represent all of them within a complex number. But we can for holomorphic functions! A holomorphic function is precisely a $\\mathbb{C} \\to \\mathbb{C}$ function with the special property that its derivative can be represented as a single complex number. (The [Cauchy-Riemann equations](https://en.wikipedia.org/wiki/Cauchy%E2%80%93Riemann_equations) ensure that the above 2x2 Jacobians have the special form of a scale-and-rotate matrix in the complex plane, i.e. the action of a single complex number under multiplication.) And we can reveal that one complex number using a single call to `vjp` with a covector of `1.0`.\n", + "\n", + "Because this only works for holomorphic functions, to use this trick we need to promise JAX that our function is holomorphic; otherwise, JAX will raise an error when `grad` is used for a complex-output function:" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "id": "Y3n9hPVrwvXx", + "outputId": "20f72dfe-7083-47f8-b086-4a16426ba97b" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Array(-27.034945-3.8511531j, dtype=complex64)" + ] + }, + "execution_count": 32, + "metadata": { + "tags": [] + }, + "output_type": "execute_result" + } + ], + "source": [ + "def f(z):\n", + " return jnp.sin(z)\n", + "\n", + "z = 3. + 4j\n", + "grad(f, holomorphic=True)(z)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "LjIbDxX-w9Qf" + }, + "source": [ + "All the `holomorphic=True` promise does is disable the error when the output is complex-valued. We can still write `holomorphic=True` when the function isn't holomorphic, but the answer we get out won't represent the full Jacobian. Instead, it'll be the Jacobian of the function where we just discard the imaginary part of the output:" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "id": "th9xhwp2xaeU", + "outputId": "2dfebe3a-bbfe-46a1-b282-f5d59d53c772" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Array(1.-0.j, dtype=complex64)" + ] + }, + "execution_count": 33, + "metadata": { + "tags": [] + }, + "output_type": "execute_result" + } + ], + "source": [ + "def f(z):\n", + " return jnp.conjugate(z)\n", + "\n", + "z = 3. + 4j\n", + "grad(f, holomorphic=True)(z) # f is not actually holomorphic!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "R8ytpfeXyBu2" + }, + "source": [ + "There are some useful upshots for how `grad` works here:\n", + "\n", + "1. We can use `grad` on holomorphic $\\mathbb{C} \\to \\mathbb{C}$ functions.\n", + "2. We can use `grad` to optimize $f : \\mathbb{C} \\to \\mathbb{R}$ functions, like real-valued loss functions of complex parameters `x`, by taking steps in the direction of the conjugate of `grad(f)(x)`.\n", + "3. If we have an $\\mathbb{R} \\to \\mathbb{R}$ function that just happens to use some complex-valued operations internally (some of which must be non-holomorphic, e.g. FFTs used in convolutions) then `grad` still works and we get the same result that an implementation using only real values would have given.\n", + "\n", + "In any case, JVPs and VJPs are always unambiguous. And if we wanted to compute the full Jacobian matrix of a non-holomorphic $\\mathbb{C} \\to \\mathbb{C}$ function, we can do it with JVPs or VJPs!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "qmXkI37T8bgL" + }, + "source": [ + "You should expect complex numbers to work everywhere in JAX. Here's differentiating through a Cholesky decomposition of a complex matrix:" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "id": "WrDHHfKI8bgM", + "outputId": "c04baa8a-2408-4a76-e3dc-4522782d1bc5" + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Array([[-0.75342447 +0.j , -3.0509021 -10.940544j ,\n", + " 5.989684 +3.5422976j],\n", + " [-3.0509021 +10.940544j , -8.904487 +0.j ,\n", + " -5.1351547 -6.5593696j],\n", + " [ 5.989684 -3.5422976j, -5.1351547 +6.5593696j,\n", + " 0.01320434 +0.j ]], dtype=complex64)" + ] + }, + "execution_count": 34, + "metadata": { + "tags": [] + }, + "output_type": "execute_result" + } + ], + "source": [ + "A = jnp.array([[5., 2.+3j, 5j],\n", + " [2.-3j, 7., 1.+7j],\n", + " [-5j, 1.-7j, 12.]])\n", + "\n", + "def f(X):\n", + " L = jnp.linalg.cholesky(X)\n", + " return jnp.sum((L - jnp.sin(L))**2)\n", + "\n", + "grad(f, holomorphic=True)(A)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "Pgr2A60q9gl1" + }, + "source": [ + "## More advanced autodiff\n", + "\n", + "In this notebook, we worked through some easy, and then progressively more complicated, applications of automatic differentiation in JAX. We hope you now feel that taking derivatives in JAX is easy and powerful. For more details, check out the [\"Advanced automatic differentiation\" section in the JAX advanced guides](https://jax.readthedocs.io/en/latest/advanced_guides.html).\n", + "\n", + "There's a whole world of other autodiff tricks and functionality out there. Topics we didn't cover, but hope to in an \"Advanced Autodiff Cookbook\" include:\n", + "\n", + " - Gauss-Newton Vector Products, linearizing once\n", + " - Custom VJPs and JVPs\n", + " - Efficient derivatives at fixed-points\n", + " - Estimating the trace of a Hessian using random Hessian-vector products.\n", + " - Forward-mode autodiff using only reverse-mode autodiff.\n", + " - Taking derivatives with respect to custom data types.\n", + " - Checkpointing (binomial checkpointing for efficient reverse-mode, not model snapshotting).\n", + " - Optimizing VJPs with Jacobian pre-accumulation." + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "collapsed_sections": [], + "name": "Autodiff Cookbook.ipynb", + "provenance": [] + }, + "jupytext": { + "formats": "ipynb,md:myst" + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/jupyter/math/chapter02_definitions_586622.ipynb b/jupyter/math/chapter02_definitions_586622.ipynb new file mode 100644 index 0000000..360fa10 --- /dev/null +++ b/jupyter/math/chapter02_definitions_586622.ipynb @@ -0,0 +1,1211 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 2/ Definitions" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# helper code needed for running in colab\n", + "if 'google.colab' in str(get_ipython()):\n", + " print('Downloading plot_helpers.py to util/ (only neded for colab')\n", + " !mkdir util; wget https://raw.githubusercontent.com/minireference/noBSLAnotebooks/master/util/plot_helpers.py -P util" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# setup SymPy\n", + "from sympy import *\n", + "x, y, z, t = symbols('x y z t')\n", + "init_printing()\n", + "\n", + "# setup plotting\n", + "%matplotlib inline\n", + "import matplotlib.pyplot as mpl\n", + "from util.plot_helpers import plot_vec, plot_vecs, autoscale_arrows" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## SymPy Matrix objects" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAABoAAABLCAYAAABumJecAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADI0lEQVRYCe2Z0U0cMRCGlyjP0YVIKWDpgEAHlw5CC9BBUJ7uXkkHkBKgAyghpAMoIA8oSgX5v2W9mrO96/GC8rQjWbbH4/+3x7Pe2bu9zWZz2DTNvUpObrbb7UluINbJ7kG6NtbT19jeWzPwXW2MrTzaTqF9kRn/LN0X9JboUsw1wDu4mnu1o1BHOlQJEcqiaDKuvlb5pPaf4oTewO5odI4AVxr8ofKkcqSSPQvpR8VLxMq7oBDpV7XZVZW8qbJ+gfFCNNt5i+sW1w0emBMMH/rZ+wOKo+G6gsDR1cNFiqyfq+ZaOm77W9XJzd3bDFUNkesFOCBHjTmuiyB83YXI56eM1eK6jFN8qsV1Pj9lrGquoFbzz3sMcjtyvHPdc7963WTlIhIYJKTM5NKdqE2ufY9O5a5Xj1beYAD0zKIInN2RWIZb3Q4nbS8Rr4YHgZMaW2EnK+nZ8aR4iQB8FCA7yEm8gMTGe0Zj76IuB9cCigHh3VGyQoFDgstCJCY2VjGbSCAEAZ+efCkWZRaRwC+FzJmNuTQhhuhdrw11YmQVAj9Vf1/18EzZ8aj9MfQh+tt3Qh3GklrgfI8e2J2o3VIS42fF76B3u05gHP6x6vjwIX8KgGO1N7xZMYd/JyLOx8paumJAuIiEeqsCGecTS/EZYoKLSCs+iNFr++4zqgWO7Rei2CPu/uI6t6tiw8V1sUfcfdcVBJquoVZVSLlIRuhfSF/M6WTnvusAJisNRBDzeuCL/ETlBrAp8QYDt/ZpDx7wwk6+BcVU7SXiVUBOR+lEpEM76KZq1xkJlNW/t0Bmd/GL0JoNbe+Ohgk0RLJW1eXjahd/NWGOa0cYIgIlb4DkWAV3/lRxSS0R4N2rW6REHZ8trxp1yapFQEgTEPz4tEoMIoXrjAR0SInm0g2uw52T4iISAn/74KbiysfYvGeEi8jpqK0c9Z3w8NqxnbaXKM5OG5ESDOzwLLOAHRI6LiIBXamsVezD2Wq+60PZTYShSHBP0UXY5sQbDLm5VbqFqMpd1vi/uc6GN7+M2EXQfpU/fAGCiF/jh1wApZGa/2Vzf/gOUP8Ao0zTbH0f7jQAAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}1\\\\2\\\\3\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡1⎤\n", + "⎢ ⎥\n", + "⎢2⎥\n", + "⎢ ⎥\n", + "⎣3⎦" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "v = Matrix([1,2,3])\n", + "v" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# define symbolically\n", + "v_1, v_2, v_3 = symbols('v_1 v_2 v_3')\n", + "v = Matrix([v_1,v_2,v_3])" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAACMAAABLCAYAAAD6fj5uAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADxElEQVRoBe2a3W0UMRDHN4hnxIdEAUcHBCrIpgM+KkjSAVGeLm+n0EEogaQDRAWEdJDwjpQIUQH/n2UfXp+9tu9W6CQ8kmN7bM/8d2bs9WRvZz6fv+y67rtKjC5PT0/fxgbW4UnWjdbNYms1tvPQG/ioNpN9uvU7E7TPIjL2xXsD3wdzLnRTKx/olvxPA4Y64sEyYB7Q2hZqYFKeaJZJWcbfTak5RPxjDR6qPFO5UX+5K9TmODhWfal6Iyp104mUcQ59UwnPiqfivd8IhV2cBSMQnNCAgDigwrPoIMJjbjWVuOlWgK6t5HeqF4GWATjNxaXMO1J7N5g72s2CkcBfSFDNKYmiZbzAF/Uaw4XMwYo9bRFzqygLxpNmXCSFBpzHJ6gNaQwLXqs2x7tlF1fZmPEkzVDk9Tur9NznbdKuAQMQABkSENoz1YOYscNrVcVuklLOEt7sF9L0BW1qm1hZS3NkUTEYq/woImMyVo2bJlOaErRVYKrclHoix1cMEdS4slchuHl13JXG1tRg2FnHKmvRVrmpgUn5sFmmWSZlgRS/xUyzTMoCKX7Ru0kvOi7X/1cSl7WMrFKSxL3G9NaCJ9YNM1sfiB9mFHZoWGXBaHpNEncmxcurqdpkDvy/8MVQbbzHOfPIDrl6MNM9leqxJM4l/Yea13sCuFxxycK6KXruBgDz23Zc7cbCOpvEaQFWuQoXZvo/3XiJm9xcYmA0iZMFwtQXcL6bnaxojWVKqSqJs67BtcXJf7FlJLw4idNcrEi87KpdtJOwSDEYJkvwcqfQj5EFAnBijDUAo86mwVVgEDpGVjHbGTBuB/EARRnDpGCklDOFV8fgW4SAZS2qNXVuYsEYSemTsfHcWM1uysnaeLyBSZmwWaZZJmWBFL/FTLNMygIp/lbFTNFbWy/AlsStuNNeknJf4lwSN5OAXuVehTb8hWQMLvLiRanETf7tPvcljnsv802WoPqD+l9Viu45WTASaC7UqseSOPd1ZRE8Mh/GsFIRZcF4UrJJnACH7uABsFYR1YAhBgbKrLVWvsSJj3v4vMz3qTCxSwKrOWcAAiBDUkI7+iVOY7htT2XfAjNrcn+KwUgo6caV6gsV/nHUq3axsqJHY8Qaa/jPhEtbVub5jBo3dRKaTDk0xsH4Q2VPbedOE/zivVJxPDXjVGyZ+PK/XAFA8b2Knzn26sP/rJKlKstkpXUdPxbjdxN3di6HXnG+PSkY656sO1IPNZmbUgpq+FsFxncTP9IJH+Sf/WgQxYAh+lNb1t8ZzN+URl8NfwAI3D0r8G1ylQAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}v_{1}\\\\v_{2}\\\\v_{3}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡v₁⎤\n", + "⎢ ⎥\n", + "⎢v₂⎥\n", + "⎢ ⎥\n", + "⎣v₃⎦" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "v" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAG0AAAAZCAYAAAA7S6CBAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADB0lEQVRoBe2a61HcMBSFDZMCktAB6QCSCgId5FEB0EF2+LX7jyEdkA5C0gFJBQl0AKkAhhLyHa3kkRRb9pLYVljdGe3V49o6vke6kuXdmM/nX6qq2iE52V8sFjeuUPS0HoCLDyA48lDMNiDtkoZdr7JkM/UAPB0K2mam+AqshAcKaQnn5NpUSMuVmQSuQlrCObk2FdJyZSaBq5CWcE6uTU/agLG9fEqbtphbpGvKn5wt+WvyM/RXVze2Xmd8qZl2jGM+QsYP0mlEynPK76O6sYtri6+RNMjSCYnIkuyT4hOSg4Y62Y4i646vLTze4Jgry8A79EnERkAitgqlsjsiP8bpSm98Ftuxxb9t9QH19zY/hFoFnzDtke5Iyr8inYDP+Z9iKI2kuQdCv8FchNTrmb18jzaFzgqtWalOJbIdXOjTOBzdiQ8wp9jVZ3fkz6i7JL0YCuiq+MAhko2P0Tpr/E561oavMTx6xiY0OhBevTYnRmi7IonAYPbZ5qFVJz4AHILPDSrh0fq8TZ1/SK76IaQPPkWxz17n8q1mXas0zjTPWtM1mKY8rEa3RmsO0gefZtnPicB24sOfgX/BKf/GG78AfhdpumE9SulAIDRKJ9vqB+iXAyqJD6xxaBeJ/poT3fKfFnv7D5wKi9qRnzVgDkB1fprhBppV2uJf6Mq2G1JvRgh6sLVC/cdCf73w6TpsFRL1/XCX/JAbEXVnZEV82hMI3wXXmT3D8i7LX+rMp5mumVZhWC/i/g1yyffFh52ihMLOaITJR33xWdt77Gfk9Y3zGykOnTKrOkkzVv/5Dw8vwnSCo41BZcvSU2yeam/Sv2bWL9Jr8o4gFwFeUu/q6muU2QxKj7CAM0SYQqjWih0l8hrNd6RJBSwiSDj8waM1WvXnpEb565lmnaIQqs60SVEIukX/EZMbEQxfqXcyjWjpWsCXS9h/Cygdyd1acHq5Tobwzo1I/ZQlM7kHILb8R2RyFh4I4NGvaQ/0S9aXmTWNaafvY07K/x6dJzLQcKOXbrf+6n159hs0bjopOPMMlwAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}v_{1} & v_{2} & v_{3}\\end{matrix}\\right]$" + ], + "text/plain": [ + "[v₁ v₂ v₃]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "v.T" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAADkAAABLCAYAAADK8i9PAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAFr0lEQVR4Ae2cUZLUNhCGTSrP1GZTlXeGGwB7giw3gCMAN4Dap923FNwAOEECNwg3IHAD4D1V2VA5Qf7PuI3saVntmfFiF+4qreSW3K1f3ZJa8tReOz8/v1VV1Tslj15fXFzc9yrmxFMfP6g/G69Pqrv2Y1LxTGUap/QxfZhx+anTt7vi3YOfgnwu1LMDpT5hoVOlP1T+TKf7JP4LhwdrC2S/nfssgbj3K6XbOaXui7sz0fecJH2elM/i/+RVGC+1pPG2cgk5EvOl0qXSHSXX/8Wfgk4k9I2S52VY+ElJaRQkblIvQAL8WGVG98pIOplfHRKvHmjlrzsVzkMIpPPeVbLeZpQ9FcDQyv9DRsBs2J6lxGM1/S3aydmD7AMRQNz0lvL3/brc8+JACghW9PbFHMZqUSAbK54qZ7UN06JACtUjJW8rGQS8NJBEMOzVo2gxIOWiBCQbJTe0G0K9GJACQaQFXYklf/6iqzpu8qvKsCQ02pLhiEfuQlAOES9Cr8RjEfhT+dYpoG5x2D/siwDMRUBZbWNAhkKorKY9K5oBHTxt5FQsaU7mMBT5K8jiEC2kwWrJhRiq2M3VksUhWkiD1ZILMVSxm9+FJceEdRsN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0SgRD7BQEWTUkmzGuOZRLXYefxh4bvIYgEEKWVISEOQJZPmGBpfwL012+ysQzHkCghsGqBlsvOd2RGoUZP/WvGqUY9lHpjyicIc2zL/+PslFN3r708cVHwIpYS+UiC7SjR/lk/8oQjpZzdkTz5TbdBl1MAiBZHikAJeczC3RkSPp3vKkXFuPH114vHcXw1tBLsZUhY6uliwM0GKq09WVX1P0O774f6YAIEAS+3XiQioaKsaF1vAb5xbHut34H3xJs/TIcA6oAAAAAElFTkSuQmCC", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}1 & 7\\\\2 & 8\\\\3 & 9\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡1 7⎤\n", + "⎢ ⎥\n", + "⎢2 8⎥\n", + "⎢ ⎥\n", + "⎣3 9⎦" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A = Matrix(\n", + " [ [1,7],\n", + " [2,8], \n", + " [3,9] ])\n", + "A" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "# define symbolically\n", + "a_11, a_12, a_21, a_22, a_31, a_32 = symbols('a_11 a_12 a_21 a_22 a_31 a_32')\n", + "A = Matrix([\n", + " [a_11, a_12],\n", + " [a_21, a_22], \n", + " [a_31, a_32]])" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAF4AAABLCAYAAAD5yTBGAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAGQ0lEQVR4Ae2dX47cRBCHZyOeUSASB5jcIGFPkM0NApyAzQ0S5Wn3LQo3SDhBQm4A3AByg4R3pEUrTsDvM92Dx/a0qz3lGY+olnps95/qqs/tmt52ZXJ2dXX1YLVa/a48lN5fX19/M1QRZWUC4vZRLdZDrVR39lmr4ged07idPrUv4ryKwKuB1o9V9oTyNvjXuhMBeoDWlCKxfNPtpzKKGvB3upVxfRgC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eHXPiDT7Jc7dhHxtN4NOMGQpeGipbJYUmx5zMAd7bhn1tNIGvAZEU2ivmpGa8OdqO2TBWb9HJHbwGLcacJKX5wr1Q7sXdWJQ+QJuiDRp/rH5URXfwAvtFaVTVs7IwR1yVZM1VZ7ChaKNFr9FVjUVItKknEODrmbn0CPAuGOuFBPh6Zi49ArwLxnohAb6emUuPAO+CsV5IgK9n5tIjwLtgrBcS4OuZufQI8C4Y64UE+HpmLj2qNsnSziIvNyKgaU/85hkv6GzjRkDTnsBzd9OMF3SiDKwBTWu15Sb9pcz5ufJLydj8wEKSR5TCUgOaijYk/YtBW7KtmEzgJaEqGEjtN9EGUvKZrn9VbvawdX0SAU0lG1TnEtAkOaOJ2bkVP5PuOjOjG2/zUmVvWxL5tQ9mf5PU7xQCmoo2yJCpAU2JwvaPOm8K2ycJsDmgCbDt/jonvIMn5mhpBht4dblX0JbV1QDNFAyU6cpYXMx3yvwT8m6QU2526KOLDQP2cCOqgrbujFmuQSYFNKkfYdyPlPn1Jm7C0dKcNkj2pKCtUfCJFvEz5wBUzut4Qvi+pExHwjl6SXXcNF5s82WEgsdM7jbIJr7j4FEdtGVyNQngUPDSVpna8V3wh/IjnWdfD3zS18q5rCk45Ie3DZIH9MlBW9YZb2KUjGMF0/alrOmB/84k5MiNLDYk6DzlfH89IOucJxvbTck0402S/mvEU/BCytykonMdN49iUpovI27IUgOaijZI70UGNOFOdroUgedpWHpA05gNEdCkm3iSydXHnySBIynd9vEf5Qa6asR/wNUlYrwWy53/ARciAI/P5ctuKLVXJ0P1UbabQHGb5B/5QGfZ7Ow8CgAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}a_{11} & a_{12}\\\\a_{21} & a_{22}\\\\a_{31} & a_{32}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡a₁₁ a₁₂⎤\n", + "⎢ ⎥\n", + "⎢a₂₁ a₂₂⎥\n", + "⎢ ⎥\n", + "⎣a₃₁ a₃₂⎦" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Vector operations" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAACUAAABLCAYAAAD3YE4pAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAD70lEQVRoBe2aUW4TMRCG04pnBELiAOkNKD1B0xsUOAHtDaj6lLxF5QaFE7RwA+AE0N6g5R2JCnEC/s/YW++uNztONigSHsmxPbbH//5je3d2szWdTp+NRqMrpZR8nM1mL1INq+hk80bjxykbatt6EDW8VZnOsdzGlQHLZwlbB9Idoo9BnQvlukDUMGiedzWFKtKhcqC2KW2aFFBWjxSmrEzFu69zjHbGIzUeKe0oXTV3j+ofpH+t/JfylcXqvlNNyDn2Sal2xkgP2MOhAHFFvaA0GSf+VzpLOODuXOn+B931fXX1ksV9twIWJn2pKeeNaScJ3UhjcDn9j1XebYxZWO0FJYNunShnciaqTmPpxl73OZ5FetilP8KYLOkFFVnjxgxrDqTXu9uCdIFJp/b1a+WuPbJhKvauqcgKrNQmV5315FgSgCOlbFYi+1UxB1TtZi0AuOi5UgC6I13MYjVJbiHHfScy/l4TcyT8VAIkC/hMujfKL5QGETMoz0LqgS+lWwlcjvtWmihn8EaCMrsv50rlanbqsdJEaRzWoXJuVb2yLlBsAjbGUrKR7iugrL4sTBWmrAxY+5U1VZiyMmDtZ7r36UbKY+7/HYz2MiWWsoNRz+ypd9fY5+awvheUDC4TjPLczvOUE5XPVeC9Ku8ieoVz6qHvFfLaIBl0EYryiRpYW73BqPoQbtE/CMEGD3uw3iVPQwOgfvtKyENbMzcHoxoIS9+aBnrqP0K7xX2hL2sjxHhBVwtGpbyEWaWKTd8RkPEyCOOTOUxZZalg1LuM8N38kiOHqexgVIBgl/W0C4PWqzeD8kZTgWdKN/KATpTj4lAnrzGeAmoGlRrcpdPEMMQxAKiw41hXpghnLaA0OWcSx0ftm48AVmeX2jplLaA0+ePOGQ0NObvPYG6YLgWUlcfCVGHKyoC1X1lThSkrA9Z+G7mmTDdk3WC545dgdKGr/UNa1pdRjRnL6ETpTonyntJc+mbgIXVbLO6LoxDrl1GeyxnnohrlfFD6omR6zuoFJYPugV85V87aqsIn6WABXe3LqOpzpVieqAJrJukFFVkxB6MC23QTIRbsmSQHFKw0J0sGo2FmgcNtr5T4x1HFcGjvyre7GhL6WmikSYhSFn4ZVR8+EO0rHXiACbNtVQ4oFx7JePgSCnNEvby4gJGLtnkX77EmGcu4EG6lulY6s/tkEOOpwLOmUz8W/nelfZWDuxmLxMz+1SR+c5hKDG+rPHh2Wuxudi7ALtsj2hozU+2hCzWwx/9j+ACO7CmZ3yesBZR3W3CdQ5XzM7j7cibv6ruRoGL33Yj2Jvh//udTAACKXdL1NiTeQfQfShbecv4AgulfUjAJnM4AAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}u_{1}\\\\u_{2}\\\\u_{3}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡u₁⎤\n", + "⎢ ⎥\n", + "⎢u₂⎥\n", + "⎢ ⎥\n", + "⎣u₃⎦" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "u_1, u_2, u_3 = symbols('u_1 u_2 u_3')\n", + "u = Matrix([u_1,u_2,u_3])\n", + "v_1, v_2, v_3 = symbols('v_1 v_2 v_3')\n", + "v = Matrix([v_1,v_2,v_3])\n", + "alpha = symbols('alpha')\n", + "\n", + "u" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAADIAAABLCAYAAAAyEtS4AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAFBElEQVRoBe2b3U0cMRDHjyjPERFSCjg6CEkFHB2QdAB0QMQTvKGkA6CCJHQAVECg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gHiTioWqHIBfV06A0RKcWdwOpIWJFBRaxcNbKYzQKTw21C5nHLqqZUzZitteyCtLHvNpL1FahanlareIq0se82kvUVqFqeVqt4irSx7zaRLY5Hsh0Y93PUBOucZWoyZf0GXY5F5B+iGAjoSP4rJfxRHw7GST1DSHtEKZgXoNMtLvqDDZflaiB8W8JEAnxJeiZMo1SKLCNAdBxqvqYx1kqgRiFaH1094rgE6zXMbaEw4yD9YgupysdG1NIEfNCv3fi5NHaBzQ2m+fTH7kS9ai28hXX1V2gjEdlxYgE7Ksz82xVuAqlI8lK94v+hho1XGj1TnzBx+QYc1OAywXOlrHslxyTMx4z7YFBdiLDYz3wiHLiWxiaMREsIyBOqq2nCMY7nSL3okqyY1rowvqS4aspEccLFgXEmmdgD+Ld5U3ilNX8j/BnIsifxNda1I19mJLOBHjeh7BHcKYH6kzNR4aqUMMqM2WInv6XFBiAsxOf7bGSDWpZxbGSQ5fzrhWjkKV7VdGiC+a93JvCHg/+IHlSgNEE6K6PFp65R0gtw9FlXmH7vUUeVyN6UeAAAAAElFTkSuQmCC", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}\\alpha u_{1}\\\\\\alpha u_{2}\\\\\\alpha u_{3}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡α⋅u₁⎤\n", + "⎢ ⎥\n", + "⎢α⋅u₂⎥\n", + "⎢ ⎥\n", + "⎣α⋅u₃⎦" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "alpha*u" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAFIAAABLCAYAAADj9dDIAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAGY0lEQVR4Ae2c243cNhSGx0aeA2cDpIB1B75U4HEHTlyB7Q5i+Gn3beF04KQCXzpIUkFsd2DnPYAXi1SQ/2NImeJwhpTmSKPB8gBcUoe3n78OKUo8szfO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v_{1}\\\\u_{2} + v_{2}\\\\u_{3} + v_{3}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡u₁ + v₁⎤\n", + "⎢ ⎥\n", + "⎢u₂ + v₂⎥\n", + "⎢ ⎥\n", + "⎣u₃ + v₃⎦" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "u+v" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAMQAAAAmCAYAAACbKjTiAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAGBUlEQVR4Ae2d2ZHUMBCGZ6kNYIEMIAOOCFgy4IiAJQO2eNs3CjIAIuDIAIiAIwSIAIoMlv8zkjXj8YwtSz7G7q4SkjVWt/pXt9SSvMXR5eXlKgddXFx8EJ8HOXgZD0NgLASOcwiWM5yIzy3lRzn4GQ9DYCwErmQSfCo+HzPxMjaGwGgI5HKIx9Lg3WhamGBDIBMCuRyCcOlHpj4ZG0NgNASSHUKOQLj0eTQNTLAhkBGBZIdQX54qccJkZAgcPAI5TpkIlyazQqgvnHg9dyNzw+VPVP/34EergwKGRwCtDRZJDiEBhEtT2zu8VL9YtQpS+bUK35Vu/q9Z3L+GRxjyRixSQ6aHkjW106Uz56gehpcq3FDdLV+xsNzwCAPeiEWqQ5zK0KZ2/8Dq8C1gsPiS4RFMoBGLziGTm3GnFi6t1K83Qf+iBAg/VT+5vlb62cuj4RFgbYNFygqx8zJOgv1mNvSmp9I+WfqNMInvq273JL6R7b7+NTaOfKFJluERAN2FRYpDYGi7TpeeSiAb7iGoVpYzDvYPt1Ue84Sptn89AbNTluEREN+HRaeQyTEkDBnT0IKGlZLr37ny+/zknsl/Vl5dxKPT3/AItrATi04OIb6sDpO8jHODz1ErSvuTJfYR50qLI8MjDHkbLLo6BPuHe0HUpErcOXA5R16SwMApokntCP04tq1u1qN5jdTA8AjAN2IR7RAyDIxtpXyq4dL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bzX+JVmH0LreE4AD6IJbrcJuaG7StlCyC2HkKDq8StGyew0KKkfOCGz4OJJWGS5dJoDkNin9PDhUnaV6kImhDArsjSfKGeGjp0l8d6hlvMhZUmtaBqyf0PKigbCNRiyj9Gyjur+wxQ5Asd63DkQnuAYxZ9iOoUsMwRmi8C+FQKlOQpNvYybLXim2PwQqHUIrQjs2n2clmX3Pj/oTKM5IrC1qV5Tsrh3cM6xVm1FQ2C+COxzCL6fid1Mzxcp02wRCPwDUTuxRxqTQUIAAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle \\sqrt{\\left|{u_{1}}\\right|^{2} + \\left|{u_{2}}\\right|^{2} + \\left|{u_{3}}\\right|^{2}}$" + ], + "text/plain": [ + " _______________________\n", + " ╱ 2 2 2 \n", + "╲╱ │u₁│ + │u₂│ + │u₃│ " + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "u.norm()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAKsAAABnCAYAAAB/wrLWAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAMT0lEQVR4Ae2d3ZEUNxDH967u2eWPKgdwZIBNBBwZQDkCQwa47gneKDsDQwiQAWRgcAZ2AH4wlBM4/39zoznNtzSSZmd3W1U6SSuppf6rRyP1SH1nNzc3O3PxCLx8+fJKte7LP1D8iaOg+Fs/7X63MB2BCwEL4J9GSL0z4PvICJOv9et9hb/J35CW/yIPlgixuQUICL+/VO1yqKryzi68jN8Up7Dv/vYTFm8Q+Fax1wLwscK/FX6pcxDUj3W8CZTPAPwu/8Qr2+RbpEHg1yZ2F3mkKDjvfGH9XUCacN6BNBpzOCn8SYUQQuceKPLeJQhVhtkWYR2cMShj7hYBYfW6i4V+46dKWM+7mZaOQoCZ9E+vBukPtYBWPyv+p/w7r4xFFyJgwroQOK9a9TaSQCKorGVJEzeXGYGLzPROjdzP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Me2vIxxOlxoAWc4zDIm2AGjYz7d6YCw/eImam3cOkGxVG/iaxmx2UjhZWNWpm2vvQxlwg3KreN4YHPp2bmXaB4Ku0eibC9bAA1GXtFaQ50aM96PnOzLTfodEbA2X562cz015jxSxkZtrvBGcwpgeuZwRNv5mZdtASECjWOVSMgYfurMQHgJQDx5MX8ER7626y/8KrlM40Jy5zPJiZdqE9ewEv54gUoBXcfwkty48gvW+Bfk6RnOWBCYqHTp5JiSXBJ8XZZBZ10Rss15u6s/wDYaxeAzqzLeqqh65MbCgakxfwYumtXT60/yrn1nxmpj1ikHxh/Usgdqu+029T/00E0FlXmpn2LnIjaeFpZtrHseEmcHdZ2ZRGWFmf9BbodQl/fdVUchEBb2baHRiBoTBL1jeGNKV2xsY0pPpkGdFO2ZNM0WbyG3UXathtlkYLzWTw7f+tPGuYSeHu0CkFZim6ne6PPuDdckvSJ8nD3ENwdnOTfmlVjfBqw6ZTjLAuGUSrc8II/A+040n7aVkqUwAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}\\frac{u_{1}}{\\sqrt{\\left|{u_{1}}\\right|^{2} + \\left|{u_{2}}\\right|^{2} + \\left|{u_{3}}\\right|^{2}}}\\\\\\frac{u_{2}}{\\sqrt{\\left|{u_{1}}\\right|^{2} + \\left|{u_{2}}\\right|^{2} + \\left|{u_{3}}\\right|^{2}}}\\\\\\frac{u_{3}}{\\sqrt{\\left|{u_{1}}\\right|^{2} + \\left|{u_{2}}\\right|^{2} + \\left|{u_{3}}\\right|^{2}}}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡ u₁ ⎤\n", + "⎢──────────────────────────⎥\n", + "⎢ _______________________⎥\n", + "⎢ ╱ 2 2 2 ⎥\n", + "⎢╲╱ │u₁│ + │u₂│ + │u₃│ ⎥\n", + "⎢ ⎥\n", + "⎢ u₂ ⎥\n", + "⎢──────────────────────────⎥\n", + "⎢ _______________________⎥\n", + "⎢ ╱ 2 2 2 ⎥\n", + "⎢╲╱ │u₁│ + │u₂│ + │u₃│ ⎥\n", + "⎢ ⎥\n", + "⎢ u₃ ⎥\n", + "⎢──────────────────────────⎥\n", + "⎢ _______________________⎥\n", + "⎢ ╱ 2 2 2 ⎥\n", + "⎣╲╱ │u₁│ + │u₂│ + │u₃│ ⎦" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "uhat = u/u.norm()\n", + "uhat" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAbAAAAGiCAYAAACGUJO6AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy81sbWrAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAh9klEQVR4nO3dC3AUZb7+8d8kkABLEohALhAQFgVRIIggYB0SBcwipbBVx0WqNKwLCogsyK6s2WPJUatOVMSoiER0JV7KAsENVGW5GG7JykUlgBuzyuESSPSfgBdIIKsBMv2vt9nMyUAmZCZze7u/n6pWptPNdE9n8vB0v9NxGIZhCAAAmokI9QYAAOALAgwAoCUCDACgJQIMAKAlAgwAoCUCDACgJQIMAKAlAgwAoCUCDACgJQIMAGD9AFuxYoUMGTJEYmNjzWn06NGyadOmFtdZu3atDBw4UDp06CCDBw+WjRs3tnWbAQDwLsB69eolzz33nJSUlMi+ffvkjjvukMmTJ0tZWVmzy+/evVumTZsmM2bMkAMHDsiUKVPM6csvv+SlBwC0iaOtN/ONj4+XJUuWmCF1ualTp0pdXZ0UFBS45o0aNUpSU1MlNze3LU8LALC5dr6u2NDQYJ4eVAGlTiU2Z8+ePbJw4UK3eRkZGbJ+/foW/+76+npzauR0OuXHH3+Ua665RhwOh6+bDAAIAdWTzp49K8nJyRIRERG6ACstLTUD6+eff5bOnTtLfn6+DBo0qNllq6urJSEhwW2eeqzmtyQ7O1uefvppbzcNAB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ABALREgAEAREf/H9qaIHOiQD19AAAAAElFTkSuQmCC", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "u = Matrix([1.5,1])\n", + "w = 2*u\n", + "uhat = u/u.norm()\n", + "\n", + "plot_vecs(u, w, uhat)\n", + "autoscale_arrows()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Dot product" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAKsAAAAPCAYAAACbZT/hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEAUlEQVRoBe2Z71HcMBDF7xgKIEkH0AGECoAOIKkA6CAM3/jGkA5IOoB0EFJBAh1AKoCkA/J+QmtkWT7JmTtjDjQjS16tnnbfrf75xvf396N5SkdHR5vyZ1nll3nyq6sv88jDQlcSnoH+kmwkv/Q0dzzMY7C+9CCdW/8X8UxbBrNwT3lF+TLeQvV+Lvmuyr8qi1KA+U4drkNM1a8lO1D5rQisJ6XA5lceBhgPtrIe6of6rJj4rnwSxobkBPG2yuJA9f0N82eMqfe3yh+93pAKs/mVhwHGw6KCcFXRQkCRtpTvXO3xgezq8fWhpn6sxh+U91VfC9sTmDdhu+q7yusmm4RlOrMuEzZnefB2H3rbln1Z7UAJzFYecliz9t/wEzaX8IDvXGzRpc5veywsFzcJzEk8tGJxDLgxUNUJvmPlMGFETeYHR04iaOOUw6yMLcCKsd27+p2qYjaEOqzaI7Xvh0Jfv5J8JyFHlLO5wYP6nITjqI5Nl8ocI0g5zIoH6eawHGD88GM+OQ/eV/cFRjZ90vsP5Tfe3k48tGGxsrrtXSUOE3jVJx/JiHJkF8pVkpwZww+/XQmDiuSGSXsN06ttSodjx0jlRCyv3yjULxWM4DEmn64cfqNji0D6ZnMxD4LaU79zZeOHIxSyVWX4McwsDzmsFrNHGmMIPNQWM9nKPYVV1qWOPLRiLRqgSlYcZoAj2MtdMErmlvNAt7TKESLGpC/ODDV14YFA+VXgSAkPpVgFw01FpZiHRHwQN7W7j7coy8MkrDBYWUXjoATcrRoC4aJ1pjIMZm9Da9HAVH8cYbscamrYLEOTPMiXahfyzhBw4ZZnPjYwYx46YBnmrMuGzRowyYMZIh/Y/rk4nyb8Qa2BGfOAEimFtfDQ5J7h+QllLl7vlS2AVyTrEqiA0hcDXVJ/6mzRtbF881CKmm2lPHg9JmLtsumd6sRDBqsvnjrzILs5em0ob6lO4MapmIcU1tj+blXjkpC/KmPkrS8BZznna8GFdHivkt7dcq/SLhRVm1XUxirKpYfPQSO9x6sRYuRZLKeYeXiczmdWg1X//+GBSYifO+qfnNCSl/KQxTJbJ5VPwYPZo7FZ6Lhorqkex0wRDyms6hggUEhO3ZRTMsPKlsJla3w2qSsP0ie4+IODLXLk3ynjlSnLg++bxeqDTNlSFA/SY3L/Vt5Q3QLTJmy4MzuzpdPKQw5roQ/Hex4DooysmQ4tcm0V5IzGFwBWlAPlu64DTxPLj90LD7KbcfA3nJx8UUF+plyccljVMaAYUYqeWGYIRvEDcVa5lbzT5yL1mSoWeH0m+ftH4y3FY0o+jmW592li5caadrtsJwa4WHF8JK0rs0OEAewaco9JWP8AfWCOn7BFeX0AAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle u_{1} v_{1} + u_{2} v_{2} + u_{3} v_{3}$" + ], + "text/plain": [ + "u₁⋅v₁ + u₂⋅v₂ + u₃⋅v₃" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "u = Matrix([u_1,u_2,u_3])\n", + "v = Matrix([v_1,v_2,v_3])\n", + "\n", + "u.dot(v)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAOCAYAAAAWo42rAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAA2UlEQVQoFXWS4Q2CQAyFwTiArOAIRjdgBF1BRjD+4y8j6Ao6AiOoq8gG+H0ndwGiLylt3732rg153/eZqOt6jatCkmUrvHkD38rlCkk8kIxCuT3cDTsQ3xcE4qgNh4HgEzrhzxJR+CLuBpO3o3nC0gjS6iKxX86rxcVP7GicQGFJ0mAV8dWD0NFAQG5winaYz3lgAWHqmIw9RZOp/wotQvzGuboivNErNQ9niFeXcZgngidiq38iDuPOWoST3cFth6o2Ck/zNhQ5jDe4oi4NQ+JaDqOCNXH6KT7nF1G9okQFwwAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle 3$" + ], + "text/plain": [ + "3" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAbAAAAGiCAYAAACGUJO6AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy81sbWrAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAcCklEQVR4nO3dfWxV9f3A8U95aiHSSqe0PBTshuNBHorIo4kUBzTIEP7ZGEtsp+CmgQXGMkMdgyjb6gQENgmFEG3UMBAcJak8iFRKoCWOpwy6jQBDWk0LmkErnRbSnl++3/1614u9pff23t77Oef9Sk7gnntO7znc3r4553zvbZzjOI4AAKBMp2hvAAAAoSBgAACVCBgAQCUCBgBQiYABAFQiYAAAlQgYAEAlAgYAUImAAQBUImAAAPcHbNOmTTJy5EhJTEy008SJE2Xfvn2trrNz504ZMmSIJCQkyIgRI2Tv3r3t3WYAAIILWP/+/eWVV16RkydPyokTJ+Txxx+X2bNnS3l5eYvLl5aWyrx582T+/Ply+vRpmTNnjp3OnTvHPz0AoF3i2vthvsnJybJ69WobqTvNnTtX6urqpKioyDdvwoQJkpGRIfn5+e15WACAx3UJdcWGhgZ7etAEypxKbElZWZksXbrUb15WVpYUFha2+rXr6+vt1KSxsVH+/e9/y7e+9S2Ji4sLdZMBAFFgjpO+/P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uh1u+//76jTTD7vGTJEt+yKSkpzhNPPOGcOnXK0aRpePidU9N+mj/Nft+5TkZGht3vb3/723bIsTbB7vcf/vAH5zvf+Y79IZacnOxkZmY6xcXFjiYt7a+Zmj9/bnxdh7Lf2l/bzzzzjDNw4EC7/ffff7/zve99zxevSD/P/DoVAIBKUb8GBgBAKAgYAEAlAgYAUImAAQBUImAAAJUIGABAJQIGAFCJgAEAVCJgAACVCBgAQCUCBgAQjf4Pu0yIPwBXyuUAAAAASUVORK5CYII=", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "u = Matrix([1,1])\n", + "v = Matrix([3,0])\n", + "plot_vecs(u,v)\n", + "autoscale_arrows()\n", + "\n", + "u_dot_v = u.dot(v)\n", + "u_dot_v" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "angle between u and v is pi/4\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAOCAYAAAAWo42rAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAA2UlEQVQoFXWS4Q2CQAyFwTiArOAIRjdgBF1BRjD+4y8j6Ao6AiOoq8gG+H0ndwGiLylt3732rg153/eZqOt6jatCkmUrvHkD38rlCkk8kIxCuT3cDTsQ3xcE4qgNh4HgEzrhzxJR+CLuBpO3o3nC0gjS6iKxX86rxcVP7GicQGFJ0mAV8dWD0NFAQG5winaYz3lgAWHqmIw9RZOp/wotQvzGuboivNErNQ9niFeXcZgngidiq38iDuPOWoST3cFth6o2Ck/zNhQ5jDe4oi4NQ+JaDqOCNXH6KT7nF1G9okQFwwAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle 3$" + ], + "text/plain": [ + "3" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "phi = acos( u.dot(v)/(u.norm()*v.norm()) )\n", + "print('angle between u and v is', phi)\n", + "u.norm()*v.norm()*cos(phi)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Cross product" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIoAAABLCAYAAACvMx91AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAJaElEQVR4Ae2dXZLUNhSFe6Z4TiWkKgsYdgBhBQw7ALKCgR2E4gneKLIDwgr42QFkBQF2MOQ9VVBUVpDzeSQjW7ItueVu03NvlUbylXx1dXQs+UeaPnr8+PH1zWbzQSElb548eXI3lWG6w0JA/XyuFp2kWqW8oytBxh9KUziUT+GBpQ8agWeJ1t2W7g76kCjPxRwjRgKty6BS3//Zb6d0qBqiHPcz7dgQSCFgREmhYroIASNKBIkpUggYUVKomC5CwIgSQWKKFALhU08qP0unu+MfVfC+wjWFD/07aB2/lv5M8VfFWRLY/FknnIc2leYx/qHiN1nGdlQo8PngcKg1ojwSSLyHeavQeR6XHgLdUZxNEtev3ubffZs6vqrwmyu3psj7fHA4bE0UEYA3u3QmwguaL03q2x90H78dTqcSNvvvd85kpa+bNrxgiYTPB4VDjannk0DyRLinvnja64/Tvk7lmaoeuXInLg6npimbLUlki/Opg44hfVPhaeCTDmNxPvylHHzJlbsjdqd8TuEw5fuUzRCHKUxz25gstzVRBFwzpSgGCJxt3/BJBxDo3imE8kx5D7xC6edK872JuX2jY2+Tt4Idm+RLTlWGqQ5hqgPQpl7Fv+sYAvykMCiujhuDBQoznL2N4iIcVM2g74HNLBxUfhDTwuZExY8jzXwFHw9pdNPJzkzz+lc6P+J46/elA1AvdPaJdExjoTBt9W2Szw2uF0awl/5AMXn9YT/IXjxZgkOu7zk45GI6C4CtR5SgVkaPPiFoYDOaiATc1L5SDJFg/nuFKYls6nzIxwjUiI77dZLfuaF2RXcVRT6r4iQOBb5HNvs4qI5cTGfhUJMozJc8jTSihjA6/Krgp6Jr0vkpxesuCl80k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UaEhBzSb0iGK3yYKuZqtm4Xmdlr8e/J9L0RxANGZpwrbbvBa9AeNFmZONd8rYxo1e19E4f6lyhUvgKr9SFSEzsKKmr7LVjVMU80+TilNZwj0ETCi9BGx4yQC4dRzruGrX+iNdFs9tfQN2vE6EVA/n8sznh6TAlGY24YeQckzuRwI8A5qUP4H0/QbVj3ixZcAAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}u_{2} v_{3} - u_{3} v_{2}\\\\- u_{1} v_{3} + u_{3} v_{1}\\\\u_{1} v_{2} - u_{2} v_{1}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡u₂⋅v₃ - u₃⋅v₂ ⎤\n", + "⎢ ⎥\n", + "⎢-u₁⋅v₃ + u₃⋅v₁⎥\n", + "⎢ ⎥\n", + "⎣u₁⋅v₂ - u₂⋅v₁ ⎦" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "u = Matrix([u_1,u_2,u_3])\n", + "v = Matrix([v_1,v_2,v_3])\n", + "\n", + "u.cross(v)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZoAAAGRCAYAAABcwXWgAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy81sbWrAAAACXBIWXMAAA9hAAAPYQGoP6dpAAChEklEQVR4nO29CZhdVZX+vTMwT4LKJIjMoKCAgCiDYgeQSQHBMMg8yCiCNhAmcYCAKKCA0qB8gMroXxQNDSKIQIJAsLttGydAQAZBJjEECKnU9/x25a3sOjl3OOPd59Z6ee4TqlK5de45e693r7XetdaYwcHBQWcwGAwGQ0UYW9UbGwwGg8FgRGMwGAyGymEejcFgMBgqhRGNwWAwGCqFEY3BYDAYKoURjcFgMBgqhRGNwWAwGCqFEY3BYDAYKoURjcFgM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lfejFexiaDSvYNFTaXZoGjjSN5N8cc8wxvgcXMlskuYTQDAZD/8NCZ4ZKu0sznAs11HHHHecTu5DQscce60488US78wbDKIF5NAaDwWCoFJajMRgMBkOlMKIxGAwGQ6UwojH0HWhNjzyWinK6Bt9///1tfx5Bw9prr+0WWWQRn1Min1RXTzCDYTTAiMYwqpt+UrNx0kkn+Z//wx/+4L73ve/592hSuxaDIXaYGMDQV8CD2WSTTdxFF13kv6Z+By8FaTWEksTRRx/tCSasDfr85z/v7rvvPj8szGAwFId5NIZR3fSTIVv8G4XX6M1GT7Yddtihtus2GPodVkdjGNVNP+mAzL/bYostGJnhZs+e7Q4//HALnRkMJcI8GoMb7e32GVvw7W9/2+d0GJ1M230aOxoMhnJgHo1hVDf9PO2009y+++7rDjnkEP/1+uuv7xs/HnbYYb5FTgydkA2GpsN2kWFUN/1kXHCSTNRpmlCawWAoDvNoDKO6NT0zXc477zy34YYbesUanabxcvh+ONrAYDDkh3k0hlHdmv7UU0/1cmb+ZGrlwQcf7Otu6E49mpC1yPWGG25w66yzjv95wo0o9QyGVrA6GoNhlIMCVTw9pp5CMniBEMmf/vQnP8kziWnTprmtttrKe4U77bSTL3plaBliivXWW68nn8EQN4xoDIZRjqxFrniNhCN//vOfD39vs8028x6kjeg2pMFCZwbDKEaeIle+H/48INzY6ucNBiMag2EUo12RK4Pt0sD3s/y8wWBEYzDUjLvuusur2lZccUU3ZswY95Of/KSrwtKNNtrILbTQQm6NNdZwV1xxRS3XajCUASMag6FmkN+gqzRKr27w17/+1e24445u66239iq6z33uc77AlBHZvShy5ftZft5gMKIxGGrG9ttv77761a+6XXfdtaufJ8G+6qqrum984xtu3XXX9R2nd999d3f++ef3pMiV74c/D2677baWP28wGNEYDJGj6uQ7Ra6XXXaZu/LKK/3IhCOOOGK+ItdJkyYN//yxxx7ra5MgPpqVnnHGGW769OmeAA2GNFhnAIMhcrRKvr/yyivutdde85NBiwC58j/+8Q9f5MrvQqacLHIN2/QwWoHaGYpcGRC35ppr+jyT1dAYWsGIxmAweG+klUeCECGJPfbYw78Mhm5goTODIXK0Sr4vueSShb0Zg6EOGNEYDJHDku+GpsOIxmCoGTNmzPAyZV6SL/P/5EIAiXcS8AITPxkxfcIJJ/jkO0Parr/+enfcccfZszM0AtbrzGCoGeQ8qIlJgvEGFGIecMAB7rHHHhuRG+H/IZaHHnrIrbTSSn6UAT9nMDQBRjQGg8FgqBQWOjMYDAZDpTCiMRgMBkOlMKIxGAwGQ6UwojEYDAZDpTCiMRgMBkOlMKIxGAwGQ6UwojEYDAZDpTCiMRgMBkOlMKIxGAwGQ6UwojEYDAZDpTCiMRgMBoOrEv8/O2xs/QktILcAAAAASUVORK5CYII=", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "u = Matrix([1,0,0])\n", + "v = Matrix([1,1,0])\n", + "w = u.cross(v) # a vector perpendicular to both u and v\n", + "\n", + "plot_vecs(u, v, u.cross(v))" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "length of cross product 1\n" + ] + }, + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "print('length of cross product', w.norm())\n", + "\n", + "phi = acos( u.dot(v) / (u.norm()*v.norm()) )\n", + "\n", + "w.norm() == u.norm()*v.norm()*sin(phi)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Projection operation" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [], + "source": [ + "def proj(vec, d):\n", + " \"\"\"Computes the projection of vector `vec` onto vector `d`.\"\"\"\n", + " return d.dot(vec)/d.norm() * d/d.norm()" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAbsAAAGiCAYAAAB+sGhNAAAAOX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FRke21vvnmm1bHjh2tpk2b6in9e/bsqXI5hPo/qOyjjz6y7rjjDt1eTYv/7LPPLG+oT90pKSnOtuq4eOihh6wDBw54vOaKKfnXLxW1qq+q9uu3iY2N1bWrX4AqH+u+Wverr75q3XbbbfrDVh3Tw4YNs7Kzsz1ed3U1X/954YvHeEPqTvGBY/ypp56yOnXqpGto06aN/uytCLrqanbXvuZP/AAAjOezY3YAALgLYQcAMB5hBwAwHmEHADAeYQcAMB5hBwAwHmEHADAeYQcAMB5hBwAwHmEHADAeYQcAENP9H26sboxHHshcAAAAAElFTkSuQmCC", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "u = Matrix([1,1])\n", + "v = Matrix([3,0])\n", + "\n", + "pu_on_v = proj(u,v)\n", + "\n", + "plot_vecs(u, v, pu_on_v)\n", + "\n", + "ax = mpl.gca()\n", + "ax.set_xlim([-1,3])\n", + "ax.set_ylim([-1,3]);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Matrix operations" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [], + "source": [ + "a_11, a_12, a_21, a_22, a_31, a_32 = symbols('a_11 a_12 a_21 a_22 a_31 a_32')\n", + "A = Matrix([\n", + " [a_11, a_12],\n", + " [a_21, a_22], \n", + " [a_31, a_32]])\n", + "b_11, b_12, b_21, b_22, b_31, b_32 = symbols('b_11 b_12 b_21 b_22 b_31 b_32')\n", + "B = Matrix([\n", + " [b_11, b_12],\n", + " [b_21, b_22], \n", + " [b_31, b_32]])\n", + "alpha = symbols('alpha')" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAF4AAABLCAYAAAD5yTBGAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAGQ0lEQVR4Ae2dX47cRBCHZyOeUSASB5jcIGFPkM0NApyAzQ0S5Wn3LQo3SDhB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{11} & a_{12}\\\\a_{21} & a_{22}\\\\a_{31} & a_{32}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡a₁₁ a₁₂⎤\n", + "⎢ ⎥\n", + "⎢a₂₁ a₂₂⎥\n", + "⎢ ⎥\n", + "⎣a₃₁ a₃₂⎦" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAMUAAABLCAYAAADAgkNYAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAKoElEQVR4Ae2d3Y3dNhCFrwM/BxsHSAGbDhJvBV53kJ8K1unAhp/sN8PuwE4FdtxBkgry04GT9wA2Fqkg5xNIhdLqShRFSeT1EOBKIilqzpwZkeKVZm89efLkq8Ph8IfyUHr79OnTb4cqrMw0UKsGZNPvJPv5kPyqu3U7qHihfRqH6a/wwPZNAyeigecDOO6r7BvKQ6d4KS8xJxjQlhWdlgZk56/6iFRG0Q2n6Lc7+WMp4kwgf1K+q/xBx1+ePOjCAZbAySeF62hV8UTAtTLDJiPkL6tezDqP0kAJnFTvFFLipfKDKI0fb8Riw8/Hq61mjgZq56R6pxBZTIHISQkC3Yk2UiRpcPCkqjk5BacYZGVGYTN9knNczzjHmq6rgV05CVefJmHKcM7ViOUs5uDvld8qf6NylnNrTYwUfwrDQwfgQtvXOgZb8ck4yU9R9Egh5WM8/Mj3SPtkHOGl8nPtJ09fdP5uycnN8wTO/sphutL+T9qnrOgkGY2TFRiKcgpnPCxd4gzhbxns/6WyWqceGBXpnsfgtuBp1qyb2gL/SE5uRMbJCtzcjuyTKdOZiOj/6IFR3ZhmOMK+U90P2v+6f42p+n57jnUOo5I34rDJHVf/Q1jo9pkWjb2mwtyVNn2nxuA+9/2pnuOseHzfC7bZOHH4HjtZ/Ah5NaCXjriqL5KTVDweXKxTYBCd1Rl3YRTYWcpUOdM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oLhiaZj3KSisfzEesU3NU7qzMyUgyaO1A/HtQz37nbEmmPUaNJOq+2YGir4PH6WLDNxolkeCBejgawOyajzuELyhtJ5URwWTNA3SgnunYSHg9k0ikE0C+v9Y0fUg6q7ztLO01yF0FB3NVKTDj1aDA04SsOzwqcYNw+XNHePOXgZBGeSacINBQ+S1DMslljMCIJw2+CoVFBUhnTpu+VX2q/HyCNJqWkFpfk5AaAs7fB0LyQheJpZXdyJnEywA9GxfSkf0Pw6lh72+JK4WQpnk+m0OkC12rDaIAHN0llOMFoMDS1YXXqnjKB0nCQElN04K2S8EiW1ThR33sHsMvKSQqeSadwlkwsoQtd4KGy/52Cu9IdyrTlIfhGUh3kPVLmQQ5ll5auJBBOi3xgYF7NXXIwqa4kPNk5ET5ufPC7ZwC7bJyk4omaPjljGAqy1SlTuzMp9G9lljj90Ishke4q+7KmYO8/I7ga0UrGMyJ7EifqD4fYPeDbCK5ZnCzBEztSRNmvA/RBjds5ofYvlXGMN8prJPr2jpe1/53wbI7BGRAjJc9//MsERnVGeLhMSbtyshRP1EgxUyvcqR5LMF4DIV0ot8OxE5gpCs5SQzC0TfFIJ2ukUQy6YG3B0FbFY8HQ1jBB67M6DehmbcHQqmPNBN5MA1mfKTaT2i5kGlhRA+EzxTsNIf1LvVUZ8zdLpoGT0YBs+p3AsNo2mHAKVoqOrc2Hq0iDHVihaaBCDYy+dvQf1ZdJv1idTtkAAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}a_{11} + b_{11} & a_{12} + b_{12}\\\\a_{21} + b_{21} & a_{22} + b_{22}\\\\a_{31} + b_{31} & a_{32} + b_{32}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡a₁₁ + b₁₁ a₁₂ + b₁₂⎤\n", + "⎢ ⎥\n", + "⎢a₂₁ + b₂₁ a₂₂ + b₂₂⎥\n", + "⎢ ⎥\n", + "⎣a₃₁ + b₃₁ a₃₂ + b₃₂⎦" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A + B" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAHgAAABLCAYAAAC7ikPRAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAIQUlEQVR4Ae2dXW7cNhSF5aDPRYoAXcBkB/lZQZwdOO0K4uwggZ/sNyPZgZMVpPUOkqwgbXbg9L2AA6MbcM8nkwIlcSjKJiWNQAK0KP7ce889JCWN7oz3jo+PH1VV9beyL52fnJy88DWUumV4QPxcyJKNzxq17f3kNLxTmc5u+u6elPIiPfDWY9Vz1R1Q7xJ8JsYLoR5vLblKnL3v2qc6qmqC73Uby/m6PFAIXhefPTSF4J5L1lVRCF4Xnz00heCeS9ZV4d5FDyLT3dlGnbgt5277Uvlc+UD1PGJlSZLtPgag/1R137IoCwjdVezRK1gA94WfD0TeqEyG1DPltyrf1zFpksyNMs/ln3Ssdar8UvkLbSjjqFw/DnCeK0nHzmKPIlgAIfBPZRztPitT/q66qwzOZTLxbP7ZyjZ6/tL5G1MHuU277ZfyKJ07jT12i2abvC+w3YdqZjbbdCsZp/ymylcqP2416iSinZ0Bfb6tn0n1xMh8oD45JpcRXx+SYTe4j4zwehdS+aWLQeWk2GMJhqzWSjHGYuQnY3B9UD2fbUM8idnfSkPtpnNPnyMEQtmacfypU5+r2LPltthlIJezV9ZQlSGTneqhrdOxp89pG419cIs2YCCqRaQxpFJ7l/hvqmPluVt5Y6PahtrR5dPXyDDtXyULwNmS5G+zBRIqtY/CriGHGmMnPyKYpExWFgXytumj2Sb6RGMfJNhK1bFLGB9o13ezMow7abvlOEPGFyUnhrQr9etdGsZrix6RCjurl3sIb8qBfZBgo5SZ2hCoOm5umHXW2Oeq6zrBCyKykms9E6iVpONQFXaWVzqvZ36rU8ITyWeyJcMuee+NTGslhHOT6j72JcUeew3mnfAHGfJaxwfKH5UhgGsKdVxLkiXJ5OYM2W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k8UAieztezaCoEz+L26ZQWgqfz9SyaCsGzuH06pYXg6Xw9i6ZC8Cxun05pIXg6X8+iqRA8i9unU1oIns7Xs2gqBM/i9umUFoKn8/Usmka9bDBvgniJXwLfdyToP3oFi1xe7/G6qwS+71DQf9QKFrm8340N/t6oL5PhhzLlp8qtr1wYeUQmri3wPYjd4N79wHcR10RXCtRrnX9Rrt+F6nzVge8h7GqbJfBdegcTq60V/2xmIzO2Gy99qrqPjkR+nZbVXCeNW3PgexC7HDBV4LvxdvufUzaVbsEQyRbdJdIb/A2B7niVCZvlxiwqBfS547FncYHvEdgJVdr6pYAc2KOuwcazUcHflgUZy9b8uzI/qdcNhrfdekf13dnAdwtmG3aPHyC8+VJADuz3rFHbjihV2+jAd43j66XPlPk1eMgek5IGf49R7PbNiV2yt30pICn2qB8jlTFsiR+UvyrbX3yHeLZe6j6rT3drVnUdRQkQHq8IgG/6qFxv3Tq6/3GEIXVSvd3Wu7/4zgonLBf92aMxpSsHdu5dwPBC8sHRSnfFrvHNj5FGbdHGCN+vu7fq1A9n/KP8TGVLpgXwRPW2rgXId6LxWyMv1cbWNkmSLuxv4TSKW3XqF4Vd/SA3+IPg6pMM++AWPcaLxhk/NMa9XvNMjJP+GCNr1/rGYDfksnK5L3lEVhky8VmWFLWCR2pmZh/J+Esz7qmOzfeTDEhWIMSvLfA9iF14VxH4zja8dSsWwWsOfB/CXgLfNTlKSuiBpNfghHYVUYk84F6DL7R9dsWeq651t9jtUM7n9YD44TGSO3NvgmCuidseO9y7Ya+AUjm7B+znBV5D/gfeLWyGI6DRegAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}a_{11} \\alpha & a_{12} \\alpha\\\\a_{21} \\alpha & a_{22} \\alpha\\\\a_{31} \\alpha & a_{32} \\alpha\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡a₁₁⋅α a₁₂⋅α⎤\n", + "⎢ ⎥\n", + "⎢a₂₁⋅α a₂₂⋅α⎥\n", + "⎢ ⎥\n", + "⎣a₃₁⋅α a₃₂⋅α⎦" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "alpha*A" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIkAAABLCAYAAABEBKR2AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAJf0lEQVR4Ae2dW3IVNxCGj6k8pxynKgswO4B4BZgdkGQFwA6geII3F9kBZAUJ7CDJCkLYgcl7qkxRWUH+T5bGGo3OTOtYM7bH6iqd0bXV+tVqaS5t7718+fLeZrP5WyFH71+9evVDrqDlrQcBzfGpRnOYG5HK9r6KCn5WnMoxfYoTLb5aBF5nRvZQeY/Ij5XkjbSmKUUGrbVnad7fpmNUHllOSe6khS3dEEgRaEqSItLSAwSakkSQyMQeKzyJslpUCDQl6avBvpKERhECTUkiMFo0j0B8d5OvEeXKFB8qye0Sd0FnCu8VHimf2+dqJH6sZsz+twqnSnenb8W5TX+uK31fO5Jci2DEwNXXIjiZLYkEOpZcPHRjgggoxhuF115YRavRC8//L3FM7+EPlPdTtZ4qMpLMS2KE5IvgZFISrwTvJBTKET9LIf5JeV+QuAaJF0+AUQ6IBzpxf+Q9zuSRf6W0JEYMdEmcrNsNq3lfgnVm388IK2dg9j1gP6rsqeL3fd3uMlGO0n30leFx0jU8j/SUZoJX0vQ8qTZYQGRPCSu1UfnTtEDpj8ofe0VRDSP1wzbywsvA9gU9Vn68GM04Gfmd95L5tSoJk/VH3N53zAB+T/KxBGECGGyP1G6q3AGhejzto/1AMVXmzkBTvHodRwm1yynBRvn0eajrLmesahhJBrbwTkbFUWq2+rsKjpRnxkkNJvl5ttnL5HYjYZgoQk8ZlAaUjcpT5WHFAXJvxVMXUtlo+Xkt9+u2GtV3YET5HGYdFfAKTWa5So6qGEnIJ+IZFhoyY6VQXhZYSpM4qUEJv5R/0XOSdNIRzm0LEp47nG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JcxtSPeGQPmFPtrqK8Nkbih4KYHNwsOJXwS/GzWpK0XTbtgfqswvj8cqw0ivJbttH1ykTOoNSzSGbByE8o1pnzHHc0WGEsK9gW02X5mSxJoVRYF54Envl2R7p25tILjIVAeW6rc9YoRsLlUs5Uap/Spfg156wUzpZ2CGgxN+espgt2BKqeSezdtpo3CYH4THIqE5PK/l55vTuYtEJL33wENMenGgV3U1lCSbgT2XarGd+lZBm0zFUgMPra5H/R08bIIcGvYAAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}a_{11} v_{1} + a_{12} v_{2}\\\\a_{21} v_{1} + a_{22} v_{2}\\\\a_{31} v_{1} + a_{32} v_{2}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡a₁₁⋅v₁ + a₁₂⋅v₂⎤\n", + "⎢ ⎥\n", + "⎢a₂₁⋅v₁ + a₂₂⋅v₂⎥\n", + "⎢ ⎥\n", + "⎣a₃₁⋅v₁ + a₃₂⋅v₂⎦" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "v_1, v_2 = symbols('v_1 v_2')\n", + "v = Matrix([v_1,v_2])\n", + "\n", + "A*v" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIkAAABLCAYAAABEBKR2AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAJf0lEQVR4Ae2dW3IVNxCGj6k8pxynKgswO4B4BZgdkGQFwA6geII3F9kBZAUJ7CDJCkLYgcl7qkxRWUH+T5bGGo3OTOtYM7bH6iqd0bXV+tVqaS5t7718+fLeZrP5WyFH71+9evVDrqDlrQcBzfGpRnOYG5HK9r6KCn5WnMoxfYoTLb5aBF5nRvZQeY/Ij5XkjbSmKUUGrbVnad7fpmNUHllOSe6khS3dEEgRaEqSItLSAwSakkSQyMQeKzyJslpUCDQl6avBvpKERhECTUkiMFo0j0B8d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Anyn9p8I3Chul+VoNJYJyh8T4y3oU6cTVvPjpPoE08LpoFcXU7sqdsyTOVoxUdq2cs6xnEiar99WWgGaCWRGpP046qfjJYFUcqR0WBfcLvqIfkPK/kOnL6SN10eA2Nfx16VFeA+Y+Q+35Mm5Avk++lnP8BxXGM6phpG5wznqnEDBnyyXvnoKzyLqacbLwGxvapJJIGCaKkCoDoGxUHgZCkrQbhEuc/6AM6bkiKt4atTgdbW28ZIHGXBsjlNjq4GbBqYTfALpJJYladGbe52Wds0J9AfdMcQ6YuEWk1iBUG7tipXoKJz4o3I13zgqD3oZRBi8mOd6GAwuukzgV8ot5u/idQU6SoQ4wa1gLhHGkPCaLs0XQ9sF/zlIdTPYDBcpQmFJCQeI+iW91OiplXrP+nBiJNziDd/afIim/CCcDvwE0k0riW+Bfc8RkK4TnJFiSA/J0za5ulaFguFJwEGOwZlJ92n3Qlb2ZZwHdWcTMZNmK1THSuFkY4L3Vwa0EJwu/HGSm7UbMmeycI1YvT/XYm/9ReKB42CpoC32vEPJcxtSPeGQPmFPtrqK8Nkbih4KYHNwsOJXwS/GzWpK0XTbtgfqswvj8cqw0ivJbttH1ykTOoNSzSGbByE8o1pnzHHc0WGEsK9gW02X5mSxJoVRYF54Envl2R7p25tILjIVAeW6rc9YoRsLlUs5Uap/Spfg156wUzpZ2CGgxN+espgt2BKqeSezdtpo3CYH4THIqE5PK/l55vTuYtEJL33wENMenGgV3U1lCSbgT2XarGd+lZBm0zFUgMPra5H/R08bIIcGvYAAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}a_{11} v_{1} + a_{12} v_{2}\\\\a_{21} v_{1} + a_{22} v_{2}\\\\a_{31} v_{1} + a_{32} v_{2}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡a₁₁⋅v₁ + a₁₂⋅v₂⎤\n", + "⎢ ⎥\n", + "⎢a₂₁⋅v₁ + a₂₂⋅v₂⎥\n", + "⎢ ⎥\n", + "⎣a₃₁⋅v₁ + a₃₂⋅v₂⎦" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A[:,0]*v[0] + A[:,1]*v[1]" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAATQAAABLCAYAAAD+gns/AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAP9klEQVR4Ae2dUZLcthGGR6p9Tm3kqhxgfQNbOoFXN1CSE6x8A6n0JL25nBvIOYEs3cDOCSTrBnLeU6XNVk6Q/6cBFogh0d0ckAQ1jSouQQDsbnwAewCSS9x7+fLlN4fD4TdsY+Hdq1ev/jqW4WlOwAk4gbUJwB99gs6rMb3Iu3eRZPwDcRZOw+/pgcedgBNwAhsT+HFE/2OkPWF66tBew8O5Axuh5UlOwAm0QQA+6qfcEqQx6cih5eU2O4aBl1D+FttDbLc4/nozY3aq2BnaGs552XjlpVvhdz83rIVjwLnDxmEkR4y/tmDT3mxwhrYWc142XnnpVvg16dASWHxg8UtyvFkUDXaN7elmBsxX3AzD+VVY9cxmeO20z23Kr1mHxsYM3biVERqnwdx2Expk2DS7Bnntqs+1wK9Zh4ae3005Aemu6augbeOcoa19nJeNV156c37pU87cuKNjOJcrJPKxKe9tfcb2DtsTpPOVj9qBI7SPkP0sCH6E/RscU+cuw8r8yGjXDJ3Xad38HPmpR2iAw4uDL+A+R5wbndhrbD8iXnUqFuRxLk4H+lPQdYP4W8SZtrsAu1fjRzjQxzbZLUPndVoXP1d+KocWLg6+RkFHlr6rxvjvSKs9LeTFz/BdlB321NO9b9Ll7uQPbKdzWZMfyeyWofM6rWOfM78LJTpOMy8BKn+pjRfN0RQwAP0b8r5H/Ntch5SP8pyLc7qZO0o6hq+iPEmOlB/lpHucw1FndAZp1gMeIP/7NDHEaWvpX8Sq8YMeMngR9MbR6g3Sc1YiQ42sUGayLUdY1EiqxovGKOsg8pJkaXiOwcF5tftcNX6GOon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0y+wsL8Wts7KA/Y9tzYB24LRY0/EKD89E5nRCnnAy8j8aRsCnUlGVSXKmwhlclVSoxC/BctM9p+NWskyRLytc0QlWHFhTyV+AFjOO/RjE8wtZPi4LRvADp6HyhYUDIQpEfyvIdoMuw708FVzK1hqKsWm1lNcpYvsirZh0Usoo8jfU6QN8aT/SL/GBzzTpJsqR8EaEvNCwi8gJOwAm0TACO3xcabrmB3DYn4ATmERBf25gn1s9yAk7ACaxPIL2H9glDt9yCd0jjHNuDE3ACTmBzAvBHn2BE/05sbhAdGp9ITt1QTp9W5uf6sRNwAk5gbQLFf6P8P8JYeQ8fArhRAAAAAElFTkSuQmCC", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}a_{11} b_{11} + a_{12} b_{21} & a_{11} b_{12} + a_{12} b_{22}\\\\a_{21} b_{11} + a_{22} b_{21} & a_{21} b_{12} + a_{22} b_{22}\\\\a_{31} b_{11} + a_{32} b_{21} & a_{31} b_{12} + a_{32} b_{22}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡a₁₁⋅b₁₁ + a₁₂⋅b₂₁ a₁₁⋅b₁₂ + a₁₂⋅b₂₂⎤\n", + "⎢ ⎥\n", + "⎢a₂₁⋅b₁₁ + a₂₂⋅b₂₁ a₂₁⋅b₁₂ + a₂₂⋅b₂₂⎥\n", + "⎢ ⎥\n", + "⎣a₃₁⋅b₁₁ + a₃₂⋅b₂₁ a₃₁⋅b₁₂ + a₃₂⋅b₂₂⎦" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A = Matrix([\n", + " [a_11, a_12],\n", + " [a_21, a_22], \n", + " [a_31, a_32]])\n", + "B = Matrix([\n", + " [b_11, b_12],\n", + " [b_21, b_22]])\n", + "\n", + "A*B" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIsAAAAzCAYAAACngPvnAAAACXBIW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text/plain": [ + "⎡a₁₁ a₂₁ a₃₁⎤\n", + "⎢ ⎥\n", + "⎣a₁₂ a₂₂ a₃₂⎦" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A.T" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "the shape of v is (2, 1)\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAB8AAAAzCAYAAABvwNN0AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAChklEQVRYCe1Y7VECMRAFxwL86AA7kLGDswM/KgBKYPgF/xzsAFuADrQDlQ6gA0dL8L2wOXKZfMLN3IxeZsIuyWZf8nYvl1x3Op2edRxlNpv9OJoPaoIvJ8YJvH2iflt1fhCKf9DS8k+8ZRcr30AZYXZv/rH19gBrCI/3XHljpQVvhPr/S/tpiG/ZHPhYXKJu8P9F20PnIzqGXOm2XBmjfQLnz3D6jmpvPBdoe8wFNO294AC9hiFBWW5Rt0rb/wwcbfveBC1E+xYTWIuPB8gny19lMrDl/k077pZ9y9b51wsOB+rFAnmHkXRcxls8FehjSDqQZKmQdudLRPoqwgtuWCnKAaAmY7QzCVVBHxlaQ3KiycUbc8NDD7qmXzULyMKwOUhNAScwJ6AKgKn3ICsxl+4sEaUdIHyWF6h8J7/SO3QV6ywkh3EUXMBGjrFHN6XQfjSIz0Gj4Em0+2au25EDTEKGpkBlMnIr/orlRl3gzPwxalZplPYWPCtWdRm3tNfFZJaflvYsuuoybpT24N6OFwMPg3/z0uBdOVadcmm4YfyFoYnkQk/kAO32iVe6dsILju6cS8McQOVRCzpPtvzWc7WDcf96E07PGjJ0adCXxCHsCgOChwkeKsiet3jBjRHRSwNsueoPY0ySGqJdO2AMg5cGrNC+SnEyZti0r4pMWXnWpUGoZqiil8XoyuEs+dIAW7LEePehBzOdFETBaQRHZSbzv6sIMCfKHOEYToTSe61KAqeTUBEgPl4E1xnOCQdPtLWAA4TPNLdiyrJgIkHGagEHyHmJmKGkZHuGuzzTRsE17dwKGbOy4H/0USmNI4rtG+YKS6+cmWp+8Le/uUXcR7vtj/3K/y+FPtWEFku3CwAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}v_{1}\\\\v_{2}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡v₁⎤\n", + "⎢ ⎥\n", + "⎣v₂⎦" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "print('the shape of v is', v.shape)\n", + "v" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "the shape of v.T is (1, 2)\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAEUAAAAZCAYAAABnweOlAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACLElEQVRYCe2Z8VHCMBTGC+cAihvgBrICbODpBMAGcvwF/3m4Aa6gGziCwgawgXeO4O/LJb1Q0paetiDtuwsveUmT7319eQnQms1mr1EU3VKcDObz+dY1zl3j6yM+jj0/Jy1IWdHR84y1rcLDSM63a8tAhuMNKQFyGlIaUgIMBExNpDSkBBgImC4CNmPieLqkoiPqmrKh/WI6+KC+QU3Qb85WtWbt0vBlbZ8pCz/j7AdlkXC6Q/shYau6WRq+ICmQoRuuyJAMKMkb7jBg09hKpGx8adtny8Jr6+E9+inh7Q5JjFUoa9yYehW344PxWWxTi79r9RD7t63vqSAp7gH0HU/I4Tif2Bn69GlrRWhFVd/aNbZ0YU3jEDoXH2AWjIu/21BfYltRbtKABrePN9hsHQfCsyv5GqFvTRFBO9Fju8tWufgAMAKfe2nCo/zYxeZ/CZY9ljxSFG5uG5mHmExvR2yfghyCT1HyWQRscPt4E4iQmGUIEQixfLSj2MOmai4+sCa3vkjyc1JiyijKJIUJdRdZUvSby7uepm5yyd5MRzCApRA+xmvLKNIzD4NMUuQnE8VJSu1Tk0PxMU5RrnzSo5568si/XFI06L+LJURRpcQc2bZ08HA4e1IsAToYRIo7cRT9ExEUkl+TYhfVIn2KkrBC9At9KrlHdxLdn6RjAV9qWvgLUhSCqazHKI5Uwfmroku3iz5Qh/ENKYG3bLYPIabfR5zU+X+fDiRMfgCTr8buI5jdnQAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}v_{1} & v_{2}\\end{matrix}\\right]$" + ], + "text/plain": [ + "[v₁ v₂]" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "print('the shape of v.T is', v.T.shape)\n", + "v.T" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAALYAAAAZCAYAAACcutQ/AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEvElEQVR4Ae2c61HcMBSFzQ4FkKQD6CCECoAOSFIB0EF2+AX/GOiAdBBIByEVBOgAUgEMJeR8XsvI8kPSxruz3tWdEXofXR1dX1/bm6ydnp7eZFn2UcnI/tnZ2ZOppDwxsOgMyF6/ScdjS8/xmgz7Xh3bVmMqJgYGy4Bs+QjlR4PdQVI8MdDBQDLsDnJS13AZSIY93LNLmncwsBKGrbhrz8ReHVwsfdcq8bAShi2L3SjS0huvZ4Mrw8OqGLbnvFP3sjGw3rYh3ba4unl1sqXEK8Hv9ljVef99qPzVbu8qW5gfNO7RxlT5UW1j5T+7MObdZ+mceBiQPXR57BMd6qUM6ZfShW1QasfgD5QHG3Ux32D+cTFVf6/0tRi3SJnROfEwIHtoNGwZLF8iMT5kX+klL739oe3hreovNWC6XzcPheK2+YFnOKJB58TDQOyhLRR50qEaw/0i2zl37GevoS3THMIXxh+r7H7N9GFWjNqD5agzqWrOlUro5gp3g0z99mdXM+ZB7Z9Nxcl9Otd4EBYcnBQ4m0Vuh2w+zJKHACxH3UlV8xa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QmCC", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}u_{1} v_{1} + u_{2} v_{2} + u_{3} v_{3}\\end{matrix}\\right]$" + ], + "text/plain": [ + "[u₁⋅v₁ + u₂⋅v₂ + u₃⋅v₃]" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "u = Matrix([u_1,u_2,u_3])\n", + "v = Matrix([v_1,v_2,v_3])\n", + "\n", + "u.T*v" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAALMAAABLCAYAAAA71baHAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAKvUlEQVR4Ae2d3Y3cNhDH9w5+DvIBpIBLB45dQc4dOEkF5+sggZ/sN8PpwHEF/uggSQX56MDJe4AcglSQ/09LyhRFLSkvedLuzgA8UhQ5nP/MiKK04tzZkydP7m42m9+VUvT26dOnX6dOWJ1p4LY1IF98pzEvUuPq3Nmd4MQPKtM4pD/DAyubBhbWwPPE+A9U95D60JlfyLvNeRPasqp1aED++WMsieqo6pz5PD5px6aBQ9WAOfOhWs7kHmnAnHmkEqs4VA2YMx+q5UzukQbMmUcqsYpD1UD4NmMSg54YP9bJR0pfKP0eP1Xq+I3qr5T/q7yIAp6fqcO7kKfKvCL8XvnbImYNGgXyGWanX+lktp3pGuiyqa1LZ+bHEoj30D8pDd71qR4nf6i82JHVHvI8f1V5wFPHnyp9q7QkefkMs6ywh52xoddlU1tnnVkg+IUQISBeUN90pfd/qPvj/WG+lOAZv9++Epe4Ls+4UouEfIZ5a/tZdsYcCV3Gdq1m65Jlxp8SyIP4RvI9i3zmMlEHCJYmtL9W+cuoT47nAHCGV8S6ymFOvqaYHd7HDsmFy2ct4z5ACy0wI0aOb29r4QYrumXyoHxf6Znqvf/pcJqyzixG3fJBOYPgoP2vMG5w6n4Oh1A9szntIc4PKODJLzcDnq7hpdqwrNnkeLn2VbNAvkUw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QvtCsUGDbLuV/W2Bm9ATfSVur7U4d5tCULDPCXdU41LOIKU4b17EvkH7dfj7lbEr8RekTJSjHswfslMEYEMud26CcfE0xC+DBBIGRrLvsjK1yuuxtDe4CfvBM0nmyNqiUM7FtZaMcA+JM/YZT1XElURcHgcG5Xyl5GgTzCHiySXXA03W4VJtDCwJTDbN0cChBYHZixpZzbK3mWX7wnKI7UycS9Wxp4SrrnNudxxkROL7lDo7VpNtZ7fqEWTYwSNh4gfJSmK+FtSSITguVtMCMnFlbx36kPlN+k8Q9x5mZhWMnRcBREBg/koRjebErmMeIp/oAgC3pa6CRfBKqOWbpoL/7OSXg3OHtuqVuWmBG3hHfKVsX+E0S/3myNl0Zrm02GpCHuHtK3sFHQWDUJhfMg76A7EjtKR90EJjamJ2eucCbP/hurTDYHb1x4+9rZ1gX27pAh07UYdY0CIwfyimEnbyjYB46VxQYRO0wKA9Gqw4CUxkzFzf6mQyi48erlUu/PMPMCvbjx1bfnUFbdL7I1qX8aCee/YbW4mWGOrFWZj0V06BO7VBGcTAPtecWukpaErPGxpGzQXRqK64VZuQU70lb69wsv0nhPk9V7lPnlHEjHuGyhDchXAxFwTz2GX+JvrUxi5+fkQkceJckXATQQa+roAaY8Y+9/KZ4Zp6pQWbrDw7mEY7lDMsVzQWx5iAw1TALZ+3gKqFKa5ZrYkauvfgVr5lrasB4mQZqaUCTXb9mrr7MqCWk8TENzNWAOfNcjVn71WogXDPzf+liQd+qjnWMkWlgcQ3IF99JCB6Ok4Qz89Zh6pVJ+EYiycAqTQO3qAE+RJqk/wF9pkTcNA9IsgAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}u_{1} v_{1} & u_{1} v_{2} & u_{1} v_{3}\\\\u_{2} v_{1} & u_{2} v_{2} & u_{2} v_{3}\\\\u_{3} v_{1} & u_{3} v_{2} & u_{3} v_{3}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡u₁⋅v₁ u₁⋅v₂ u₁⋅v₃⎤\n", + "⎢ ⎥\n", + "⎢u₂⋅v₁ u₂⋅v₂ u₂⋅v₃⎥\n", + "⎢ ⎥\n", + "⎣u₃⋅v₁ u₃⋅v₂ u₃⋅v₃⎦" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "u * v.T" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAADgAAAAzCAYAAADCQcvdAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEAklEQVRoBe2a71EbMRDF7UwKIEkHpgMIFcR0EE8qiOkgDJ/sbwzpAEqI6QCng5AOoIMEOkje7zh5dPKd9s53Fj6GndHoz8mr97SrlXTn4Ww22xuUyHw+fyxp3tkm4S3l8UaIb5UegnSxs0yqgS0CDnBaDGXBOxVONAPL6t/274n4TIV6ggVftLy12GkmRupzkvfDz6lfpLR4GwxRglIMoVPljuBA5c9qu1E+UbpWeauiMVphsFwUP57mpBwRt1bPXMOW81YYLIK/Bf4xTxkPkaWeUlphsFwUa73z2XjWvPTbt1XWeK0wWBYs4NZgYzWwR7KtXBUeJqo0xRC1oMMspQcqQ+5ICZf5pZRUNsXQeKPXQERRTg1JomjZLNbBoD6bbfT6IVsDgWahMiE8uTTBEF2DUnRAKmHgXBS33aq0xRAlKOQcxG81yLNYKp+5VhisIIMrLkWQ3JePecVt+v6zrsutMFgET0O0IkuQwaJsFSHxsHsX9VYYzCgqEqyziYd0pHLqw3ZjDMKdRVHLggN1xA1TuKI3h8ViGwxWkCmO1MPaK8EeGq0A+dWChenoYeXFW9DcJnbBaNomRsLBXvhXiTLXtnO1c3WLSi8IigGX7HsRyi7Zyr+p/lOp8LZB9TXpC8HzAPkH1bGmKb0gWOKKnIdrfV4wCUo5Pu8OvNwimDnelZr+r36dSu6aX6T0UuVa74SiUTQnhzJuDqRDKYcYd8Rxp+hrKNOY39Xtk9KxyqxDU6IE9evsDZqvRYqxJtck3sskF43P2GDgRlP2tqGAySKIle6kiPufL9wu9tSO+25VGFvpQckn4+6h7uJdicEiCBHCs1MYKgqJh89b1/OxWff3njImHkw/vLbSYjTISLl/0fUVZLOp56kCDTjONN6fHAQb/WFO3se1Vo4SXOutBimFHK7pImtZt07bNCYTudFkWi5aBpTgcq1BiWg7L40IihQfXFiTVa67c4Rru6hI8RLnvfLjlCw03j9rPPUZVvWpRVAKOBrtK19ZTmXW4UC5H92qxtm4XforwddRarqoBiCoHCkPgwqkCd87LVELihRWIqjwdjv84DlWW5JAo3HYb90n88xzVP+q9qr9WY+fJEpQXW6UUMj6C2WjsB0qqVnnWOb/EYLJ5pvFvvX7KEEpNRVYA3T0fCosfK5zL6A5I9PG16/oRJtrsCOAbdVgPffJrpGuqAUbadpiZ1kpvPtBmP04aj0g9cWCq+nDLVUhgnM3NaVXBEWOgMf6q3XQhn0vXBSgOTlelWQnqbxOe/Sg4QiO1LFwt1Pd3GMYOIUIC5Zja4BgdlVTmXW4OnyE+PUs4+MI8mOSExb1at9xjc+Ys+cBmHwlIuVj5EAyXj18Kiz/A63Ueun6+OEbAAAAAElFTkSuQmCC", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}3 & 3\\\\2 & \\frac{3}{2}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡3 3 ⎤\n", + "⎢ ⎥\n", + "⎣2 3/2⎦" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A = Matrix([\n", + " [3, 3],\n", + " [2, S(3)/2]\n", + "])\n", + "A" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAFYAAAAzCAYAAAANb/8eAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAEEElEQVR4Ae2b21EbMRSGcSYFENIBdMClApwO4kkH0EEyebLfGOiApIIEOsApgXQAqSCEDpLv30ieRViLd4/W3tuZE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BDThQ4zWBQIP3kZ++zMoNVkjcqbwfr2nQn4QFxHbZ3egfk+F/nJVgXA1O28Y5z++Ux2tteSDKwoAlSLcp246xAmO6xQeh/FZAqAp23jL9wxYW9rBVdyiPNpWUKf/niwuhouSAsh7gEt0sKA8uC0AsjvQMbEVfZ7mL+L8ZAbfcw4erA6YMjfatbk8+T/TAug6NzyMw38dnm0QWjMf3gX6J3qkTYRGkx5mf8D+BtEXPJH4RUAAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}-1 & 2\\\\\\frac{4}{3} & -2\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡-1 2 ⎤\n", + "⎢ ⎥\n", + "⎣4/3 -2⎦" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A.inv()" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAADUAAAAzCAYAAAA3v0BtAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAC2ElEQVRoBe1a7U3jQBAFdAUg6CB0wEcFQAeEDu4oI/mHKAGoAIUOoAMEHUAHx6WEe8/n0a2dmbG9Cc4QeaTVfu+8tzO73oyyPZlMdrcUmU6nc6U5VBMwqth3gPIV6U8t3YRCb4OZ1XCTx2wblnpH4Qqsn+2536MHHH4B6ZiW2jj50ZYRduEQY2nuI5R7O2/QJUfhN3QfIN2g7QO5KS4pTOZBvEf6RDpGGiH1JtDP836N/JFKSzyvyM+RTGKu+2HiHGmMdIU1H7hwXwKdPB+7yAtC1IsyPYT1W9YtcUlZk3pqH0PPm6LrBW1nIKhe5xwfmdQZ8NHt6yJux35VQpLyrJCw2EvKlWJIUkAogL1b9lu6X2X3lcq+0lY0RbWUdpaEg1iR3y1VQpIqr24C1lxM2uTCWCAWklSJkm/R0QLi/+fNfKtGJsUnGV8xdTlCw1tizXp/p++UHEzx6YXFVtkA0HdY7xP5hayLMl3vEumntGm5+/bjBCzEHaPIx26GNvrzE3Iq/kqhVfiAPUHOi4H5KeraSwNd/6QNKT5X1iIAP4divjs7SeQz1YlIOnggle5G5PJgqcjWSbENlkp3I3J5sFRk66TYNtJSjc8k7gCeK50DiunOLVuG/kOs0TqQ2kgKC2YFFFdAhC/yrECq634glB1QXAGp7ECqSwrAsgOKy5JaZn4TKf6G0oIgEh9gfzgxScH1JMDhge7lV7AHQOszSWGwAOYPNUvaELfmflm7R6qNUolbtBnb2xiPlHaWBJhY0QwoysB15CYpnClxO83FpE0ujHVgN3WapMoZ2QFFU2MPHU2ksgOKPWA3Vbik4ILZAUVTY16HXEhylt1VGt9+mJ0VUHS1tuzEpmYFUhtJlRdG54BiS9zuMOjOCqS67udqDNw5kApsnAq0wVKV7QhckdtvhJtGnj4F3PLWCwy9iJ1UMANsURf343990j8ySqAlNCmA43dsAfdf2JDTgoeVBLwAAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡1 0⎤\n", + "⎢ ⎥\n", + "⎣0 1⎦" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A * A.inv()" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAADUAAAAzCAYAAAA3v0BtAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAC2ElEQVRoBe1a7U3jQBAFdAUg6CB0wEcFQAeEDu4oI/mHKAGoAIUOoAMEHUAHx6WEe8/n0a2dmbG9Cc4QeaTVfu+8tzO73oyyPZlMdrcUmU6nc6U5VBMwqth3gPIV6U8t3YRCb4OZ1XCTx2wblnpH4Qqsn+2536MHHH4B6ZiW2jj50ZYRduEQY2nuI5R7O2/QJUfhN3QfIN2g7QO5KS4pTOZBvEf6RDpGGiH1JtDP836N/JFKSzyvyM+RTGKu+2HiHGmMdIU1H7hwXwKdPB+7yAtC1IsyPYT1W9YtcUlZk3pqH0PPm6LrBW1nIKhe5xwfmdQZ8NHt6yJux35VQpLyrJCw2EvKlWJIUkAogL1b9lu6X2X3lcq+0lY0RbWUdpaEg1iR3y1VQpIqr24C1lxM2uTCWCAWklSJkm/R0QLi/+fNfKtGJsUnGV8xdTlCw1tizXp/p++UHEzx6YXFVtkA0HdY7xP5hayLMl3vEumntGm5+/bjBCzEHaPIx26GNvrzE3Iq/kqhVfiAPUHOi4H5KeraSwNd/6QNKT5X1iIAP4divjs7SeQz1YlIOnggle5G5PJgqcjWSbENlkp3I3J5sFRk66TYNtJSjc8k7gCeK50DiunOLVuG/kOs0TqQ2kgKC2YFFFdAhC/yrECq634glB1QXAGp7ECqSwrAsgOKy5JaZn4TKf6G0oIgEh9gfzgxScH1JMDhge7lV7AHQOszSWGwAOYPNUvaELfmflm7R6qNUolbtBnb2xiPlHaWBJhY0QwoysB15CYpnClxO83FpE0ujHVgN3WapMoZ2QFFU2MPHU2ksgOKPWA3Vbik4ILZAUVTY16HXEhylt1VGt9+mJ0VUHS1tuzEpmYFUhtJlRdG54BiS9zuMOjOCqS67udqDNw5kApsnAq0wVKV7QhckdtvhJtGnj4F3PLWCwy9iJ1UMANsURf343990j8ySqAlNCmA43dsAfdf2JDTgoeVBLwAAAAASUVORK5CYII=", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\0 & 1\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡1 0⎤\n", + "⎢ ⎥\n", + "⎣0 1⎦" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A.inv() * A" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAFYAAAAzCAYAAAANb/8eAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAESElEQVR4Ae1c7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yBKSdL7BqtKHeeqnb2jzbx3wAE7CtHYgcvUzcLtEUvfqgSqHD1cVML5NX3U2bsK3FGaAvto3eYBSpWHZrA+LmX1lcX2C3XN43CCCTp7D5g7tksU9hjdPIvVSw+qoHlhA0DoT4PP3lXojtKk2Ifq5lnsEkoHXdjAxFx6g87ed0Soik2GfYxuJrEQyOWuPlUBt1KZePDZe0tQwopU2MfqZhIboqdMPOrsPUT+Lvt42L12C1s0sRBunr0LOD7QFoitewcWuD20mdgxv9feCzHfK+ilZlwDDCnfKxhHXdgob7sVJiX3ajGgPpa+r/Yej3LxAtAakStqDDR5Q2PBo1osn+rVfwbB/WgOYQzwpanF3T/jET7Q4xtb6QAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle \\left[\\begin{matrix}b_{11} & b_{12}\\\\b_{21} & b_{22}\\end{matrix}\\right]$" + ], + "text/plain": [ + "⎡b₁₁ b₁₂⎤\n", + "⎢ ⎥\n", + "⎣b₂₁ b₂₂⎦" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "B = Matrix([\n", + " [b_11, b_12],\n", + " [b_21, b_22]])\n", + "B" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAE0AAAASCAYAAAAe0VOSAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACRElEQVRYCdWY4VECMRCFD4cCHO0AOxCtQO1A7QDoQMZ//NUO1AoUO9AOVEqgA5UO8H0xy+S8g4BOxsvOZJLdTS773mX3Aq35fF6MRqPtoijGagdqH9L31GcrqfFswYw2mamdaDhVe8aWs6TG40gLCNrX+CnQ/20o4Mdq/T8GkATPgjSC9AE25aRRMmi/kpR4FqQpMpee2mz2qyibtygZnnaAlZM2EWkX3nao/l76YzAnp2EyPO6kiRjSgPzvqN1Kv1bfUxtrjC0rSY3H0tPq2ZE2dOnpe8anWTH2HWxSPG1PCPlPav6sZ5zAXT+nkB/9XG2gcdfs1sf8Ni/steZGuoEMXTso8g9Cox8T61mN3UxRPFoPlku/wLKpJ7vjYJXfSCPoUu3SIgPywoOlk75mY8OSxPylyYGidXWksB8nvKOeUrGpRPHogVfh3hrz8t7U7GK/1G/pCdOOHPUm9ibdFUQP5e0CgAtwRWL+yoK0higebd9XzHYIiOZKjZfE4UCW+o00Ji3I0MIwDd1xZUJmEsPDCX9dgWmpv+0XkZr87px4nd+hDyLv1uu5dVE8NdggaSq742CV30jjenGnieQzp4yrRq6EKXx3XVobj7CSktTQyseNh/30O9JkJAWthjEva9kEj+ZS/6hnXb+uhL3ObyetNLEhCi8yaT31hAzVc0UpvE7v6qHXK/7GkqaAk/5x4AnhmgEp9sWkrg0DAmv9Lf6EXEf8Jjz0WI1NuH68y+7uUTG/5jZKFO+nAqJ+l0T2FoZV/i8xjhrmreLFLgAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle b_{11} + b_{22}$" + ], + "text/plain": [ + "b₁₁ + b₂₂" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "B.trace()" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIEAAAASCAYAAAB8Ur29AAAACXBIWXMAAA7EAAAOxAGVKw4bAAADE0lEQVRoBdVZ7XETMRA9Z1IAM3QQOiBQAUkHhA5MSsjwz39DB4QKIHSQUAFJSkgHQDow7x27Nz7fx5OMVgmakfWxq3379taSzl6s1+tmtVo9a5rmEvUV6i+MX6AtXmrhFHd8wmBNPpFYe+QHgAfUY3TvUa85F1Fq4UT4PmazJp9IrDYJNgi+RP9qYxzVrYUT5f+23Zp8imN1SYBMOzJmYTsB7dfC2X5KUeOafKKwuiRAkNrjAEAPUQEzu7Vwgml05mvyCcFa8GLIgod/i4Z3gh8co7xG/YL5b+2o0EctnELuSjM1+URh+cWQbwc8aw5QLwD2Ee0S9RJ9zhUpsFUFp4izCUZq8onE8uPA7wNvANYeB9ay/zYhHqkqtXBS/flXvZp8wrD2LQo8a+48ATYiw2/ucx9bNr7D+BT9Q5/3VsmhJ3HMxgez6bvQEvOenPRpUu6+jLVm+ztktJFaTrDubkJZ8uE6wx2Nm8lS+EisFFtjvngSMMt6Zz+UPfPaOwLGPC58bhBEJWcwUCQOdM5h67TVxgf6n9DwvuI/YCm5Lx20sMVEGiTvQDF9QvIB5mzcAJXKR2IpW1O++HHAb5xfCD0EJ9ZpXxlhgDsF7wq8PA6KktsCiQO997DlycZl56gHmGMwWZT8r1adT8knIS6pfCSWis2UL3sbseoeLpT5Tffti9+ekkXhcBe4mQFU8pmlISLFR4Hm8FFYObY6v/atx6OA/xv42cf/Eb4iGS5MXqqROCOYJHbPLKYTSl7K0UQ7ko+yk8FHYmXY6rnlSbDE7GcY4bnLXYCvhqUTgMBZOPCBRwDfTkbPcSUnYHDJ4qN8EXyysIStnittEmABt3y/A/QUSg5ycKDLM5D3gUNb13NFyXvKQYMcPsoFxScHS9na9sV3gu35Rx0biTO0x3TExmzbM9HGk/JHdX4H8JJ8drH15JLASPC1kA/Z3wh4LzhjfJWcOv9TKclnV1vdfwcqcAbAh3GEyofD18WfmGfbKDl1Ugrs/IYe7yW9gvkFJ5S8t+gJDOAvj7W5uM3yzaGgYjPlyx9Gchcaf0Wp+wAAAABJRU5ErkJggg==", + "text/latex": [ + "$\\displaystyle b_{11} b_{22} - b_{12} b_{21}$" + ], + "text/plain": [ + "b₁₁⋅b₂₂ - b₁₂⋅b₂₁" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "B.det()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.4" + }, + "widgets": { + "state": {}, + "version": "1.1.1" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/jupyter/math/eseries_37d1f4.ipynb b/jupyter/math/eseries_37d1f4.ipynb new file mode 100644 index 0000000..48e8154 --- /dev/null +++ b/jupyter/math/eseries_37d1f4.ipynb @@ -0,0 +1,638 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# QuTiP example: eseries" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "J.R. Johansson and P.D. Nation\n", + "\n", + "For more information about QuTiP see [http://qutip.org](http://qutip.org)" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "from numpy import pi" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "from qutip import *" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example eseries object: $\\sigma_x \\exp(i\\omega t)$" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "omega = 1.0\n", + "es1 = eseries(sigmax(), 1j * omega)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 1 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = 1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example eseries object: $\\sigma_x \\cos(\\omega t)$" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "omega = 1.0\n", + "es2 = eseries(0.5 * sigmax(), 1j * omega) + eseries(0.5 * sigmax(), -1j * omega)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 2 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = 1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0.5]\n", + " [ 0.5 0. ]]\n", + "Exponent #1 = -1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0.5]\n", + " [ 0.5 0. ]]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Evaluate eseries object at time $t = 0$" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 1.0\\\\1.0 & 0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "esval(es2, 0.0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Evaluate eseries object at array of times $t = [0, \\pi, 2\\pi]$" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([ Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]],\n", + " Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. -1.]\n", + " [-1. 0.]],\n", + " Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]], dtype=object)" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tlist = [0.0, 1.0 * pi, 2.0 * pi]\n", + "esval(es2, tlist)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Expectation values of eseries" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 2 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = 1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0.5]\n", + " [ 0.5 0. ]]\n", + "Exponent #1 = -1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 0.5]\n", + " [ 0.5 0. ]]" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es2" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 2 terms\n", + "Hilbert space dimensions: [[1, 1]]\n", + "Exponent #0 = 1j\n", + "1.0\n", + "Exponent #1 = -1j\n", + "1.0" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "expect(sigmax(), es2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Arithmetics with eseries" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 1 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = 1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es1 = eseries(sigmax(), 1j * omega)\n", + "es1" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 1 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = -1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es2 = eseries(sigmax(), -1j * omega)\n", + "es2" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 2 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = 1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]\n", + "Exponent #1 = -1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es1 + es2" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 2 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = 1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]\n", + "Exponent #1 = -1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. -1.]\n", + " [-1. 0.]]" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es1 - es2" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 1 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = 0j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 1. 0.]\n", + " [ 0. 1.]]" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es1 * es2" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 2 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = 2j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 1. 0.]\n", + " [ 0. 1.]]\n", + "Exponent #1 = -2j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[-1. 0.]\n", + " [ 0. -1.]]" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "(es1 + es2) * (es1 - es2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Expectation values of eseries" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 2 terms\n", + "Hilbert space dimensions: [[2], [2]]\n", + "Exponent #0 = (-0-1j)\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = False\n", + "Qobj data =\n", + "[[ 0.5+0.j 0.0+0.5j]\n", + " [ 0.0+0.5j -0.5+0.j ]]\n", + "Exponent #1 = 1j\n", + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = False\n", + "Qobj data =\n", + "[[ 0.5+0.j 0.0-0.5j]\n", + " [ 0.0-0.5j -0.5+0.j ]]" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es3 = eseries([0.5*sigmaz(), 0.5*sigmaz()], [1j, -1j]) + eseries([-0.5j*sigmax(), \n", + " 0.5j*sigmax()], [1j, -1j])\n", + "es3" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}1.0 & 0.0\\\\0.0 & -1.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 1. 0.]\n", + " [ 0. -1.]]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es3.value(0.0)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\\begin{equation*}\\left(\\begin{array}{*{11}c}0.0 & 1.0\\\\1.0 & 0.0\\\\\\end{array}\\right)\\end{equation*}" + ], + "text/plain": [ + "Quantum object: dims = [[2], [2]], shape = (2, 2), type = oper, isherm = True\n", + "Qobj data =\n", + "[[ 0. 1.]\n", + " [ 1. 0.]]" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es3.value(pi/2)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "ESERIES object: 2 terms\n", + "Hilbert space dimensions: [[1, 1]]\n", + "Exponent #0 = (-0-1j)\n", + "(-0.5+0j)\n", + "Exponent #1 = 1j\n", + "(-0.5+0j)" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "rho = fock_dm(2, 1)\n", + "es3_expect = expect(rho, es3)\n", + "\n", + "es3_expect" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([ -1.00000000e+00, -6.12323400e-17])" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "es3_expect.value([0.0, pi/2])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Versions" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
SoftwareVersion
QuTiP4.2.0
Numpy1.13.1
SciPy0.19.1
matplotlib2.0.2
Cython0.25.2
Number of CPUs2
BLAS InfoINTEL MKL
IPython6.1.0
Python3.6.1 |Anaconda custom (x86_64)| (default, May 11 2017, 13:04:09) \n", + "[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
OSposix [darwin]
Wed Jul 19 22:16:28 2017 MDT
" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from qutip.ipynbtools import version_table\n", + "\n", + "version_table()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/jupyter/math/handcalc_quarto_578f98.ipynb b/jupyter/math/handcalc_quarto_578f98.ipynb new file mode 100644 index 0000000..979713d --- /dev/null +++ b/jupyter/math/handcalc_quarto_578f98.ipynb @@ -0,0 +1,683 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "663b02fd-d873-4d42-8026-62742e54765c", + "metadata": {}, + "source": [ + "---\n", + "title: \"My Document\"\n", + "execute:\n", + " echo: false\n", + " cache: true\n", + "format:\n", + " html:\n", + " html-math-method: katex\n", + " embed-resources: true\n", + " self-contained-math: true\n", + " toc: true\n", + " docx:\n", + " df-print: tibble\n", + " pdf:\n", + " toc: true\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "d035b47e-1dfd-4e8e-a2c0-650fb3804bf6", + "metadata": {}, + "source": [ + "# Weave Test" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "a4a67a02-024b-4eb3-9848-a5990783dd62", + "metadata": {}, + "outputs": [], + "source": [ + "using Handcalcs, BridgeCalcsUS\n", + "using Latexify, LaTeXStrings\n", + "using Unitful, UnitfulLatexify\n", + "using Format" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "c6e5e48f", + "metadata": {}, + "outputs": [], + "source": [ + "import TestHandcalcFunctions: calc_Ix, calc_Iy" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "b3609683-6db8-41f5-a74b-92ac170e739f", + "metadata": {}, + "outputs": [], + "source": [ + "const inch = u\"inch\"\n", + "const ft = u\"ft\";" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "b3bf7314", + "metadata": {}, + "outputs": [], + "source": [ + "set_default(fmt = x->format(round(x, digits=4)));" + ] + }, + { + "cell_type": "markdown", + "id": "18dbc744-817e-4178-813d-59b487dcb233", + "metadata": {}, + "source": [ + "## Rectangle Properties" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "1e93c8fa-7501-47c5-9dbd-953104822764", + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\begin{aligned}\n", + "b &= 5\\;\\text{ }(\\text{base})\n", + "\\\\[10pt]\n", + "h &= 12\\;\\text{ }(\\text{height})\n", + "\\end{aligned}$" + ], + "text/plain": [ + "L\"$\\begin{aligned}\n", + "b &= 5\\;\\text{ }(\\text{base})\n", + "\\\\[10pt]\n", + "h &= 12\\;\\text{ }(\\text{height})\n", + "\\end{aligned}$\"" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "@handcalcs begin\n", + " b = 5; \"base\";\n", + " h = 12; \"height\";\n", + "end" + ] + }, + { + "cell_type": "markdown", + "id": "53241f31-7f40-434f-9440-c49060495e5a", + "metadata": {}, + "source": [ + "### Calculate Ix" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "d48d8b86-a40c-423b-9925-dbdece39671b", + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\begin{aligned}\n", + "I_{x} &= \\frac{b \\cdot h^{3}}{12} = \\frac{5 \\cdot 12^{3}}{12} = 720.0\n", + "\\end{aligned}$" + ], + "text/plain": [ + "L\"$\\begin{aligned}\n", + "I_{x} &= \\frac{b \\cdot h^{3}}{12} = \\frac{5 \\cdot 12^{3}}{12} = 720.0\n", + "\\end{aligned}$\"" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "@handcalcs begin\n", + " I_x = b*h^3/12\n", + "end" + ] + }, + { + "cell_type": "markdown", + "id": "21f163cc-f3c7-4b99-9108-38eeebfb4f01", + "metadata": {}, + "source": [ + "### Calculate Area" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "c1780a43-f694-45b6-ab9f-8e20607fcc49", + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\begin{aligned}\n", + "area &= b \\cdot h = 5 \\cdot 12 = 60\n", + "\\end{aligned}$" + ], + "text/plain": [ + "L\"$\\begin{aligned}\n", + "area &= b \\cdot h = 5 \\cdot 12 = 60\n", + "\\end{aligned}$\"" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "@handcalcs begin\n", + " area = b*h\n", + "end" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "e6d94e6f", + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\begin{aligned}\n", + "P_{e} &= \\frac{\\pi^{2} \\cdot E}{\\left( \\frac{K \\cdot l}{r_{s}} \\right)^{2}} \\cdot A_{g} = \\frac{3.1416^{2} \\cdot 29000}{\\left( \\frac{1 \\cdot 408}{2.12} \\right)^{2}} \\cdot 19.7 = 152.2353\\;\\text{ }(\\text{AASHTO 6.9.4.1.2-1})\n", + "\\end{aligned}$" + ], + "text/plain": [ + "L\"$\\begin{aligned}\n", + "P_{e} &= \\frac{\\pi^{2} \\cdot E}{\\left( \\frac{K \\cdot l}{r_{s}} \\right)^{2}} \\cdot A_{g} = \\frac{3.1416^{2} \\cdot 29000}{\\left( \\frac{1 \\cdot 408}{2.12} \\right)^{2}} \\cdot 19.7 = 152.2353\\;\\text{ }(\\text{AASHTO 6.9.4.1.2-1})\n", + "\\end{aligned}$\"" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "@handfunc P_e = A6_9_4_1_2d1(29000, 19.7, 1.0, 408, 2.12) " + ] + }, + { + "cell_type": "markdown", + "id": "07b35feb-77df-4ec0-b6da-7cedba19888b", + "metadata": {}, + "source": [ + "## Example Plot" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "c396e5ea", + "metadata": {}, + "outputs": [], + "source": [ + "using Plots" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "e5de1657-fe9c-455e-afa1-d55321da581c", + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAIAAAD9V4nPAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nO3deWAM5/8H8M88s5tEDrcglxzIIW4pWmdQ91FXi35p6+xB0dKWqqtVvnppq24trfarResqVUfdirpChCCuEFfkQGSz8zy/P9Yv1Qpy7O7M7LxffyVrZT+Zncx7n3kuSQhBAAAARsXULgAAAEBNCEIAADA0BCEAABgaghAAAAwNQQgAAIaGIAQAAENDEAIAgKEhCAEAwNAQhAAAYGgIQgAAMDQnBeHx48fnzZvnnNdyNM4551ztKnQpJyd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+bNu2bfPmzWpXoT8pKSlz5sxRuwqnQhACAIChIQgBAMDQEIQAAGBokhD/XorCEWbMmPHuu+/6+vo64bUc7ebNm5IkFXrJBsPKycm5cuWK4xZJcmHJycm+vr5ms243PFRJWlqaEAKTmwvKarVevnw5MDBQ7ULso3fv3pMnT370c5wUhJzzxMRE1/hLVhSFiGRZVrsQ/cnOzjbI0GL7wnErHPypFpornXIVK1YsVuwxi807KQgBAAC0CX2EAABgaAhCAAAwNAQhAAAYGoIQAAAMrUiLbgMRZWVlffvttzVr1qxfv77atehDenr6mjVrjhw54unp2blz51q1aqldkaatXLly69atAQEBAwcOxK6E+XT9+vXVq1fHx8eXKFGie/fuERERalekM6dPn960aVPbtm1dZhLFo6FFWFTjx48fNWrUihUr1C5EN8aPH/+///2vTJky2dnZjRs3xqF7hE8//XTkyJFhYWE7d+5s0aIF51ztivRh+PDhv/76a4UKFW7cuFG3bl0svV0giqL069dvxIgRx44dU7sWJ0GLsEj27t27Y8eOzp07q12InkydOtXDw8P2taen5+zZs7t27apuSdqUk5Mzffr0JUuWNG/efPDgwVWqVPn9999bt26tdl06MH/+/NxzTFGU+fPnN23aVN2SdOSTTz5p1KjRhQsX1C7EedAiLDyLxTJ48OCvvvoKM3YLJPcKRUR379719vZWsRgtO3nyZGpqapMmTYjIZDI1b94cLZt8+tc55uXlpWIx+nLy5Mlvvvlm3LhxahfiVGgRFt7777/fsWNHdHEVWmJi4pdffrlu3Tq1C9GolJSUMmXK5H7MKl++/KVLl9QtSXf279+/dOnSP//8U+1C9IFzPnDgwBkzZhjtowNahI/SuHFj0wP69etHREeOHFmxYsWYMWPUrlGLjh49+uBxM5lM27dvz31OcnJy27Zt33vvvYYNG6pYqpaZTCar1Zr7bU5OjsuseuUciYmJzzzzzOzZszFYJp9mzpxZuXLlli1bql2Is6FF+Cj3X7j/ZenSpTdv3mzUqBERnT171mw2X79+HRvP2kRHR99/BX9QSkpKy5YtBw0aNHLkSKdVpTt+fn6pqalZWVm2lRKTk5PDw8PVLko3zpw507Jly0mTJvXq1UvtWnTj+++/v3nzZr169YgoJSVl2LBhI0aMePnll9Wuy+Gw1mghJScnp6Sk2L6eMGFC6dKlx4wZg+tUfly7di02NvbZZ59999131a5F04QQ1apVGzduXK9evdLS0ipXrrxhw4Y6deqoXZcOnD9/vnnz5m+++aYRLuJ2lJCQcPv2bdvXHTp0GDt2bNeuXf38/NStygkQhHbw4osv+vr6Tps2Te1C9GHgwIGLFi2qUaOG7dugoCDMoHiY1atXv/TSSx06dNi7d2/dunUXL16sdkX60Llz540bN0ZGRtq+rVWr1vz589UtSXcqVao0Z86cNm3aqF2IMyAI7cB2a9Tf31/tQvTh7NmzN27cyP3Ww8OjWrVqKtajcWfPnt29e3dAQECjRo0kSVK7HH1ITEzMyMjI/dbb2xt3awoqLi6uUqVKxYsXV7sQZ0AQAgCAoWHUKAAAGBqCEAAADA1BCAAAhoYgBAAAQ0MQAgCAoSEIAQDA0BCEAABgaAhCAAAwNAQhAAAYGoIQAAAMDUEIAACG9n/dSouaf7YNzgAAAABJRU5ErkJggg==", + "image/svg+xml": [ + "\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ], + "text/html": [ + "\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + "\n", + " \n", + " \n", + " \n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "#| label: fig-parametric\n", + "#| fig-cap: \"Parametric Plots\"\n", + "f(x) = x^2\n", + "plot(f)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "ff71d62f-7035-498b-b227-a911875bb908", + "metadata": {}, + "outputs": [ + { + "data": { + "text/latex": [ + "$\\begin{aligned}\n", + "c &= \\begin{cases}\n", + "a + b & \\text{if } \\left( h < 6 \\right)\\\\\n", + "a - b & \\text{otherwise}\n", + "\\end{cases} = \\begin{cases}\n", + "\\left[\n", + "\\begin{array}{c}\n", + "1 \\\\\n", + "2 \\\\\n", + "3 \\\\\n", + "\\end{array}\n", + "\\right] + \\left[\n", + "\\begin{array}{c}\n", + "4 \\\\\n", + "5 \\\\\n", + "7 \\\\\n", + "\\end{array}\n", + "\\right] & \\text{if } \\left( 12 < 6 \\right)\\\\\n", + "\\left[\n", + "\\begin{array}{c}\n", + "1 \\\\\n", + "2 \\\\\n", + "3 \\\\\n", + "\\end{array}\n", + "\\right] - \\left[\n", + "\\begin{array}{c}\n", + "4 \\\\\n", + "5 \\\\\n", + "7 \\\\\n", + "\\end{array}\n", + "\\right] & \\text{otherwise}\n", + "\\end{cases} = \\left[\n", + "\\begin{array}{c}\n", + "-3 \\\\\n", + "-3 \\\\\n", + "-4 \\\\\n", + "\\end{array}\n", + "\\right]\n", + "\\end{aligned}$" + ], + "text/plain": [ + "L\"$\\begin{aligned}\n", + "c &= \\begin{cases}\n", + "a + b & \\text{if } \\left( h < 6 \\right)\\\\\n", + "a - b & \\text{otherwise}\n", + "\\end{cases} = \\begin{cases}\n", + "\\left[\n", + "\\begin{array}{c}\n", + "1 \\\\\n", + "2 \\\\\n", + "3 \\\\\n", + "\\end{array}\n", + "\\right] + \\left[\n", + "\\begin{array}{c}\n", + "4 \\\\\n", + "5 \\\\\n", + "7 \\\\\n", + "\\end{array}\n", + "\\right] & \\text{if } \\left( 12 < 6 \\right)\\\\\n", + "\\left[\n", + "\\begin{array}{c}\n", + "1 \\\\\n", + "2 \\\\\n", + "3 \\\\\n", + "\\end{array}\n", + "\\right] - \\left[\n", + "\\begin{array}{c}\n", + "4 \\\\\n", + "5 \\\\\n", + "7 \\\\\n", + "\\end{array}\n", + "\\right] & \\text{otherwise}\n", + "\\end{cases} = \\left[\n", + "\\begin{array}{c}\n", + "-3 \\\\\n", + "-3 \\\\\n", + "-4 \\\\\n", + "\\end{array}\n", + "\\right]\n", + "\\end{aligned}$\"" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "a = [1;2;3]\n", + "b = [4;5;7]\n", + "@handcalcs begin\n", + "c = if h<6\n", + " a + b\n", + " else\n", + " a - b\n", + " end\n", + "end" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "6a67d4a3-d87f-4ebd-a3dd-6005e84b66d2", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "e5ed00c9-3906-485e-a3a0-6538c456a86e", + "metadata": {}, + "outputs": [], + "source": [ + "using Tidier, RDatasets" + ] + }, + { + "cell_type": "markdown", + "id": "c2c42d34-74c3-4a6d-a1a9-a7813d7b302f", + "metadata": {}, + "source": [ + "## Large Dataset" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "deb64018-48a3-4915-b202-f637b19f5403", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "data": { + "text/html": [ + "
4406×19 DataFrame
4381 rows omitted
RowOFPOFNPOPPOPNPEMRHospNumChronAdlDiffAgeBlackSexMarriedSchoolFamIncEmployedPrivinsMedicaidRegionHlth
Int32Int32Int32Int32Int32Int32Int32Int32Float64Cat…Cat…Cat…Int32Float64Cat…Cat…Cat…Cat…Cat…
1500001206.9yesmaleyes62.881yesyesnootherother
2102020207.4nofemaleyes102.7478noyesnootherother
31300033416.6yesfemaleno100.6532nonoyesotherpoor
41605011217.6nomaleyes30.6588noyesnootherpoor
5300000217.9nofemaleyes60.6588noyesnootherother
61700000516.6nofemaleno70.3301nonoyesotherpoor
7900000007.5nofemaleno80.828noyesnomidwestother
8300000008.7nofemaleno83.0456noyesnomidwestother
9100000007.3nofemaleno83.0456noyesnomidwestother
10000000007.8nofemaleno83.0456noyesnomidwestother
11000000106.6nomaleyes82.9498yesyesnomidwestother
124452001516.9nofemaleyes152.9498noyesnomidwestother
13200000118.4nofemaleno80.8988nononomidwestother
4395200000008.8nofemaleno121.06noyesnootherexcellent
4396100000318.2nofemaleno163.47nononootherpoor
4397200010007.1nomaleyes122.22yesyesnootherother
4398200000107.0nofemaleyes122.22noyesnootherother
43991101001218.4nomaleyes41.9539noyesnootherother
4400200000107.6nofemaleyes81.9539noyesnootherother
44011241000308.2nomaleyes72.2497noyesnootherother
44021100000008.4nofemaleyes82.2497noyesnootherother
44031200000207.8nofemaleno115.8132noyesnootherother
440410020011507.3nomaleyes123.87792noyesnootherother
44051610000006.6nofemaleyes123.87792noyesnootherother
4406000000007.1nomaleyes06.5968yesnonootherexcellent
" + ], + "text/latex": [ + "\\begin{tabular}{r|cccccccccccc}\n", + "\t& OFP & OFNP & OPP & OPNP & EMR & Hosp & NumChron & AdlDiff & Age & Black & Sex & \\\\\n", + "\t\\hline\n", + "\t& Int32 & Int32 & Int32 & Int32 & Int32 & Int32 & Int32 & Int32 & Float64 & Cat… & Cat… & \\\\\n", + "\t\\hline\n", + "\t1 & 5 & 0 & 0 & 0 & 0 & 1 & 2 & 0 & 6.9 & yes & male & $\\dots$ \\\\\n", + "\t2 & 1 & 0 & 2 & 0 & 2 & 0 & 2 & 0 & 7.4 & no & female & $\\dots$ \\\\\n", + "\t3 & 13 & 0 & 0 & 0 & 3 & 3 & 4 & 1 & 6.6 & yes & female & $\\dots$ \\\\\n", + "\t4 & 16 & 0 & 5 & 0 & 1 & 1 & 2 & 1 & 7.6 & no & male & $\\dots$ \\\\\n", + "\t5 & 3 & 0 & 0 & 0 & 0 & 0 & 2 & 1 & 7.9 & no & female & $\\dots$ \\\\\n", + "\t6 & 17 & 0 & 0 & 0 & 0 & 0 & 5 & 1 & 6.6 & no & female & $\\dots$ \\\\\n", + "\t7 & 9 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7.5 & no & female & $\\dots$ \\\\\n", + "\t8 & 3 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 8.7 & no & female & $\\dots$ \\\\\n", + "\t9 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7.3 & no & female & $\\dots$ \\\\\n", + "\t10 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7.8 & no & female & $\\dots$ \\\\\n", + "\t11 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 6.6 & no & male & $\\dots$ \\\\\n", + "\t12 & 44 & 5 & 2 & 0 & 0 & 1 & 5 & 1 & 6.9 & no & female & $\\dots$ \\\\\n", + "\t13 & 2 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 8.4 & no & female & $\\dots$ \\\\\n", + "\t14 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 8.1 & no & female & $\\dots$ \\\\\n", + "\t15 & 19 & 0 & 1 & 2 & 0 & 1 & 1 & 0 & 7.8 & no & female & $\\dots$ \\\\\n", + "\t16 & 19 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7.6 & no & female & $\\dots$ \\\\\n", + "\t17 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 8.3 & no & male & $\\dots$ \\\\\n", + "\t18 & 3 & 9 & 1 & 0 & 0 & 0 & 2 & 1 & 8.0 & no & female & $\\dots$ \\\\\n", + "\t19 & 2 & 0 & 0 & 0 & 0 & 0 & 3 & 0 & 7.3 & yes & male & $\\dots$ \\\\\n", + "\t20 & 12 & 0 & 2 & 0 & 0 & 0 & 4 & 0 & 7.4 & no & male & $\\dots$ \\\\\n", + "\t21 & 2 & 0 & 1 & 0 & 1 & 2 & 1 & 0 & 6.7 & no & male & $\\dots$ \\\\\n", + "\t22 & 3 & 0 & 1 & 0 & 0 & 0 & 2 & 0 & 7.3 & no & male & $\\dots$ \\\\\n", + "\t23 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 7.5 & no & female & $\\dots$ \\\\\n", + "\t24 & 1 & 0 & 0 & 0 & 0 & 0 & 2 & 0 & 7.1 & no & female & $\\dots$ \\\\\n", + "\t$\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & $\\dots$ & \\\\\n", + "\\end{tabular}\n" + ], + "text/plain": [ + "\u001b[1m4406×19 DataFrame\u001b[0m\n", + "\u001b[1m Row \u001b[0m│\u001b[1m OFP \u001b[0m\u001b[1m OFNP \u001b[0m\u001b[1m OPP \u001b[0m\u001b[1m OPNP \u001b[0m\u001b[1m EMR \u001b[0m\u001b[1m Hosp \u001b[0m\u001b[1m NumChron \u001b[0m\u001b[1m AdlDiff \u001b[0m\u001b[1m Age \u001b[0m\u001b[1m \u001b[0m ⋯\n", + " │\u001b[90m Int32 \u001b[0m\u001b[90m Int32 \u001b[0m\u001b[90m Int32 \u001b[0m\u001b[90m Int32 \u001b[0m\u001b[90m Int32 \u001b[0m\u001b[90m Int32 \u001b[0m\u001b[90m Int32 \u001b[0m\u001b[90m Int32 \u001b[0m\u001b[90m Float64 \u001b[0m\u001b[90m \u001b[0m ⋯\n", + "──────┼─────────────────────────────────────────────────────────────────────────\n", + " 1 │ 5 0 0 0 0 1 2 0 6.9 ⋯\n", + " 2 │ 1 0 2 0 2 0 2 0 7.4\n", + " 3 │ 13 0 0 0 3 3 4 1 6.6\n", + " 4 │ 16 0 5 0 1 1 2 1 7.6\n", + " 5 │ 3 0 0 0 0 0 2 1 7.9 ⋯\n", + " 6 │ 17 0 0 0 0 0 5 1 6.6\n", + " 7 │ 9 0 0 0 0 0 0 0 7.5\n", + " 8 │ 3 0 0 0 0 0 0 0 8.7\n", + " ⋮ │ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋱\n", + " 4400 │ 2 0 0 0 0 0 1 0 7.6 ⋯\n", + " 4401 │ 12 4 1 0 0 0 3 0 8.2\n", + " 4402 │ 11 0 0 0 0 0 0 0 8.4\n", + " 4403 │ 12 0 0 0 0 0 2 0 7.8\n", + " 4404 │ 10 0 20 0 1 1 5 0 7.3 ⋯\n", + " 4405 │ 16 1 0 0 0 0 0 0 6.6\n", + " 4406 │ 0 0 0 0 0 0 0 0 7.1\n", + "\u001b[36m 10 columns and 4391 rows omitted\u001b[0m" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "ofp = dataset(\"Ecdat\", \"OFP\")" + ] + }, + { + "cell_type": "markdown", + "id": "b78ec6e1-c33a-42b9-b007-796a78e97531", + "metadata": {}, + "source": [ + "## Small Dataset" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "fb33a2f8-a9ac-4afa-8148-cbfa728eb874", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "data": { + "text/html": [ + "
4×2 DataFrame
Rowregionmean_age
Cat…Float64
1other73.987
2midwest74.0769
3noreast73.9343
4west74.1165
" + ], + "text/latex": [ + "\\begin{tabular}{r|cc}\n", + "\t& region & mean\\_age\\\\\n", + "\t\\hline\n", + "\t& Cat… & Float64\\\\\n", + "\t\\hline\n", + "\t1 & other & 73.987 \\\\\n", + "\t2 & midwest & 74.0769 \\\\\n", + "\t3 & noreast & 73.9343 \\\\\n", + "\t4 & west & 74.1165 \\\\\n", + "\\end{tabular}\n" + ], + "text/plain": [ + "\u001b[1m4×2 DataFrame\u001b[0m\n", + "\u001b[1m Row \u001b[0m│\u001b[1m region \u001b[0m\u001b[1m mean_age \u001b[0m\n", + " │\u001b[90m Cat… \u001b[0m\u001b[90m Float64 \u001b[0m\n", + "─────┼───────────────────\n", + " 1 │ other 73.987\n", + " 2 │ midwest 74.0769\n", + " 3 │ noreast 73.9343\n", + " 4 │ west 74.1165" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "ofp = @clean_names(ofp)\n", + "ofp_mean = @chain ofp begin\n", + " @group_by(region)\n", + " @summarize(mean_age = mean(age*10))\n", + "end" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "ef80f05f-8fe0-486e-8fb8-72f248cd67c3", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "using PrettyTables" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "fd44f931-69a5-4993-bd98-5b32aeaf37b1", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "┌─────────────────────────────────┬──────────┐\n", + "│\u001b[1m region \u001b[0m│\u001b[1m mean_age \u001b[0m│\n", + "│\u001b[90m CategoricalValue{String, UInt8} \u001b[0m│\u001b[90m Float64 \u001b[0m│\n", + "├─────────────────────────────────┼──────────┤\n", + "│ other │ 73.987 │\n", + "│ midwest │ 74.0769 │\n", + "│ noreast │ 73.9343 │\n", + "│ west │ 74.1165 │\n", + "└─────────────────────────────────┴──────────┘\n" + ] + } + ], + "source": [ + "pretty_table(ofp_mean)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Julia 1.10.2", + "language": "julia", + "name": "julia-1.10" + }, + "language_info": { + "file_extension": ".jl", + "mimetype": "application/julia", + "name": "julia", + "version": "1.10.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/jupyter/math/latexify_examples_fcaa0e.ipynb b/jupyter/math/latexify_examples_fcaa0e.ipynb new file mode 100644 index 0000000..e177657 --- /dev/null +++ b/jupyter/math/latexify_examples_fcaa0e.ipynb @@ -0,0 +1,540 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "W5mNJI3Bnl6n" + }, + "source": [ + "# `latexify` examples\n", + "\n", + "This notebook provides several examples to use `latexify`.\n", + "\n", + "See also the\n", + "[official documentation](https://github.com/google/latexify_py/blob/documentation/docs/index.md)\n", + "for more details.\n", + "\n", + "If you have any questions, please ask it in the\n", + "[issue tracker](https://github.com/google/latexify_py/issues)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "fWCVgcRHoLd8" + }, + "source": [ + "## Install `latexify`" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "4IPGyu2dFH6T", + "outputId": "471cab8d-3069-4a27-f3ff-67ba177ec58d" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Collecting latexify-py\n", + " Downloading latexify_py-0.4.2-py3-none-any.whl (38 kB)\n", + "Collecting dill>=0.3.2 (from latexify-py)\n", + " Downloading dill-0.3.7-py3-none-any.whl (115 kB)\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m115.3/115.3 kB\u001b[0m \u001b[31m5.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[?25hInstalling collected packages: dill, latexify-py\n", + "Successfully installed dill-0.3.7 latexify-py-0.4.2\n" + ] + } + ], + "source": [ + "# Restart the runtime before running the examples below.\n", + "%pip install latexify-py\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "-Mzq4_dNoSmc" + }, + "source": [ + "## Import `latexify` into your code" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "hViDMhyMFNCO", + "outputId": "b46edb25-5952-4cff-da1e-d65e7e3caad0" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "'0.4.2'" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import math # Optional\n", + "import numpy as np # Optional\n", + "import latexify\n", + "\n", + "latexify.__version__\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "4QJ6I2s7odX1" + }, + "source": [ + "## Examples" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "NvbEYSwXFaeE", + "outputId": "5d0ca2a4-a285-4053-9cc4-3776746443be" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "-1.0\n", + "\\mathrm{solve}(a, b, c) = \\frac{-b + \\sqrt{ b^{2} - 4 a c }}{2 a}\n" + ] + } + ], + "source": [ + "@latexify.function\n", + "def solve(a, b, c):\n", + " return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)\n", + "\n", + "print(solve(1, 4, 3)) # Invoking the function works as expected.\n", + "print(solve) # Printing the function shows the underlying LaTeX source.\n", + "solve # Displays the expression.\n", + "\n", + "# Writes the underlying LaTeX source into a file.\n", + "with open(\"compiled.tex\", \"w\") as fp:\n", + " print(solve, file=fp)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 56 + }, + "id": "wS7BhtPgjSak", + "outputId": "76a8547c-e6b5-458d-aeb2-f9df2f35f7c7" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$$ \\displaystyle \\frac{-b + \\sqrt{ b^{2} - 4 a c }}{2 a} $$" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# latexify.expression works similarly, but does not output the signature.\n", + "@latexify.expression\n", + "def solve(a, b, c):\n", + " return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)\n", + "\n", + "solve\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "G73dnoqqjg4A", + "outputId": "b9f53cf8-4a34-452c-8d9b-946ddd0998df" + }, + "outputs": [ + { + "data": { + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + }, + "text/plain": [ + "'\\\\mathrm{solve}(a, b, c) = \\\\frac{-b + \\\\sqrt{ b^{2} - 4 a c }}{2 a}'" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# latexify.get_latex obtains the underlying LaTeX expression directly.\n", + "def solve(a, b, c):\n", + " return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)\n", + "\n", + "latexify.get_latex(solve)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 58 + }, + "id": "8bYSWIngGF8E", + "outputId": "669e070d-2718-49cb-a2fe-0defe0286b27" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$$ \\displaystyle \\mathrm{sinc}(x) = \\left\\{ \\begin{array}{ll} 1, & \\mathrm{if} \\ x = 0 \\\\ \\frac{\\sin x}{x}, & \\mathrm{otherwise} \\end{array} \\right. $$" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "@latexify.function\n", + "def sinc(x):\n", + " if x == 0:\n", + " return 1\n", + " else:\n", + " return math.sin(x) / x\n", + "\n", + "sinc\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 78 + }, + "id": "h1i4BjdgHjxl", + "outputId": "e448ff37-4753-4090-b2b1-1ef21b279b34" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$$ \\displaystyle \\mathrm{fib}(x) = \\left\\{ \\begin{array}{ll} 0, & \\mathrm{if} \\ x = 0 \\\\ 1, & \\mathrm{if} \\ x = 1 \\\\ \\mathrm{fib} \\mathopen{}\\left( x - 1 \\mathclose{}\\right) + \\mathrm{fib} \\mathopen{}\\left( x - 2 \\mathclose{}\\right), & \\mathrm{otherwise} \\end{array} \\right. $$" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Elif or nested else-if are unrolled.\n", + "@latexify.function\n", + "def fib(x):\n", + " if x == 0:\n", + " return 0\n", + " elif x == 1:\n", + " return 1\n", + " else:\n", + " return fib(x-1) + fib(x-2)\n", + "\n", + "fib\n" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 39 + }, + "id": "-JhJMAXM7j-X", + "outputId": "a47dcd59-2ff9-4aa1-935d-7c789b39057e" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$$ \\displaystyle \\mathrm{greek}(\\alpha, \\beta, \\gamma, \\Omega) = \\alpha \\beta + \\Gamma \\mathopen{}\\left( \\gamma \\mathclose{}\\right) + \\Omega $$" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Some math symbols are converted automatically.\n", + "@latexify.function(use_math_symbols=True)\n", + "def greek(alpha, beta, gamma, Omega):\n", + " return alpha * beta + math.gamma(gamma) + Omega\n", + "\n", + "greek\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 39 + }, + "id": "ySyNPS0y4tzu", + "outputId": "2d95b5ce-a9b8-42b1-eb55-dc8bd0097d69" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$$ \\displaystyle f(x) = g \\mathopen{}\\left( x \\mathclose{}\\right) $$" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Function names, arguments, variables can be replaced.\n", + "identifiers = {\n", + " \"my_function\": \"f\",\n", + " \"my_inner_function\": \"g\",\n", + " \"my_argument\": \"x\",\n", + "}\n", + "\n", + "@latexify.function(identifiers=identifiers)\n", + "def my_function(my_argument):\n", + " return my_inner_function(my_argument)\n", + "\n", + "my_function\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 56 + }, + "id": "TyacQaDM4Ei7", + "outputId": "8e971bbd-2c74-45d2-d0fa-7f46569b10a6" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$$ \\displaystyle f(a, b, c) = \\frac{-b + \\sqrt{ b^{2} - 4 a c }}{2 a} $$" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Assignments can be reduced into one expression.\n", + "@latexify.function(reduce_assignments=True)\n", + "def f(a, b, c):\n", + " discriminant = b**2 - 4 * a * c\n", + " numerator = -b + math.sqrt(discriminant)\n", + " denominator = 2 * a\n", + " return numerator / denominator\n", + "\n", + "f\n" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 78 + }, + "id": "oD8MFS2WE-2U", + "outputId": "f9fad1bd-b7eb-41cc-8743-ec0d80cca8bc" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$$ \\displaystyle \\mathrm{transform}(x, y, a, b, \\theta, s, t) = \\begin{bmatrix} 1 & 0 & s \\\\ 0 & 1 & t \\\\ 0 & 0 & 1 \\end{bmatrix} \\cdot \\begin{bmatrix} \\cos \\theta & -\\sin \\theta & 0 \\\\ \\sin \\theta & \\cos \\theta & 0 \\\\ 0 & 0 & 1 \\end{bmatrix} \\cdot \\begin{bmatrix} a & 0 & 0 \\\\ 0 & b & 0 \\\\ 0 & 0 & 1 \\end{bmatrix} \\cdot \\begin{bmatrix} x \\\\ y \\\\ 1 \\end{bmatrix} $$" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Matrix support.\n", + "@latexify.function(reduce_assignments=True, use_math_symbols=True)\n", + "def transform(x, y, a, b, theta, s, t):\n", + " cos_t = math.cos(theta)\n", + " sin_t = math.sin(theta)\n", + " scale = np.array([[a, 0, 0], [0, b, 0], [0, 0, 1]])\n", + " rotate = np.array([[cos_t, -sin_t, 0], [sin_t, cos_t, 0], [0, 0, 1]])\n", + " move = np.array([[1, 0, s], [0, 1, t], [0, 0, 1]])\n", + " return move @ rotate @ scale @ np.array([[x], [y], [1]])\n", + "\n", + "transform\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 241 + }, + "id": "81OlPVWyGfWN", + "outputId": "48660400-a812-41e2-91ea-23e49ea20c7f" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$ \\begin{array}{l} \\mathbf{function} \\ \\mathrm{fib}(x) \\\\ \\hspace{1em} \\mathbf{if} \\ x = 0 \\\\ \\hspace{2em} \\mathbf{return} \\ 0 \\\\ \\hspace{1em} \\mathbf{else} \\\\ \\hspace{2em} \\mathbf{if} \\ x = 1 \\\\ \\hspace{3em} \\mathbf{return} \\ 1 \\\\ \\hspace{2em} \\mathbf{else} \\\\ \\hspace{3em} \\mathbf{return} \\ \\mathrm{fib} \\mathopen{}\\left( x - 1 \\mathclose{}\\right) + \\mathrm{fib} \\mathopen{}\\left( x - 2 \\mathclose{}\\right) \\\\ \\hspace{2em} \\mathbf{end \\ if} \\\\ \\hspace{1em} \\mathbf{end \\ if} \\\\ \\mathbf{end \\ function} \\end{array} $" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# latexify.algorithmic generates an algorithmic environment instead of an equation.\n", + "@latexify.algorithmic\n", + "def fib(x):\n", + " if x == 0:\n", + " return 0\n", + " elif x == 1:\n", + " return 1\n", + " else:\n", + " return fib(x-1) + fib(x-2)\n", + "\n", + "fib\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 261 + }, + "id": "kbw_1txkGfnX", + "outputId": "fdc58207-1c06-4d88-e249-b0b011bd98c0" + }, + "outputs": [ + { + "data": { + "text/latex": [ + "$ \\begin{array}{l} \\mathbf{function} \\ \\mathrm{collatz}(x) \\\\ \\hspace{1em} n \\gets 0 \\\\ \\hspace{1em} \\mathbf{while} \\ x > 1 \\\\ \\hspace{2em} n \\gets n + 1 \\\\ \\hspace{2em} \\mathbf{if} \\ x \\mathbin{\\%} 2 = 0 \\\\ \\hspace{3em} x \\gets \\left\\lfloor\\frac{x}{2}\\right\\rfloor \\\\ \\hspace{2em} \\mathbf{else} \\\\ \\hspace{3em} x \\gets 3 x + 1 \\\\ \\hspace{2em} \\mathbf{end \\ if} \\\\ \\hspace{1em} \\mathbf{end \\ while} \\\\ \\hspace{1em} \\mathbf{return} \\ n \\\\ \\mathbf{end \\ function} \\end{array} $" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Another example: latexify.algorithmic supports usual control flows.\n", + "@latexify.algorithmic\n", + "def collatz(x):\n", + " n = 0\n", + " while x > 1:\n", + " n = n + 1\n", + " if x % 2 == 0:\n", + " x = x // 2\n", + " else:\n", + " x = 3 * x + 1\n", + " return n\n", + "\n", + "collatz\n" + ] + } + ], + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/jupyter/math/sympy_expressions_e09585.ipynb b/jupyter/math/sympy_expressions_e09585.ipynb new file mode 100644 index 0000000..9f58702 --- /dev/null +++ b/jupyter/math/sympy_expressions_e09585.ipynb @@ -0,0 +1,398 @@ +{ + "metadata": { + "name": "", + "signature": "sha256:556305574de0d0804701dc70002ea506850fd2332c1d7e60a85f867c13625200" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "# SymPy Expressions\n", + "\n", + "SymPy expressions reason about mathematics and generate numeric code." + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "from sympy import *\n", + "from sympy.abc import x, y, z\n", + "init_printing(use_latex='mathjax')" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 1 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Operations on SymPy objects create expressions" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "x + y" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$x + y$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 2, + "text": [ + "x + y" + ] + } + ], + "prompt_number": 2 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "type(x + y)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "pyout", + "prompt_number": 3, + "text": [ + "sympy.core.add.Add" + ] + } + ], + "prompt_number": 3 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### These expressions can be somewhat complex" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "expr = sin(x)**2 + 2*cos(x)\n", + "expr" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$\\sin^{2}{\\left (x \\right )} + 2 \\cos{\\left (x \\right )}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 4, + "text": [ + " 2 \n", + "sin (x) + 2\u22c5cos(x)" + ] + } + ], + "prompt_number": 4 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### We generate numeric code from these expressions" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "ccode(expr) # C" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "pyout", + "prompt_number": 5, + "text": [ + "'pow(sin(x), 2) + 2*cos(x)'" + ] + } + ], + "prompt_number": 5 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "fcode(expr) # Fortran" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "pyout", + "prompt_number": 6, + "text": [ + "' sin(x)**2 + 2*cos(x)'" + ] + } + ], + "prompt_number": 6 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "jscode(expr) # JavaScript" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "pyout", + "prompt_number": 7, + "text": [ + "'Math.pow(Math.sin(x), 2) + 2*Math.cos(x)'" + ] + } + ], + "prompt_number": 7 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "latex(expr) # Even LaTeX" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "pyout", + "prompt_number": 8, + "text": [ + "'\\\\sin^{2}{\\\\left (x \\\\right )} + 2 \\\\cos{\\\\left (x \\\\right )}'" + ] + } + ], + "prompt_number": 8 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### We also reason about expressions" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "expr" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$\\sin^{2}{\\left (x \\right )} + 2 \\cos{\\left (x \\right )}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 9, + "text": [ + " 2 \n", + "sin (x) + 2\u22c5cos(x)" + ] + } + ], + "prompt_number": 9 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "expr.diff(x)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$2 \\sin{\\left (x \\right )} \\cos{\\left (x \\right )} - 2 \\sin{\\left (x \\right )}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 10, + "text": [ + "2\u22c5sin(x)\u22c5cos(x) - 2\u22c5sin(x)" + ] + } + ], + "prompt_number": 10 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "expr.diff(x).diff(x)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$- 2 \\sin^{2}{\\left (x \\right )} + 2 \\cos^{2}{\\left (x \\right )} - 2 \\cos{\\left (x \\right )}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 11, + "text": [ + " 2 2 \n", + "- 2\u22c5sin (x) + 2\u22c5cos (x) - 2\u22c5cos(x)" + ] + } + ], + "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### And then can generate code" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "ccode(expr.diff(x).diff(x))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "pyout", + "prompt_number": 12, + "text": [ + "'-2*pow(sin(x), 2) + 2*pow(cos(x), 2) - 2*cos(x)'" + ] + } + ], + "prompt_number": 12 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Combining reasoning and code generation gives us more efficient code" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "expr.diff(x).diff(x)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$- 2 \\sin^{2}{\\left (x \\right )} + 2 \\cos^{2}{\\left (x \\right )} - 2 \\cos{\\left (x \\right )}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 13, + "text": [ + " 2 2 \n", + "- 2\u22c5sin (x) + 2\u22c5cos (x) - 2\u22c5cos(x)" + ] + } + ], + "prompt_number": 13 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "simplify(expr.diff(x).diff(x))" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "latex": [ + "$$- 2 \\cos{\\left (x \\right )} + 2 \\cos{\\left (2 x \\right )}$$" + ], + "metadata": {}, + "output_type": "pyout", + "prompt_number": 14, + "text": [ + "-2\u22c5cos(x) + 2\u22c5cos(2\u22c5x)" + ] + } + ], + "prompt_number": 14 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "ccode(simplify(expr.diff(x).diff(x))) # Faster code" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "metadata": {}, + "output_type": "pyout", + "prompt_number": 15, + "text": [ + "'-2*cos(x) + 2*cos(2*x)'" + ] + } + ], + "prompt_number": 15 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Final Thoughts\n", + "\n", + "We combine high-level reasoning with low-level code generation.\n", + "\n", + "Blaze does the same thing, just swap out calculus and trig with relational and linear algebra." + ] + } + ], + "metadata": {} + } + ] +} \ No newline at end of file diff --git a/latex/math/36640_t_ab6f06.tex b/latex/math/36640_t_ab6f06.tex new file mode 100644 index 0000000..d119065 --- /dev/null +++ b/latex/math/36640_t_ab6f06.tex @@ -0,0 +1,8810 @@ +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % +% % +% The Project Gutenberg EBook of Lectures on Elementary Mathematics, by % +% Joseph Louis Lagrange % +% % +% This eBook is for the use of anyone anywhere at no cost and with % +% almost no restrictions whatsoever. You may copy it, give it away or % +% re-use it under the terms of the Project Gutenberg License included % +% with this eBook or online at www.gutenberg.org % +% % +% % +% Title: Lectures on Elementary Mathematics % +% % +% Author: Joseph Louis Lagrange % +% % +% Translator: Thomas Joseph McCormack % +% % +% Release Date: July 6, 2011 [EBook #36640] % +% Most recently updated: June 11, 2021 % +% % +% Language: English % +% % +% Character set encoding: UTF-8 % +% % +% *** START OF THIS PROJECT GUTENBERG EBOOK LECTURES ON ELEMENTARY MATHEMATICS *** +% % +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % + +\def\ebook{36640} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% %% +%% Packages and substitutions: %% +%% %% +%% book: Required. %% +%% inputenc: Latin-1 text encoding. Required. %% +%% %% +%% babel: Greek snippets. Required. %% +%% %% +%% ifthen: Logical conditionals. Required. %% +%% %% +%% amsmath: AMS mathematics enhancements. Required. %% +%% amssymb: Additional mathematical symbols. Required. %% +%% %% +%% alltt: Fixed-width font environment. Required. %% +%% array: Enhanced tabular features. Required. %% +%% %% +%% footmisc: Start footnote numbering on each page. Required. %% +%% %% +%% multicol: Twocolumn environment for index. Required. %% +%% makeidx: Indexing. Required. %% +%% %% +%% caption: Caption customization. Required. %% +%% graphicx: Standard interface for graphics inclusion. Required. %% +%% %% +%% calc: Length calculations. Required. %% +%% %% +%% fancyhdr: Enhanced running headers and footers. Required. %% +%% %% +%% geometry: Enhanced page layout package. Required. %% +%% hyperref: Hypertext embellishments for pdf output. Required. %% +%% %% +%% %% +%% Producer's Comments: %% +%% %% +%% OCR text for this ebook was obtained on June 24, 2011, from %% +%% http://www.archive.org/details/lecturesonelemen00lagruoft. %% +%% %% +%% Minor changes to the original are noted in this file in three %% +%% ways: %% +%% 1. \Typo{}{} for typographical corrections, showing original %% +%% and replacement text side-by-side. %% +%% 2. \Add{} for inconsistent/missing punctuation. %% +%% 3. [** TN: Note]s for lengthier or stylistic comments. %% +%% %% +%% %% +%% Compilation Flags: %% +%% %% +%% The following behavior may be controlled by boolean flags. %% +%% %% +%% ForPrinting (false by default): %% +%% If true, compile a print-optimized PDF file: Larger text block,%% +%% two-sided layout, US Letter paper, black hyperlinks. Default: %% +%% screen optimized file (one-sided layout, blue hyperlinks). %% +%% %% +%% %% +%% PDF pages: 181 (if ForPrinting set to false) %% +%% PDF page size: 4.75 x 7" %% +%% PDF bookmarks: created, point to ToC entries %% +%% PDF document info: filled in %% +%% Images: 1 jpg, 6 png diagrams %% +%% %% +%% Summary of log file: %% +%% * One over-full and two under-full hboxes; no visual issues. %% +%% %% +%% Compile History: %% +%% %% +%% July, 2011: adhere (Andrew D. Hwang) %% +%% texlive2007, GNU/Linux %% +%% %% +%% Command block: %% +%% %% +%% pdflatex x2 %% +%% makeindex %% +%% pdflatex x2 %% +%% %% +%% %% +%% July 2011: pglatex. %% +%% Compile this project with: %% +%% pdflatex 36640-t.tex ..... TWO times %% +%% makeindex 36640-t.idx %% +%% pdflatex 36640-t.tex ..... TWO times %% +%% %% +%% pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) %% +%% %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\listfiles +\documentclass[12pt]{book}[2005/09/16] + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PACKAGES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\usepackage[utf8]{inputenc}[2006/05/05] + +\usepackage[greek,english]{babel} + +\usepackage{ifthen}[2001/05/26] %% Logical conditionals + +\usepackage{amsmath}[2000/07/18] %% Displayed equations +\usepackage{amssymb}[2002/01/22] %% and additional symbols + +\usepackage{alltt}[1997/06/16] %% boilerplate, credits, license +\usepackage{array}[2005/08/23] %% extended array/tabular features + +\usepackage[perpage,symbol]{footmisc}[2005/03/17] + +\usepackage{multicol}[2006/05/18] +\usepackage{makeidx}[2000/03/29] + +\usepackage[font=footnotesize,aboveskip=0pt,labelformat=empty]{caption}[2007/01/07] +\usepackage{graphicx}[1999/02/16]%% For diagrams + +\usepackage{calc}[2005/08/06] + +\usepackage{fancyhdr} %% For running heads + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%% Interlude: Set up PRINTING (default) or SCREEN VIEWING %%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% ForPrinting=true false (default) +% Asymmetric margins Symmetric margins +% 1 : 1.62 text block aspect ratio 3 : 4 text block aspect ratio +% Black hyperlinks Blue hyperlinks +% Start major marker pages recto No blank verso pages +% +\newboolean{ForPrinting} + +%% UNCOMMENT the next line for a PRINT-OPTIMIZED VERSION of the text %% +%\setboolean{ForPrinting}{true} + +%% Initialize values to ForPrinting=false +\newcommand{\Margins}{hmarginratio=1:1} % Symmetric margins +\newcommand{\HLinkColor}{blue} % Hyperlink color +\newcommand{\PDFPageLayout}{SinglePage} +\newcommand{\TransNote}{Transcriber's Note} +\newcommand{\TransNoteCommon}{% + The camera-quality files for this public-domain ebook may be + downloaded \textit{gratis} at + \begin{center} + \texttt{www.gutenberg.org/ebooks/\ebook}. + \end{center} + + This ebook was produced using OCR text provided by the University of + Toronto Gerstein Library through the Internet Archive. + \bigskip + + Minor typographical corrections and presentational changes have been + made without comment. + \bigskip +} + +\newcommand{\TransNoteText}{% + \TransNoteCommon + + This PDF file is optimized for screen viewing, but may easily be + recompiled for printing. Please consult the preamble of the \LaTeX\ + source file for instructions and other particulars. +} +%% Re-set if ForPrinting=true +\ifthenelse{\boolean{ForPrinting}}{% + \renewcommand{\Margins}{hmarginratio=2:3} % Asymmetric margins + \renewcommand{\HLinkColor}{black} % Hyperlink color + \renewcommand{\PDFPageLayout}{TwoPageRight} + \renewcommand{\TransNote}{Transcriber's Note} + \renewcommand{\TransNoteText}{% + \TransNoteCommon + + This PDF file is optimized for printing, but may easily be + recompiled for screen viewing. Please consult the preamble + of the \LaTeX\ source file for instructions and other particulars. + } + % Marginal notes omitted in screen version; need these only if ForPrinting + \setlength{\marginparwidth}{1in}% + \setlength{\marginparsep}{12pt}% +}{% If ForPrinting=false, don't skip to recto + \renewcommand{\cleardoublepage}{\clearpage} +} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%% End of PRINTING/SCREEN VIEWING code; back to packages %%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\ifthenelse{\boolean{ForPrinting}}{% + \setlength{\paperwidth}{8.5in}% + \setlength{\paperheight}{11in}% +% ~1:1.67 + \usepackage[body={5in,8in},\Margins]{geometry}[2002/07/08] +}{% + \setlength{\paperwidth}{4.75in}% + \setlength{\paperheight}{7in}% + \raggedbottom +% ~3:4 + \usepackage[body={4.5in,6in},\Margins,includeheadfoot]{geometry}[2002/07/08] +} + +\providecommand{\ebook}{00000} % Overridden during white-washing +\usepackage[pdftex, + hyperref, + hyperfootnotes=false, + pdftitle={The Project Gutenberg eBook \#\ebook: Lectures on Elementary Mathematics}, + pdfauthor={Joseph Louis LaGrange}, + pdfkeywords={University of Toronto, The Internet Archive, Thomas J. McCormack, Andrew D. Hwang}, + pdfstartview=Fit, % default value + pdfstartpage=1, % default value + pdfpagemode=UseNone, % default value + bookmarks=true, % default value + linktocpage=false, % default value + pdfpagelayout=\PDFPageLayout, + pdfdisplaydoctitle, + pdfpagelabels=true, + bookmarksopen=true, + bookmarksopenlevel=0, + colorlinks=true, + linkcolor=\HLinkColor]{hyperref}[2007/02/07] + + +%% Fixed-width environment to format PG boilerplate %% +\newenvironment{PGtext}{% +\begin{alltt} +\fontsize{8.1}{9}\ttfamily\selectfont}% +{\end{alltt}} + +%% Miscellaneous global parameters %% +% No hrule in page header +\renewcommand{\headrulewidth}{0pt} + +% For extra-loose spacing in catalog and narrow ToC environments +\newcommand{\Loosen}{\spaceskip0.5em plus 0.25em minus 0.25em} + +% Globally loosen the spacing +\setlength{\emergencystretch}{1em} + +% Crudely add a bit more space after \hlines +\setlength{\extrarowheight}{1pt} + +% Scratch pad for length calculations +\newlength{\TmpLen} + +%% Running heads %% +\newcommand{\FlushRunningHeads}{\clearpage\fancyhf{}\cleardoublepage} +\newcommand{\InitRunningHeads}{% + \setlength{\headheight}{15pt} + \pagestyle{fancy} + \thispagestyle{empty} + \ifthenelse{\boolean{ForPrinting}} + {\fancyhead[RO,LE]{\thepage}} + {\fancyhead[R]{\thepage}} +} + +\newcommand{\SetRunningHeads}[1]{% + \fancyhead[C]{\textsc{\MakeLowercase{#1}}} +} + +\newcommand{\BookMark}[2]{\phantomsection\pdfbookmark[#1]{#2}{#2}} + +%% ToC formatting %% +\AtBeginDocument{\renewcommand{\contentsname}% + {\protect\thispagestyle{empty}% + \protect\centering\normalfont\large CONTENTS.}} + +\newcommand{\TableofContents}{% + \FlushRunningHeads + \InitRunningHeads + \SetRunningHeads{Contents.} + \BookMark{0}{Contents.} + \tableofcontents +} + +% [** TN: Original ToC has "PAGES" printed at top right of each page; omitted.] +% For internal bookkeeping +\newboolean{ToCNeedDash} %\ToCNote units are separated by dashes + +%\ToCSect{Title}{xref} +\newcommand{\ToCSect}[2]{% + \smallskip% + \settowidth{\TmpLen}{9999}% + \noindent\strut\parbox[b]{\textwidth-\TmpLen}{\small% + \scshape\hangindent2em #1\dotfill}% + \makebox[\TmpLen][r]{\pageref{#2}}% +} + +% \Lecture, \Appendix macros control group formatting +% Enclosing environment for ToC headings generated by marginal notes +\newenvironment{ToCnarrower}{% + \begin{list}{}{% + \setlength{\parskip}{0pt}% + \setlength{\leftmargin}{3em}% + \setlength{\parindent}{0pt}% + \settowidth{\TmpLen}{9999}% + \setlength{\rightmargin}{\TmpLen}% + }\item[]\Loosen\ignorespaces% + }{% + \end{list} +} + +% And the actual marginal note entries +% \ToCNote{Title}{Number} +\newcommand{\ToCNote}[2]{% + \ifthenelse{\boolean{ToCNeedDash}}{\ --- }{\setboolean{ToCNeedDash}{true}}% + \hyperref[#2]{#1}% + \ignorespaces +} + +%% Major document divisions %% +\newcommand{\PGBoilerPlate}{% + \pagenumbering{Alph} + \pagestyle{empty} +% \BookMark{-1}{Front Matter.} + \BookMark{0}{PG Boilerplate.} +} +\newcommand{\FrontMatter}{% + \cleardoublepage % pagestyle still empty; \Preface calls \pagestyle{fancy} + \frontmatter + \BookMark{-1}{Front Matter.} +} +\newcommand{\MainMatter}{% + \FlushRunningHeads + \InitRunningHeads + \mainmatter + \BookMark{-1}{Main Matter.} +} +\newcommand{\BackMatter}{% + \FlushRunningHeads + \InitRunningHeads + \backmatter + \BookMark{-1}{Back Matter.} +} +\newcommand{\PGLicense}{% + \FlushRunningHeads + \pagenumbering{Roman} + \InitRunningHeads + \BookMark{-1}{PG License.} + \SetRunningHeads{Licensing.} +} + +%% Index formatting %% +\newcommand{\FN}[1]{\hyperpage{#1}~footnote} +\newcommand{\EtSeq}[1]{\hyperpage{#1}~et~seq.} +%[** TN: Added word "also"] +\newcommand{\See}[2]{see also~\textit{#1}} + +\makeindex +\makeatletter +\renewcommand{\@idxitem}{\par\hangindent 30\p@\global\let\idxbrk\nobreak} +\renewcommand\subitem{\idxbrk\@idxitem \hspace*{12\p@}\let\idxbrk\relax} +\renewcommand{\indexspace}{\par\penalty-3000 \vskip 10pt plus5pt minus3pt\relax} + +\renewenvironment{theindex}{% + \setlength\columnseprule{0.5pt}\setlength\columnsep{18pt}% + \phantomsection\label{index} + \addtocontents{toc}{\protect\ToCSect{Index}{index}} + \InitRunningHeads + \SetRunningHeads{Index.} + \BookMark{0}{Index.} + \begin{multicols}{2}[\SectTitle{Index.}\small]% ** N.B. font size + \setlength\parindent{0pt}\setlength\parskip{0pt plus 0.3pt}% + \thispagestyle{empty}\let\item\@idxitem\raggedright% + }{% + \end{multicols}\FlushRunningHeads +} +\makeatother + +%% Sectional units %% +\newcommand{\SectTitle}[2][\large]{% + \section*{\centering\normalfont#1\MakeUppercase{#2}} +} +\newcommand{\SectSubtitle}[2][\normalsize]{% + \subsection*{\centering\normalfont#1\MakeUppercase{#2}} +} + +% \Chapter[PDF name]{Number.}{Heading title} +\newcommand{\Lecture}[3][]{% + \FlushRunningHeads + \InitRunningHeads + \ifthenelse{\equal{#1}{}}{% + \SetRunningHeads{#3}% + }{% + \SetRunningHeads{#1}% + } + \BookMark{0}{Lecture #2 #3}% + \label{lecture:#2}% + \thispagestyle{empty} + \ifthenelse{\not\equal{#2}{I.}}{% End ToC entry block of previous chapter + \addtocontents{toc}{\protect\end{ToCnarrower}}% + }{} + \addtocontents{toc}{% + \protect\ToCSect{Lecture #2\protect\quad #3}{lecture:#2}} + \addtocontents{toc}{% + \protect\settowidth{\TmpLen}{9999}\protect\addtolength{\TmpLen}{3em}}% + \addtocontents{toc}{\protect\begin{ToCnarrower}}% + \SectTitle{Lecture #2} + \SectSubtitle{#3} +} + +\newcommand{\Preface}{% + \normalsize + \FlushRunningHeads + \pagestyle{fancy} + \InitRunningHeads + \SetRunningHeads{Preface.} + \BookMark{0}{Preface.} + \label{preface} + \addtocontents{toc}{\protect\ToCSect{Preface}{preface}} + \SectTitle{Preface.} +} + +\newcommand{\BioSketch}[2]{% + \FlushRunningHeads + \InitRunningHeads + \SetRunningHeads{Biographical Sketch.} + \BookMark{0}{Biographical Sketch.} + \label{biosketch} + \addtocontents{toc}{\protect\ToCSect{Biographical Sketch of #1}{biosketch}} + \SectTitle{#1} + \SectSubtitle{#2} +} + +\newcommand{\Appendix}[1]{% + \FlushRunningHeads + \InitRunningHeads + \SetRunningHeads{Appendix.} + \BookMark{0}{Appendix.} + \label{appendix} + \addtocontents{toc}{\protect\end{ToCnarrower}}% Close chapter subunit block + \addtocontents{toc}{\protect\ToCSect{Appendix}{appendix}} + \addtocontents{toc}{\protect\begin{ToCnarrower}} + \addtocontents{toc}{\protect\ToCNote{#1}{appendix}} + \addtocontents{toc}{\protect\end{ToCnarrower}} + \SectTitle{Appendix.} + \SectSubtitle{#1} +} + +\newcommand{\Signature}[2]{% + \medskip% + \null\hfill\textsc{#1}\hspace*{\parindent} \\ + \hspace*{\parindent}#2% +} + +\newcounter{MNote} +\newcommand{\MNote}[1]{% + \refstepcounter{MNote}% + \phantomsection\label{note:\theMNote}% + \ifthenelse{\boolean{ForPrinting}}{% + %marginal note + \marginpar{\raggedright\footnotesize#1}% + }{}% Nothing + \addtocontents{toc}{\protect\ToCNote{#1}{note:\theMNote}}% + \ignorespaces% +} + +%% Illustrations %% +\newcommand{\Frontispiece}{% + \ifthenelse{\boolean{ForPrinting}}{% + \cleardoublepage % Place verso, opposite the title page + \null + \newpage + }{}% Else do nothing + \BookMark{0}{Frontispiece.} + \null\vfill + \begin{figure}[hp!] + \centering + \ifthenelse{\boolean{ForPrinting}}{% + \includegraphics[width=\textwidth]{./images/lagrange.jpg} + }{% + \includegraphics[width=0.9\textwidth]{./images/lagrange.jpg} + } + \end{figure} + \vfill + \cleardoublepage +} +% \Figure{Number}{width} +\newcommand{\Figure}[2]{% + \begin{figure}[hbt!] + \centering + \includegraphics[width=#2]{./images/fig#1.png} + \caption{Fig.~#1.} + \end{figure}\ignorespaces% +} + +%% Book Catalogs %% +\newcommand{\CatalogSmallFont}{% + \ifthenelse{\boolean{ForPrinting}}{\footnotesize}{\scriptsize}% +} +% Catalog at front of book +\newcommand{\FrontCatalog}[1]{% + \newpage + \thispagestyle{empty} + \SectTitle{#1} +} +\newcommand{\Book}[1]{% + \medskip\par\noindent\CatalogSmallFont\Loosen\hangindent 2em#1% +} + +% and at back +\newcommand{\Catalog}{% + \FlushRunningHeads + \InitRunningHeads + \fancyhf{} + \BookMark{0}{Catalogue.} + \begin{center} + \Large CATALOGUE OF PUBLICATIONS \\[12pt] + \footnotesize OF THE \\[12pt] + \large OPEN COURT PUBLISHING CO. + \end{center} + \tb +} +\newenvironment{Author}[1]{\medskip\par\noindent #1}{} +\newcommand{\Title}[3][4\parindent]{% +\par\footnotesize\hangindent3\parindent#2% + +\ifthenelse{\not\equal{#3}{}}{% + \hspace*{\parindent}\CatalogSmallFont\hangindent#1 #3\par% + }{} +} + +\newcommand{\Item}[1]{\makebox[1em][r]{#1}\ \hangindent4em} + +%% Corrections. %% +\newcommand{\Typo}[2]{#2} +\newcommand{\Add}[1]{\Typo{}{#1}} + +%% Page separators and cross-references %% +\newcommand{\PageSep}[1]{\ignorespaces} + +\newcommand{\PgLabel}[1]{\phantomsection\label{pg#1}} +\newcommand{\PgRef}[1]{\hyperref[pg#1]{p.~\pageref*{pg#1}}} +\newcommand{\PgRange}[2]{% + \ifthenelse{\equal{\pageref{pg#1}}{\pageref{pg#2}}}{% + \hyperref[pg#1]{p.~\pageref*{pg#1}}% + }{% + pp.~\hyperref[pg#1]{\pageref*{pg#1}}--\hyperref[pg#2]{\pageref*{pg#2}}% + }% +} + +%% Miscellaneous textual formatting %% +\newcommand{\First}[1]{\textsc{\large #1}} +\newcommand{\ieme}{\textsuperscript{me}} + +% Decorative breaks +\newcommand{\tb}[1][0.75in]{\begin{center}\rule{#1}{0.5pt}\end{center}} +\newcommand{\stars}{% +\begin{center} + \makebox[1in][c]{ + \raisebox{-0.5ex}{*}\hfill\raisebox{0.5ex}{*}\hfill\raisebox{-0.5ex}{*}% + } +\end{center} +} + +%% Miscellaneous mathematical formatting %% +\DeclareMathSizes{12}{11}{8}{7} +\DeclareInputMath{183}{\cdot} + +\newcommand{\PadTo}[3][c]{% + \settowidth{\TmpLen}{\ensuremath{#2}}% + \makebox[\TmpLen][#1]{\ensuremath{#3}}% +} + +\newcommand{\Tag}[1]{% + \tag*{\ensuremath{#1}} +} + +% Square roots of matching height +\newcommand{\mysqrt}[1]{\sqrt{\vphantom{b}#1}} +\newcommand{\sqrta}{\mysqrt{a}} +\newcommand{\sqrtc}{\mysqrt{c}} + +% Multiplication row for table on page 30 +\newcommand{\MultRow}[2]{#1\,\smash{\rule[-5pt]{0.5pt}{15pt}}} + +%%%%%%%%%%%%%%%%%%%%%%%% START OF DOCUMENT %%%%%%%%%%%%%%%%%%%%%%%%%% +\begin{document} +%% PG BOILERPLATE %% +\PGBoilerPlate +\begin{center} +\begin{minipage}{\textwidth} +\small +\begin{PGtext} +The Project Gutenberg EBook of Lectures on Elementary Mathematics, by +Joseph Louis Lagrange + +This eBook is for the use of anyone anywhere at no cost and with +almost no restrictions whatsoever. You may copy it, give it away or +re-use it under the terms of the Project Gutenberg License included +with this eBook or online at www.gutenberg.org + + +Title: Lectures on Elementary Mathematics + +Author: Joseph Louis Lagrange + +Translator: Thomas Joseph McCormack + +Release Date: July 6, 2011 [EBook #36640] +Most recently updated: June 11, 2021 + +Language: English + +Character set encoding: UTF-8 + +*** START OF THIS PROJECT GUTENBERG EBOOK LECTURES ON ELEMENTARY MATHEMATICS *** +\end{PGtext} +\end{minipage} +\end{center} +\newpage +%% Credits and transcriber's note %% +\begin{center} +\begin{minipage}{\textwidth} +\begin{PGtext} +Produced by Andrew D. Hwang. +\end{PGtext} +\end{minipage} +\end{center} +\vfill + +\begin{minipage}{0.85\textwidth} +\small +\BookMark{0}{Transcriber's Note.} +\subsection*{\centering\normalfont\scshape% +\normalsize\MakeLowercase{\TransNote}}% + +\raggedright +\TransNoteText +\end{minipage} +%%%%%%%%%%%%%%%%%%%%%%%%%%% FRONT MATTER %%%%%%%%%%%%%%%%%%%%%%%%%% +\FrontMatter +\null\vfill +\noindent {\Large ON ELEMENTARY MATHEMATICS} +\vfill +\PageSep{} +\FrontCatalog{IN THE SAME SERIES.} + +\tb + +\Book{ON CONTINUITY AND IRRATIONAL NUMBERS, and +ON THE NATURE AND MEANING OF NUMBERS\@. +By R.~\textsc{Dedekind}. From the German by \textit{W.~W. Beman}. +Pages,~115. Cloth, 75~cents net (3s.~6d.~net).} + +\Book{GEOMETRIC EXERCISES IN PAPER-FOLDING\@. By \textsc{T.~Sundara Row}. +Edited and revised by \textit{W.~W. Beman} and +\textit{D.~E. Smith}. With many half-tone engravings from photographs +of actual exercises, and a package of papers for +folding. Pages, circa~200. Cloth, \$1.00\Typo{.}{} net (4s.~6d.~net). +(In Preparation.)} + +\Book{ON THE STUDY AND DIFFICULTIES OF MATHEMATICS\@. +By \textsc{Augustus De~Morgan}. Reprint edition\Typo{`}{} +with portrait and bibliographies. Pp.,~288. Cloth, \$1.25 +net (4s.~6d.~net).} + +\Book{LECTURES ON ELEMENTARY MATHEMATICS\@. By +\textsc{Joseph Louis Lagrange}. From the French by \textit{Thomas~J. +McCormack}, With portrait and biography. Pages,~172. +Cloth, \$1.00 net (4s.~6d.~net).} + +\Book{ELEMENTARY ILLUSTRATIONS OF THE DIFFERENTIAL +AND INTEGRAL CALCULUS\@. By \textsc{Augustus De~Morgan}. +Reprint edition. With a bibliography of text-books +of the Calculus. Pp.,~144. Price, \$1.00 net (4s.~6d.~net).} + +\Book{MATHEMATICAL ESSAYS AND RECREATIONS\@. By +\textsc{Prof.\ Hermann Schubert}, of Hamburg, Germany. From +the German by \textit{T.~J. McCormack}. Essays on Number\Typo{.}{,} +The Magic Square, The Fourth Dimension, The Squaring +of the Circle. Pages,~149. Price, Cloth, 75c.~net (3s.~net).} + +\Book{A BRIEF HISTORY OF ELEMENTARY MATHEMATICS\@. +By \textsc{Dr.\ Karl Fink}, of Tübingen. From the German by \textit{W.~W. +Beman} and \textit{D.~E. Smith}. Pp.~333. Cloth, \$1.50 net +(5s.~6d.~net).} + +\tb +\vfill + +\noindent\makebox[\textwidth][s]{\large THE OPEN COURT PUBLISHING COMPANY} +\begin{center} +\footnotesize 324 DEARBORN ST., CHICAGO. \\ +\normalsize LONDON: Kegan Paul, Trench, Trübner \& Co. +\end{center} +\PageSep{i} +%[Blank page] +\PageSep{ii} +\Frontispiece +\PageSep{iii} +\begin{center} +\Large LECTURES\\[24pt] +\footnotesize ON\\[24pt] +\LARGE ELEMENTARY MATHEMATICS +\vfill + +\footnotesize BY\\[18pt] +\large JOSEPH LOUIS LAGRANGE +\vfill + +\footnotesize FROM THE FRENCH BY\\[18pt] +\normalsize THOMAS J. McCORMACK +\vfill\vfill + +\small SECOND EDITION +\vfill\vfill + +\large CHICAGO \\ +\normalsize THE OPEN COURT PUBLISHING COMPANY \\[12pt] +\footnotesize LONDON AGENTS \\ +\textsc{Kegan Paul, Trench, Trübner \& Co., Ltd.} \\ +1901 +\end{center} +\newpage +\PageSep{iv} +\null\vfill +\begin{center} +\footnotesize TRANSLATION COPYRIGHTED \\ +BY \\ +\small\textsc{The Open Court Publishing Co.} \\ +1898. +\end{center} +\vfill +\PageSep{v} + + +\Preface + +\First{The} present work, which is a translation of the \textit{Leçons élémentaires +sur les \Typo{mathematiques}{mathématiques}} of Joseph Louis Lagrange, +\index{Lagrange, J. L.}% +the greatest of modern analysts, and which is to be found in Volume~VII. +of the new edition of his collected works, consists of a +series of lectures delivered in the year 1795 at the \textit{\Typo{Ecole}{École} Normale},---an +institution which was the direct outcome of the French Revolution +and which gave the first impulse to modern practical +ideals of education. With Lagrange, at this institution, were associated, +as professors of mathematics. Monge and Laplace, and we +\index{Laplace}% +\index{Monge}% +owe to the same historical event the final form of the famous \textit{Géométrie +descriptive}, as well as a second course of lectures on arithmetic +and algebra, introductory to these of Lagrange, by Laplace. + +With the exception of a German translation by Niedermüller +\index{Ecole@{\Typo{Ecole}{École} Normale}}% +(Leipsic, 1880), the lectures of Lagrange have never been published +in separate form; originally they appeared in a fragmentary +shape in the \textit{Séances des \Typo{Ecoles}{Écoles} Normales}, as they had been reported +by the stenographers, and were subsequently reprinted in +the journal of the Polytechnic School. From references in them +\index{Polytechnic School}% +to subjects afterwards to be treated it is to be inferred that a fuller +development of higher algebra was intended,---an intention which +the brief existence of the \textit{\Typo{Ecole}{École} Normale} defeated. With very few +exceptions, we have left the expositions in their historical form, +having only referred in an Appendix to a point in the early history +of algebra. + +The originality, elegance, and symmetrical character of these +lectures have been pointed out by \Typo{DeMorgan}{De~Morgan}, and notably by Dühring, +\index{DeMorgan@{\Typo{DeMorgan}{De Morgan}}}% +\index{Duhring@{Dühring, E.}}% +who places them in the front rank of elementary expositions, +as an exemplar of their kind. Coming, as they do, from one of +the greatest mathematicians of modern times, and with all the excellencies +which such a source implies, unique in their character +\PageSep{vi} +as a \emph{reading-book} in mathematics, and interwoven with historical +and philosophical remarks of great helpfulness, they cannot fail +to have a beneficent and stimulating influence\Typo{,}{.} + +The thanks of the translator of the present volume are due to +Professor Henry~B. Fine, of Princeton, N.~J., for having read the +proofs. + +\Signature{Thomas J. McCormack.} +{\textsc{La Salle, Illinois}, August~1, 1898.} +\PageSep{vii} + + +\BioSketch{Joseph Louis Lagrange.} +{Biographical Sketch.} +\index{Economy of thought}% +\index{Lagrange, J. L.|EtSeq}% +\index{Short-mind symbols|EtSeq}% +\index{Stenophrenic symbols|EtSeq}% +\index{Symbols|EtSeq}% + +\First{A great} part of the progress of formal thought, where it is +not hampered by outward causes, has been due to the invention +of what we may call \emph{stenophrenic}, or \emph{short-mind}, symbols. +These, of which all written language and scientific notations are +examples, disengage the mind from the consideration of ponderous +and circuitous mechanical operations and economise its energies +for the performance of new and unaccomplished tasks of thought. +And the advancement of those sciences has been most notable +which have made the most extensive use of these short-mind symbols. +Here mathematics and chemistry stand pre-eminent. The +\index{Greeks, mathematics of the}% +\index{Mathematics!evolution of}% +ancient Greeks, with all their mathematical endowment as a race, +and even admitting that their powers were more visualistic than +analytic, were yet so impeded by their lack of short-mind symbols +as to have made scarcely any progress whatever in analysis. Their +arithmetic was a species of geometry. They did not possess the +sign for zero, and also did not make use of position as an indicator +of value. Even later, when the germs of the indeterminate analysis +were disseminated in Europe by Diophantus, progress ceased +here in the science, doubtless from this very cause. The historical +\index{Science!development of|EtSeq}% +calculations of Archimedes, his approximation to the value of~$\pi$,~etc, +owing to this lack of appropriate arithmetical and algebraical +symbols, entailed enormous and incredible labors, which, if +they had been avoided, would, with his genius, indubitably have +led to great discoveries. +\PageSep{viii} + +Subsequently, at the close of the Middle Ages, when the so-called +Arabic figures became established throughout Europe with +the symbol~$0$ and the principle of local value, immediate progress +was made in the art of reckoning. The problems which arose +gave rise to questions of increasing complexity and led up to the +general solutions of equations of the third and fourth degree by +the Italian mathematicians of the sixteenth century. Yet even +these discoveries were made in somewhat the same manner as +problems in mental arithmetic are now solved in common schools; +for the present signs of plus, minus, and equality, the radical and +exponential signs, and especially the systematic use of letters for +denoting general quantities in algebra, had not yet become universal. +The last step was definitively due to the French mathematician +Vieta (1540--1603), and the mighty advancement of analysis +\index{Vieta}% +resulting therefrom can hardly be measured or imagined. The +trammels were here removed from algebraic thought, and it ever +afterwards pursued its way unincumbered in development as if impelled +by some intrinsic and irresistible potency. Then followed +the introduction of exponents by Descartes, the representation of +\index{Descartes}% +geometrical magnitudes by algebraical symbols, the extension of +the theory of exponents to fractional and negative numbers by +Wallis (1616--1703), and other symbolic artifices, which rendered +\index{Wallis}% +the language of analysis as economic, unequivocal, and appropriate +as the needs of the science appeared to demand. In the famous +dispute regarding the invention of the infinitesimal calculus, while +not denying and even granting for the nonce the priority of Newton +\index{Newton, his problem}% +in the matter, some writers have gone so far as to regard Leibnitz's +\index{Leibnitz}% +introduction of the integral symbol~$\int$ as alone a sufficient substantiation +of his claims to originality and independence, so far as the +power of the new science was concerned. + +For the \emph{development} of science all such short-mind symbols +are of paramount importance, and seem to carry within themselves +the germ of a perpetual mental motion which needs no outward +power for its unfoldment. Euler's well-known saying that his +\index{Euler}% +\PageSep{ix} +pencil seemed to surpass him in intelligence finds its explanation +here, and will be understood by all who have experienced the uncanny +feeling attending the rapid development of algebraical formulæ, +where the urned thought of centuries, so to speak, rolls from +one's finger's ends. + +But it should never be forgotten that the mighty stenophrenic +engine of which we here speak, like all machinery, affords us rather +a mastery over nature than an insight into it; and for some, unfortunately, +the higher symbols of mathematics are merely brambles +that hide the living springs of reality. Many of the greatest +discoveries of science,---for example, those of Galileo, Huygens, +\index{Galileo}% +\index{Huygens}% +and Newton,---were made without the mechanism which afterwards +becomes so indispensable for their development and application. +Galileo's reasoning anent the summation of the impulses imparted +to a falling stone is virtual integration; and Newton's mechanical +discoveries were made by the man who invented, but evidently did +not use to that end, the doctrine of fluxions. +\stars + +We have been following here, briefly and roughly, a line of +progressive abstraction and generalisation which even in its beginning +was, psychologically speaking, at an exalted height, but in the +course of centuries had been carried to points of literally ethereal +refinement and altitude. In that long succession of inquirers by +whom this result was effected, the process reached, we may say, +its culmination and purest expression in Joseph Louis Lagrange, +born in Turin, Italy, the 30th~of January,~1736, died in Paris, April~10, +1813. Lagrange's power over symbols has, perhaps, never been +paralleled either before his day or since. It is amusing to hear his +biographers relate that in early life he evinced no aptitude for +mathematics, but seemed to have been given over entirely to the +pursuits of pure literature; for at fifteen we find him teaching +mathematics in an artillery school in Turin, and at nineteen he +had made the greatest discovery in mathematical science since that +of the infinitesimal calculus, namely, the creation of the algorism +\PageSep{x} +\index{Variations, calculus of}% +and method of the Calculus of Variations. ``Your analytical solution +of the isoperimetrical problem,'' writes Euler, then the prince +\index{Euler}% +of European mathematicians, to him, ``leaves nothing to be desired +in this department of inquiry, and I am delighted beyond measure +that it has been your lot to carry to the highest pitch of perfection, +a theory, which since its inception I have been almost the only one +to cultivate.'' But the exact nature of a ``variation'' even Euler +did not grasp, and even as late as~1810 in the English treatise of +Woodhouse on this subject we read regarding a certain new sign +\index{Woodhouse}% +introduced, that M.~Lagrange's ``power over symbols is so unbounded +that the possession of it seems to have made him capricious.'' + +Lagrange himself was conscious of his wonderful capacities in +this direction. His was a time when geometry, as he himself +phrased it, had become a dead language, the abstractions of analysis +were being pushed to their highest pitch, and he felt that with +his achievements its possibilities within certain limits were being +rapidly exhausted. The saying is attributed to him that chairs of +mathematics, so far as creation was concerned, and unless new +fields were opened up, would soon be as rare at universities as +chairs of Arabic. In both research and exposition, he totally reversed +the methods of his predecessors. They had proceeded in +their exposition from special cases by a species of induction; his +eye was always directed to the highest and most general points of +view; and it was by his suppression of details and neglect of minor, +unimportant considerations that he swept the whole field of analysis +with a generality of insight and power never excelled, adding +to his originality and profundity a conciseness, elegance, and lucidity +which have made him the model of mathematical writers. +\stars + +Lagrange came of an old French family of Touraine, France, +said to have been allied to that of Descartes. At the age of twenty-six +he found himself at the zenith of European fame. But his +reputation had been purchased at a great cost. Although of ordinary +\PageSep{xi} +height and well proportioned, he had by his ecstatic devotion +to study,---periods always accompanied by an irregular pulse and +high febrile \Typo{excitatian}{excitation},---almost ruined his health. At this age, +accordingly, he was seized with a hypochondriacal affection and +with bilious disorders, which accompanied him \Typo{thronghout}{throughout} his life, +and which were only allayed by his great abstemiousness and careful +regimen. He was bled twenty-nine times, an infliction which +alone would have affected the most robust constitution. Through +his great care for his health he gave much attention to medicine. +He was, in fact, conversant with all the sciences, although knowing +his \textit{forte} he rarely expressed an opinion on anything unconnected +with mathematics. + +When Euler left Berlin for St.~Petersburg in~1766 he and +D'Alembert induced Frederick the Great to make Lagrange president +of the Academy of Sciences at Berlin. Lagrange accepted +the position and lived in Berlin twenty years, where he wrote some +of his greatest works. He was a great favorite of the Berlin people, +and enjoyed the profoundest respect of Frederick the Great, +although the latter seems to have preferred the noisy reputation of +Maupertuis, Lamettrie, and Voltaire to the unobtrusive fame and +personality of the man whose achievements were destined to shed +more lasting light on his reign than those of any of his more strident +literary predecessors: Lagrange was, as he himself said, \textit{philosophe +sans crier}. + +The climate of Prussia agreed with the mathematician. He +refused the most seductive offers of foreign courts and princes, and +it was not until the death of Frederick and the intellectual reaction +of the Prussian court that he returned to Paris, where his career +broke forth in renewed splendor. He published in~1788 his great +\textit{Mécanique analytique}, that ``scientific poem'' of Sir William +Rowan Hamilton, which gave the quietus to mechanics as then +formulated, and having been made during the Revolution Professor +of Mathematics at the new \textit{\Typo{Ecole}{École} Normale} and the \textit{\Typo{Ecole}{École} Polytechnique}, +\index{Ecole@{\Typo{Ecole}{École} Normale}}% +\index{Polytechnic School}% +he entered with Laplace and Monge upon the activity +\index{Laplace}% +\index{Monge}% +\PageSep{xii} +which made these schools for generations to come exemplars of +practical scientific education, systematising by his lectures there, +and putting into definitive form, the science of mathematical analysis +of which he had developed the extremest capacities. Lagrange's +activity at Paris was interrupted only once by a brief period +of melancholy aversion for mathematics, a lull which he +devoted to the adolescent science of chemistry and to philosophical +studies; but he afterwards resumed his old love with increased ardor +and assiduity. His significance for thought generally is far +beyond what we have space to insist upon. Not least of all, theology, +which had invariably mingled itself with the researches of his +predecessors, was with him forever divorced from a legitimate influence +of science. + +The honors of the world sat ill upon Lagrange: \textit{la magnificence +le gênait}, he said; but he lived at a time when proffered +things were usually accepted, not refused. He was loaded with +personal favors and official distinctions by Napoleon who called +\index{Napoleon}% +him \textit{la haute pyramide des sciences mathématiques}, was made a +Senator, a Count of the Empire, a Grand Officer of the Legion of +Honor, and, just before his death, received the grand cross of the +Order of Reunion. He never feared death, which he termed \textit{une +dernière fonction, ni pénible ni désagréable}, much less the disapproval +of the great. He remained in Paris during the Revolution +when \textit{savants} were decidedly in disfavor, but was suspected +of aspiring to no throne but that of mathematics. When Lavoisier +\index{Lavoisier}% +was executed he said: ``It took them but a moment to lay low that +head; yet a hundred years will not suffice perhaps to produce its +like again.'' + +Lagrange would never allow his portrait to be painted, maintaining +that a man's works and not his personality deserved preservation. +The frontispiece to the present work is from a steel +engraving based on a sketch obtained by stealth at a meeting of +the Institute. His genius was excelled only by the purity and +nobleness of his character, in which the world never even sought +\PageSep{xiii} +to find a blot, and by the exalted Pythagorean simplicity of his +life. He was twice married, and by his wonderful care of his person +lived to the advanced age of seventy-seven years, not one of +which had been misspent. His life was the veriest incarnation of +the scientific spirit; he lived for nothing else. He left his weak +body, which retained its intellectual powers to the very last, as an +offering upon the altar of science, happily made when his work +had been done; but to the world he bequeathed his ``ever-living'' +thoughts now recently resurgent in a new and monumental edition +of his works (published by Gauthier-Villars, Paris). \textit{Ma vie est +là!} he said, pointing to his brain the day before his death. + +\Signature{Thomas J. McCormack.}{} +\PageSep{xiv} +%[Blank page] +\PageSep{xv} +\TableofContents +\iffalse +%[** TN: Used marginal notes to generate entries; entries in original ToC +% don't obviously match the book's units.] +CONTENTS. + +PAGES + +Preface + +Biographical Sketch of Joseph Louis LaGrange. + +Lecture I. On Arithmetic, and in Particular Fractions +and Logarithms. 1-23 + +Systems of Numeration. Fractions. Greatest Common +Divisor. Continued Fractions. Theory of +Powers, Proportions, and Progressions. Involution +and Evolution. Rule of Three. Interest. Annuities. +Logarithms. + +Lecture II. On the Operations of Arithmetic . . . 24-53 + +Arithmetic and Geometry. New Method of Subtraction. +Abridged and Approximate Multiplication. +Decimals. Property of the Number 9. +Tests of Divisibility. Theory of Remainders. +Checks on Multiplication and Division. Evolution. +Rule of Three. Theory and Practice. Probability +of Life. Alligation or the Rule of Mixtures. + +Lecture III. On Algebra, Particularly the Resolution +of Equations of the Third and Fourth Degree 54-95 + +Origin of Greek Algebra. Diophantus. Indeterminate +Analysis. Equations of the Second Degree. +Translations of Diophantus. Algebra Among the +Arabs. History of Algebra in Italy, France, and +Germany. History of Equations of the Third and +Fourth Degree and of the Irreducible Case. Theory +of Equations. Discussion of Cubic Equations. +Discussion of the Irreducible Case. The Theory +\PageSep{xvi} +of Roots. Extraction of the Square and Cube Roots +of Two Imaginary Binomials. Theory of Imaginary +Expressions. Trisection of an Angle. Method +of Indeterminates. Discussion of Biquadratic Equations. + +Lecture IV. On the Resolution of Numerical Equations ... 96-126 + +Algebraical Resolution of Equations. Numerical +Resolution of Equations. Position of the Roots. +Representation of Equations by Curves. Graphic +Resolution of Equations. Character of the Roots of +Equations. Limits of the Roots of Numerical Equations. +Separation of the Roots. Method of Substitutions. +The Equation of Differences. Method of +Elimination. Constructions and Instruments for +Solving Equations. + +Lecture V. On the Employment of Curves in the Solution +of Problems 127-149 + +Application of Geometry to Algebra. Resolution of +Problems by Curves. The Problem of Two Lights. +Variable Quantities Minimal Values. Analysis +of Biquadratic Equations Conformably to the Problem +of the Two Lights. Advantages of the Method +of Curves The Curve of Errors. \textit{Regula falsi.} +Solution of Problems by the Curve of Errors. +Problem of the Circle and Inscribed Polygon. +Problem of the Observer and Three Objects. Parabolic +Curves. Newton's Problem. Interpolation +of Intermediate Terms in Series of Observations, +Experiments, etc. + +Appendix . 151 + +Note on the Origin of Algebra. +\fi +\PageSep{1} +\MainMatter +\index{Numerical equations|See{Equations}}% + + +\Lecture[On Arithmetic.]{I.}{On Arithmetic, and in Particular Fractions +and Logarithms.} + +\First{Arithmetic} is divided into two parts. The first +is based on the decimal system of notation and +\MNote{Systems of numeration\Add{.}} +on the manner of arranging numeral characters to express +numbers. This first part comprises the four +common operations of addition, subtraction, multiplication, +and division,---operations which, as you +know, would be different if a different system were +adopted, but, which it would not be difficult to transform +from one system to another, if a change of systems +were desirable. + +The second part is independent of the system of +\index{Numeration, systems of}% +numeration. It is based on the consideration of quantities +and on the general properties of numbers. The +theory of fractions, the theory of powers and of roots, +the theory of arithmetical and geometrical progressions, +and, lastly, the theory of logarithms, fall under +this head. I purpose to advance, here, some remarks +on the different branches of this part of arithmetic. +\PageSep{2} + +It may be regarded as \emph{universal arithmetic}, having +\index{Arithmetic!universal|EtSeq}% +an intimate affinity to algebra. For, if instead of +\index{Algebra!definition of}% +particularising the quantities considered, if instead of +assigning them numerically, we treat them in quite a +general way, designating them by letters, we have +algebra. + +You know what a fraction is. The notion of a +\index{Fractions|EtSeq}% +\index{Ratios, constant|EtSeq}% +\MNote{Fractions.} +fraction is slightly more composite than that of whole +numbers. In whole numbers we consider simply a +quantity repeated. To reach the notion of a fraction +it is necessary to consider the quantity divided into a +certain number of parts. Fractions represent in general +ratios, and serve to express one quantity by means +of another. In general, nothing measurable can be +measured except by fractions expressing the result of +the measurement, unless the measure be contained an +exact number of times in the thing to be measured. + +You also know how a fraction can be reduced to +\index{Divisor, greatest common|EtSeq}% +its lowest terms. When the numerator and the denominator +are both divisible by the same number, +their greatest common divisor can be found by a very +ingenious method which we owe to Euclid. This +\index{Euclid}% +method is exceedingly simple and lucid, but it may +be rendered even more palpable to the eye by the following +consideration. Suppose, for example, that you +have a given length, and that you wish to measure it. +The unit of measure is given, and you wish to know +how many times it is contained in the length. You +first lay off your measure as many times as you can on +\PageSep{3} +the given length, and that gives you a certain whole +number of measures. If there is no remainder your +operation is finished. But if there be a remainder, +\MNote{Greatest common divisor.} +that remainder is still to be evaluated. If the measure +is divided into equal parts, for example, into ten, +twelve, or more equal parts, the natural procedure is +to use one of these parts as a new measure and to see +how many times it is contained in the remainder. +You will then have for the value of your remainder, +a fraction of which the numerator is the number of +parts contained in the remainder and the denominator +the total number of parts into which the given measure +is divided. + +I will suppose, now, that your measure is not so +divided but that you still wish to determine the ratio +of the proposed length to the length which you have +adopted as your measure. The following is the procedure +which most naturally suggests itself. + +If you have a remainder, since that is less than the +\index{Fractions!continued|EtSeq}% +measure, naturally you will seek to find how many +times your remainder is contained in this measure. +Let us say two times, and that a remainder is still +left. Lay this remainder on the preceding remainder. +Since it is necessarily smaller, it will still be contained +a certain number of times in the preceding remainder, +say three times, and there will be another remainder +or there will not; and so on. In these different remainders +you will have what is called a \emph{continued fraction}. +For example, you have found that the measure +\PageSep{4} +is contained three times in the proposed length. You +have, to start with, the number \emph{three}. Then you have +\MNote{Continued fractions.} +found that your first remainder is contained twice in +your measure. You will have the fraction \emph{one} divided +by \emph{two}. But this last denominator is not complete, +for it was supposed there was still a remainder. That +remainder will give another and similar fraction, which +is to be added to the last denominator, and which by +our supposition is \emph{one} divided by \emph{three}. And so with +the rest. You will then have the fraction +\[ +3 + \cfrac{1}{2 + \cfrac{1}{3 + \ddots}} +\] +as the expression of your ratio between the proposed +length and the adopted measure. + +Fractions of this form are called \emph{continued fractions}, +and can be reduced to ordinary fractions by the common +rules. Thus, if we stop at the first fraction, i.e., +if we consider only the first remainder and neglect the +second, we shall have $3 + \frac{1}{2}$, which is equal to~$\frac{7}{2}$. Considering +only the first and the second remainders, we +stop at the second fraction, and shall have $3 + \dfrac{1}{2 + \frac{1}{3}}$. +Now $2 + \frac{1}{3} = \frac{7}{3}$. We shall have therefore $3 + \frac{3}{7}$, which +is equal to~$\frac{24}{7}$. And so on with the rest. If we arrive +in the course of the operation at a remainder which is +contained exactly in the preceding remainder, the +operation is terminated, and we shall have in the continued +\PageSep{5} +fraction a common fraction that is the exact +value of the length to be measured, in terms of the +length which served as our measure. If the operation +\MNote{Terminating continued fractions.} +is not thus terminated, it can be continued to infinity, +and we shall have only fractions which approach more +and more nearly to the true value. + +If we now compare this procedure with that employed +for finding the greatest common divisor of two +numbers, we shall see that it is virtually the same +thing; the difference being that in finding the greatest +common divisor we devote our attention solely to +the different remainders, of which the last is the divisor +sought, whereas by employing the successive +quotients, as we have done above, we obtain fractions +which constantly approach nearer and nearer to the +fraction formed by the two numbers given, and of +which the last is that fraction itself reduced to its +lowest terms. + +As the theory of continued fractions is little known, +but is yet of great utility in the solution of important +numerical questions, I shall enter here somewhat +more fully into the formation and properties of these +fractions. And, first, let us suppose that the quotients +found, whether by the mechanical operation, or by +the method for finding the greatest common divisor, +are, as above, $3$,~$2$, $3$, $5$, $7$,~$3$. The following is a rule +by which we can write down at once the convergent +fractions which result from these quotients, without +developing the continued fraction. +\PageSep{6} + +The first quotient, supposed divided by unity, +will give the first fraction, which will be too small, +\MNote{Converging fractions.} +\index{Fractions!converging}% +namely,~$\frac{3}{1}$. Then, multiplying the numerator and denominator +of this fraction by the second quotient and +adding unity to the numerator, we shall have the second +fraction,~$\frac{7}{2}$, which will be too large. Multiplying +in like manner the numerator and denominator of this +fraction by the third quotient, and adding to the numerator +the numerator of the preceding fraction, and +to the denominator the denominator of the preceding +fraction, we shall have the third fraction, which will +be too small. Thus, the third quotient being~$3$, we +have for our numerator $(7 × 3 = 21) + 3 = 24$, and for +our denominator $(2 × 3 = 6) + 1 = 7$. The third convergent, +therefore, is~$\frac{24}{7}$. We proceed in the same +manner for the fourth convergent. The fourth quotient +being~$5$, we say $24$~times~$5$ is~$120$, and this plus~$7$, +the numerator of the fraction preceding, is~$127$; +similarly, $7$~times~$5$ is~$35$, and this plus~$2$ is~$37$. The +new fraction, therefore, is~$\frac{127}{37}$. And so with the rest. + +In this manner, by employing the six quotients $3$,~$2$, +$3$, $5$, $7$,~$3$ we obtain the six fractions +\[ +\frac{3}{1},\quad +\frac{7}{2},\quad +\frac{24}{7},\quad +\frac{127}{37},\quad +\frac{913}{266},\quad +\frac{2866}{835}, +\] +of which the last, supposing the operation to be completed +at the sixth quotient~$3$, will be the required +value of the length measured, or the fraction itself +reduced to its lowest terms. + +The fractions which precede the last are alternately +\PageSep{7} +smaller and larger than the last, and have the advantage +of approaching more and more nearly to its value +in such wise that no other fraction can approach it +\MNote{Convergents.} +\index{Convergents}% +more nearly except its denominator be larger than the +product of the denominator of the fraction in question +and the denominator of the fraction following. For +example, the fraction~$\frac{24}{7}$ is less than the true value +which is that of the fraction~$\frac{2866}{835}$, but it approaches +to it more nearly than any other fraction does whose +denominator is not greater than the product of~$7$ by~$37$, +that is,~$259$. Thus, any fraction expressed in large +numbers may be reduced to a series of fractions expressed +in smaller numbers and which approach as +near to it as possible in value. + +The demonstration of the foregoing properties is +deduced from the nature of continued fractions, and +from the fact that if we seek the difference between +one of the convergent fractions and that next adjacent +to it we shall obtain a fraction of which the numerator +is always unity and the denominator the product of +the two denominators; a consequence which follows +\textit{\Typo{a}{à}~priori} from the very law of formation of these fractions. +Thus the difference between $\frac{7}{2}$~and~$\frac{3}{1}$ is~$\frac{1}{2}$, in +excess; between $\frac{24}{7}$~and~$\frac{7}{2}$, $\frac{1}{14}$,~in defect; between $\frac{127}{37}$ +and~$\frac{24}{7}$, $\frac{1}{259}$,~in excess; and so on. The result being, +that by employing this series of differences we can +express in another and very simple manner the fractions +with which we are here concerned, by means of +a second series of fractions of which the numerators +\PageSep{8} +are all unity and the denominators successively the +products of every two adjacent denominators. Instead +\MNote{A second method of expression.} +of the fractions written above, we have thus the +series: +\[ +\frac{3}{1} + \frac{1}{1 × 2} + - \frac{1}{2 × 7} + + \frac{1}{7 × 37} + - \frac{1}{37 × 266} + + \frac{1}{266 × 835}. +\] + +The first term, as we see, is the first fraction, the +first and second together give the second fraction~$\frac{7}{2}$, +the first, the second, and the third give the third fraction~$\frac{24}{7}$, +and so on with the rest; the result being that +the series entire is equivalent to the last fraction. + +There is still another way, less known but in some +respects more simple, of treating the same question---which +leads directly to a series similar to the preceding. +Reverting to the previous example, after having +found that the measure goes three times into the length +to be measured and that after the first remainder has +been applied to the measure there is left a new remainder, +instead of comparing this second remainder +with the preceding, as we did above, we may compare +it with the measure itself. Thus, supposing it goes +into the latter seven times with a remainder, we again +compare this last remainder with the measure, and so +on, until we arrive, if possible, at a remainder which +is an aliquot part of the measure,---which will terminate +the operation. In the contrary event, if the +measure and the length to be measured are incommensurable, +the process may be continued to infinity. +\PageSep{9} +We shall have then, as the expression of the length +measured, the series +\MNote{A third method of expression.} +\[ +3 + \frac{1}{2} - \frac{1}{2 × 7} + \ldots. +\] + +It is clear that this method is also applicable to +ordinary fractions. We constantly retain the denominator +of the fraction as the dividend, and take the different +remainders successively as divisors. Thus, the +fraction~$\frac{2866}{835}$ gives the quotients $3$,~$2$, $7$, $18$, $19$, $46$, +$119$, $417$\Typo{}{,}~$835$; from which we obtain the series +\[ +3 + \frac{1}{2} - \frac{1}{2 × 7} + + \frac{1}{2 × 7 × 18} + - \frac{1}{2 × 7 × 18 × 19} + \ldots; +\] +and as these partial fractions rapidly diminish, we +shall have, by combining them successively, the simple +fractions, +\[ +\frac{7}{2},\quad +\frac{48}{2 × 7},\quad +\frac{865}{2 × 7 × 18}, \ldots, +\] +which will constantly approach nearer and nearer to +the true value sought, and the error will be less than +the first of the partial fractions neglected. + +Our remarks on the foregoing methods of evaluating +fractions should not be construed as signifying +that the employment of decimal fractions is not nearly +\index{Decimal!fractions}% +\index{Fractions!decimal}% +always preferable for expressing the values of fractions +to whatever degree of exactness we wish. But cases +occur where it is necessary that these values should +be expressed by as few figures as possible. For example, +if it were required to construct a planetarium, +\index{Planetarium}% +\PageSep{10} +since the ratios of the revolutions of the planets to one +another are expressed by very large numbers, it would +\MNote{Origin of continued fractions.} +\index{Fractions!origin of continued}% +be necessary, in order not to multiply unduly the +number of the teeth on the wheels, to avail ourselves +of smaller numbers, but at the same time so to select +them that their ratios should approach as nearly as +possible to the actual ratios. It was, in fact, this very +question that prompted Huygens, in his search for its +\index{Huygens}% +solution, to resort to continued fractions and that so +gave birth to the theory of these fractions. Afterwards, +in the elaboration of this theory, it was found +adapted to the solution of other important questions, +and this is the reason, since it is not found in elementary +works, that I have deemed it necessary to go +somewhat into detail in expounding its principles. + +We will now pass to the theory of powers, proportions, +and progressions. + +As you already know, a number multiplied by itself +\index{Powers|EtSeq}% +gives its square, and multiplied again by itself +gives its cube, and so on. In geometry we do not go +beyond the cube, because no body can have more than +three dimensions. But in algebra and arithmetic we +may go as far as we please. And here the theory of +the extraction of roots takes its origin. For, although +every number can be raised to its square and to its +cube and so forth, it is not true reciprocally that every +number is an exact square or an exact cube. The +number~$2$, for example, is not a square; for the square +of~$1$ is~$1$, and the square of~$2$ is four; and there being +\PageSep{11} +no other whole numbers between these two, it is impossible +to find a whole number which multiplied by +itself will give~$2$. It cannot be found in fractions, for +\MNote{Involution and evolution.} +\index{Evolution}% +\index{Involution and evolution}% +if you take a fraction reduced to its lowest terms, the +square of that fraction will again be a fraction reduced +to its lowest terms, and consequently cannot be equal +to the whole number~$2$. But though we cannot obtain +the square root of~$2$ exactly, we can yet approach to it +as nearly as we please, particularly by decimal fractions. +By following the common rules for the extraction +of square roots, cube roots, and so forth, the process +may be extended to infinity, and the true values +of the roots may be approximated to any degree of +exactitude we wish. + +But I shall not enter into details here. The theory +of powers has given rise to that of progressions, before +entering on which a word is necessary on proportions. + +Every fraction expresses a ratio. Having two equal +\index{Proportion|EtSeq}% +\index{Ratios, constant|EtSeq}% +fractions, therefore, we have two equal ratios; and +the numbers constituting the fractions or the ratios +form what is called a \emph{proportion}. Thus the equality +of the ratios $2$~to~$4$ and $3$~to~$6$ gives the proportion +$2 : 4 :: 3 : 6$, because $4$~is the double of~$2$ as $6$~is the +double of~$3$. Many of the rules of arithmetic depend +on the theory of proportions. First, it is the foundation +of the famous \emph{rule of three}, which is so extensively +\index{Rule!three@of three|EtSeq}% +used. You know that when the first three terms of a +proportion are given, to obtain the fourth you have +\PageSep{12} +only to multiply the last two together and divide the +product by the first. Various special rules have also +\MNote{Proportions\Add{.}} +been conceived and have found a place in the books +on arithmetic; but they are all reducible to the rule +of three and may be neglected if we once thoroughly +grasp the conditions of the problem. There are direct, +inverse, simple, and compound rules of three, rules of +partnership, of mixtures, and so forth. In all cases +it is only necessary to consider carefully the conditions +of the problem and to arrange the terms of the +proportion correspondingly. + +I shall not enter into further details here. There +\index{Progressions, theory of}% +is, however, another theory which is useful on numerous +occasions,---namely, the \emph{theory of progressions}. +When you have several numbers that bear the same +proportion to one another, and which follow one another +in such a manner that the second is to the first +as the third is to the second, as the fourth is to the +third, and so forth, these numbers form a progression. +I shall begin with an observation. + +The books of arithmetic and algebra ordinarily distinguish +between two kinds of progression, arithmetical +and geometrical, corresponding to the proportions +called arithmetical and geometrical. But the appellation +proportion appears to me extremely inappropriate +as applied to \emph{arithmetical proportion}. And as it +\index{Arithmetical proportion}% +is one of the objects of the \textit{École Normale} to rectify +\index{Ecole@{\Typo{Ecole}{École} Normale}}% +the language of science, the present slight digression +will not be considered irrelevant. +\PageSep{13} + +I take it, then, that the idea of proportion is already +well established by usage and that it corresponds solely +to what is called \emph{geometrical proportion}. When we +\index{Geometrical!proportion}% +\MNote{Arithmetical and geometrical proportions.} +speak of the proportion of the parts of a man's body, +of the proportion of the parts of an edifice,~etc.; when +we say that a plan should be reduced proportionately +in size,~etc.; in fact, when we say generally that one +thing is proportional to another, we understand by +proportion equality of ratios only, as in geometrical +proportion, and never equality of differences as in +arithmetical proportion. Therefore, instead of saying +\index{Equi-different numbers}% +that the numbers, $3$,~$5$, $7$,~$9$, are in arithmetical proportion, +because the difference between $5$~and~$3$ is the +same as that between $9$~and~$7$, I deem it desirable that +some other term should be employed, so as to avoid +all ambiguity. We might, for instance, call such numbers +\emph{equi-different}, reserving the name of \emph{proportionals} +for numbers that are in geometrical proportion, as $2$,~$4$, +$6$,~$8$,~etc. + +As for the rest, I cannot see why the proportion +called \emph{arithmetical} is any more arithmetical than that +which is called geometrical, nor why the latter is more +geometrical than the former. On the contrary, the +primitive idea of geometrical proportion is based on +arithmetic, for the notion of ratios springs essentially +from the consideration of numbers. + +Still, in waiting for these inappropriate designations +to be changed, I shall continue to make use of +them, as a matter of simplicity and convenience. +\PageSep{14} + +The theory of arithmetical progressions presents +few difficulties. Arithmetical progressions consist of +\MNote{Progressions.} +\index{Progressions, theory of}% +quantities which increase or diminish constantly by +the same amount. But the theory of geometrical progressions +is more difficult and more important, as a +large number of interesting questions depend upon it---for +example, all problems of compound interest, all +problems that relate to discount, and many others of +like nature. + +In general, quantities in geometrical proportion +are produced, when a quantity increases and the force +generating the increase, so to speak, is proportional +to that quantity. It has been observed that in countries +where the means of subsistence are easy of acquisition, +as in the first American colonies, the population +is doubled at the expiration of twenty years; if +it is doubled at the end of twenty years it will be quadrupled +at the end of forty, octupled at the end of sixty, +and so on; the result being, as we see, a geometrical +progression, corresponding to intervals of time in +arithmetical progression. It is the same with compound +interest. If a given sum of money produces, +at the expiration of a certain time, a certain sum, at +the end of double that time, the original sum will have +produced an equivalent additional sum, and in addition +the sum produced in the first space of time will, +in its proportion, likewise have produced during the +second space of time a certain sum; and so with the +rest. The original sum is commonly called the \emph{principal}, +\PageSep{15} +the sum produced the \emph{interest}, and the constant +\index{Interest}% +ratio of the principal to the interest per annum, the +\emph{rate}. Thus, the rate \emph{twenty} signifies that the interest +\MNote{Compound interest.} +is the twentieth part of the principal,---a rate which +is commonly called $5$~\emph{per cent.}, $5$~being the twentieth +part of~$100$. On this basis, the principal, at the end +of one year, will have increased by its one-twentieth +part; consequently, it will have been augmented in +the ratio of $21$~to~$20$. At the end of two years, it will +have been increased again in the same ratio, that is in +the ratio of $\frac{21}{20}$~multiplied by~$\frac{21}{20}$; at the end of three +years, in the ratio of $\frac{21}{20}$~multiplied twice by itself; and +so on. In this manner we shall find that at the end of +fifteen years it will almost have doubled itself, and that +at the end of fifty-three years it will have increased +tenfold. Conversely, then, since a sum paid now will +be doubled at the end of fifteen years, it is clear that +a sum not payable till after the expiration of fifteen +years is now worth only one-half its amount. This +is what is termed the \emph{present value} of a sum payable +\index{Present value}% +at the end of a certain time; and it is plain, that to +find that value, it is only necessary to divide the sum +promised by the fraction~$\frac{21}{20}$, or to multiply it by the +fraction~$\frac{20}{21}$, as many times as there are years for the +sum to run. In this way we shall find that a sum +payable at the end of fifty-three years, is worth at +present only one-tenth. From this it is evident what +little advantage is to be derived from surrendering the +absolute ownership of a sum of money in order to obtain +\PageSep{16} +the enjoyment of it for a period of only fifty +years, say; seeing that we gain by such a transaction +\MNote{Present values and annuities.} +\index{Annuities}% +only one-tenth in actual use, whilst we lose the ownership +of the property forever. + +In \emph{annuities}, the consideration of interest is combined +with that of the probability of life; and as +every one is prone to believe that he will live very +long, and as, on the other hand, one is apt to under-*estimate +the value of property which must be abandoned +on death, a peculiar temptation arises, when +one is without children, to invest one's fortune, wholly +or in part, in annuities. Nevertheless, when put to +the test of rigorous calculation, annuities are not +found to offer sufficient advantages to induce people +to sacrifice for them the ownership of the original +capital. Accordingly, whenever it has been attempted +to create annuities sufficiently attractive to induce individuals +to invest in them, it has been necessary to +offer them on terms which are onerous to the company. + +But we shall have more to say on this subject when +we expound the theory of annuities, which is a branch +of the calculus of probabilities. + +I shall conclude the present lecture with a word +\index{Logarithms|EtSeq}% +on \emph{logarithms}. The simplest idea which we can form +of the theory of logarithms, as they are found in the +ordinary tables, is that of conceiving all numbers +as powers of~$10$; the exponents of these powers, +then, will be the logarithms of the numbers. From +\PageSep{17} +this it is evident that the multiplication and division +of two numbers is reducible to the addition and subtraction +of their respective exponents, that is, of their +\MNote{Logarithms\Add{.}} +logarithms. And, consequently, involution and the +extraction of roots are reducible to multiplication and +division, which is of immense advantage in arithmetic +and renders logarithms of priceless value in that science. + +But in the period when logarithms were invented, +mathematicians were not in possession of the theory +of powers. They did not know that the root of a number +could be represented by a fractional power. The +following was the way in which they approached the +problem. + +The primitive idea was that of two corresponding +progressions, one arithmetical, and the other geometrical. +In this way the general notion of a logarithm +was reached. But the means for finding the logarithms +of all numbers were still lacking. As the numbers +follow one another in arithmetical progression, it +was requisite, in order that they might all be found +among the terms of a geometrical progression, so to +establish that progression that its successive terms +should differ by extremely small quantities from one +another; and, to prove the possibility of expressing +all numbers in this way, Napier, the inventor, first +\index{Napier|EtSeq}% +considered them as expressed by lines and parts of +lines, and these lines he considered as generated by +\PageSep{18} +the continuous motion of a point, which was quite +natural. + +\MNote{Napier (1550--1617).} +He considered, accordingly, two lines, the first of +which was generated by the motion of a point describing +in equal times spaces in geometrical progression, +and the other generated by a point which described +spaces that increased as the times and consequently +formed an arithmetical progression corresponding to +the geometrical progression. And he supposed, for +the sake of simplicity, that the initial velocities of +these two points were equal. This gave him the logarithms, +at first called \emph{natural}, and afterwards \emph{hyperbolical}, +when it was discovered that they could be expressed +as parts of the area included between a +hyperbola and its asymptotes. By this method it is +clear that to find the logarithm of any given number, +it is only necessary to take a part on the first line +equal to the given number, and to seek the part on +the second line which shall have been described in +the same interval of time as the part on the first. + +Conformably to this idea, if we take as the two +first terms of our geometrical progression the numbers +with very small differences $1$~and~$1.0000001$, and as +those of our arithmetical progression $0$~and $0.0000001$, +and if we seek successively, by the known rules, all +the following terms of the two progressions, we shall +find that the number~$2$ expressed approximately to the +eighth place of decimals is the $6931472$th~term of the +geometrical progression, that is, that the logarithm of~$2$ +\PageSep{19} +is~$0.6931472$. The number~$10$ will be found to be the +$23025851$th~term of the same progression; therefore, +the logarithm of~$10$ is~$2.3025851$, and so with the rest. +\MNote{Origin of logarithms\Add{.}} +\index{Logarithms!origin of}% +But Napier, having to determine only the logarithms +of numbers less than unity for the purposes of trigonometry, +where the sines and cosines of angles are +expressed as fractions of the radius, considered a decreasing +geometrical progression of which the first +two terms were $1$~and~$0.9999999$; and of this progression +he determined the succeeding terms by enormous +computations. On this last hypothesis, the logarithm +which we have just found for~$2$ becomes that of the +number~$\frac{1}{5}$ or~$0.5$, and that of the number~$10$ becomes +that of the number~$\frac{1}{10}$ or~$0.1$; as is readily apparent +from the nature of the two progressions. + +Napier's work appeared in~1614. Its utility was +felt at once. But it was also immediately seen that it +would conform better to the decimal system of our +arithmetic, and would be simpler, if the logarithm of~$10$ +were made unity, conformably to which that of~$100$ +would be~$2$, and so with the rest. To that end, instead +of taking as the first two terms of our geometrical +progression the numbers $1$~and~$\Typo{0.0000001}{1.0000001}$, we should +have to take the numbers $1$~and~$1.0000002302$, retaining +$0$~and~$0.0000001$ as the corresponding terms of the +arithmetical progression. Whence it will be seen, +that, while the point which is supposed to generate by +its motion the geometrical line, or the numbers, is +describing the very small portion~$0.0000002302\dots$, +\PageSep{20} +the other point, the office of which is to generate +simultaneously the arithmetical line, will have described +\MNote{Briggs (1556--1631). Vlacq.} +\index{Briggs}% +\index{Vlacq}% +the portion~$0.0000001$; and that therefore the +spaces described in the same time by the two points +at the beginning of their motion, that is to say, their +initial velocities, instead of being equal, as in the +preceding system, will be in the proportion of the +numbers $2.302\dots$~to~$1$, where it will be remarked +that the number~$2.302\dots$ is exactly the number +which in the original system of natural logarithms +stood for the logarithm of~$10$,---a result demonstrable +\textit{à~priori}, as we shall see when we come to apply +the formulæ of algebra to the theory of logarithms. +Briggs, a contemporary of Napier, is the author of this +change in the system of logarithms, as he is also of +the tables of logarithms now in common use. A portion +\index{Logarithms!tables of}% +of these was calculated by Briggs himself, and +the remainder by Vlacq, a Dutchman. + +These tables appeared at Gouda, in~1628. They +contain the logarithms of all numbers from~$1$ to~$100000$ +to ten decimal places, and are now extremely rare. +But it was afterwards discovered that for ordinary purposes +seven decimals were sufficient, and the logarithms +are found in this form in the tables which are +used to-day. Briggs and Vlacq employed a number +of highly ingenious artifices for facilitating their work. +The device which offered itself most naturally and +which is still one of the simplest, consists in taking +the numbers $1$,~$10$, $100$,~$\dots$, of which the logarithms +\PageSep{21} +are $0$,~$1$,~$2$,~$\dots$, and in interpolating between the successive +terms of these two series as many corresponding +terms as we desire, in the first series by geometrical +\MNote{Computation of logarithms.} +mean proportionals and in the second by +arithmetical means. In this manner, when we have +arrived at a term of the first series approaching, to the +eighth decimal place, the number whose logarithm +we seek, the corresponding term of the other series +will be, to the eighth decimal place approximately, +the logarithm of that number. Thus, to obtain the +logarithm of~$2$, since $2$~lies between $1$~and~$10$, we seek +first by the extraction of the square root of~$10$, the +geometrical mean between $1$~and~$10$, which we find to +be~$3.16227766$, while the corresponding arithmetical +mean between $0$~and~$1$ is~$\frac{1}{2}$ or~$0.50000000$; we are +assured thus that this last number is the logarithm of +the first. Again, as $2$~lies between $1$~and~$3.16227766$, +the number just found, we seek in the same manner +the geometrical mean between these two numbers, +and find the number~$1.77827941$. As before, taking +the arithmetical mean between $0$~and~$5.0000000$, we +shall have for the logarithm of~$1.77827941$ the number~$0.25000000$. +Again, $2$~lying between $1.77827941$ +and~$3.16227766$, it will be necessary, for still further +approximation, to find the geometrical mean between +these two, and likewise the arithmetical mean between +their logarithms. And so on. In this manner, +by a large number of similar operations, we find that +the logarithm of~$2$ is~$0.3010300$, that of~$3$ is~$0.4771213$, +\PageSep{22} +and so on, not carrying the degree of exactness beyond +the seventh decimal place. But the preceding +\MNote{Value of the history of science.} +\index{Science!history of}% +calculation is necessary only for prime numbers; because +the logarithms of numbers which are the product +of two or several others, are found by simply +taking the sum of the logarithms of their factors. + +As for the rest, since the calculation of logarithms +is now a thing of the past, except in isolated instances, +it may be thought that the details into which we have +here entered are devoid of value. We may, however, +justly be curious to know the trying and tortuous +paths which the great inventors have trodden, the different +\index{Inventors, great}% +steps which they have taken to attain their goal, +and the extent to which we are indebted to these veritable +benefactors of the human race. Such knowledge, +moreover, is not matter of idle curiosity. It can +afford us guidance in similar inquiries and sheds an +increased light on the subjects with which we are +employed. + +Logarithms are an instrument universally employed +in the sciences, and in the arts depending on calculation. +The following, for example, is a very evident +application of their use. + +Persons not entirely unacquainted with music know +\index{Music}% +that the different notes of the octave are expressed by +numbers which give the divisions of a stretched cord +producing those notes. Thus, the principal note being +denoted by~$1$, its octave will be denoted by~$\frac{1}{2}$, +its fifth by~$\frac{2}{3}$, its third by~$\frac{4}{5}$, its fourth by~$\frac{3}{4}$, its second +\PageSep{23} +by~$\frac{8}{9}$, and so on. The distance of one of these notes +from that next adjacent to it is called an \emph{interval}, and +is measured, not by the difference, but by the ratio of +the numbers expressing the two sounds. Thus, the +interval between the fourth and fifth, which is called +the \emph{major tone}, is regarded as sensibly double of that +between the third and fourth, which is called the \emph{semi-major}. +In fact, the first being expressed by~$\frac{8}{9}$, the +second by~$\frac{15}{16}$, it can be easily proved that the first +does not differ by much from the square of the second. +Now, it is clear that this conception of intervals, on +\MNote{Musical temperament.} +\index{Temperament, theory of}% +which the whole theory of temperament is founded, +conducts us naturally to logarithms. For if we express +the value of the different notes by the logarithms +of the lengths of the cords answering to them, +then the interval of one note from another will be +expressed by the simple difference of values of the +two notes; and if it were required to divide the octave +into twelve equal semi-tones, which would give the +temperament that is simplest and most exact, we +should simply have to divide the logarithm of one +half, the value of the octave, into twelve equal parts. +\PageSep{24} + + +\Lecture{II.}{On the Operations of Arithmetic.} +\index{Arithmetic!operations of|EtSeq}% + +\First{An ancient} writer once remarked that arithmetic +and geometry were \emph{the wings of mathematics}. +\index{Geometry}% +\index{Mathematics!wings of}% +\MNote{Arithmetic and geometry.} +I believe we can say, without metaphor, that +these two sciences are the foundation and essence of +all the sciences that treat of magnitude. But not +only are they the foundation, they are also, so to +speak, the capstone of these sciences. For, whenever +we have reached a result, in order to make use of it, +it is requisite that it be translated into numbers or +into lines; to translate it into numbers, arithmetic is +necessary; to translate it into lines, we must have +recourse to geometry. + +The importance of arithmetic, accordingly, leads +me to the further discussion of that subject to-day, +although we have begun algebra. I shall take up its +several parts, and shall offer new observations, which +will serve to supplement what I have already expounded +to you. I shall employ, moreover, the geometrical +\index{Geometrical!calculus}% +calculus, wherever that is necessary for giving +\PageSep{25} +greater generality to the demonstrations and +methods. + +First, then, as regards addition, there is nothing +to be added to what has already been said. Addition +is an operation so simple in character that its conception +is a matter of course. But with regard to subtraction, +\MNote{New method of subtraction\Add{.}} +\index{Subtraction, new method of|EtSeq}% +there is another manner of performing that +operation which is frequently more advantageous than +the common method, particularly for those familiar +with it. It consists in converting the subtraction into +addition by taking the complement of every figure of +the number which is to be subtracted, first with respect +to~$10$ and afterwards with respect to~$9$. Suppose, +for example, that the number~$2635$ is to be subtracted +from the number~$7853$. Instead of saying $5$~from~$13$ +\begin{figure}[hbt!] +\centering +$\begin{array}{r} +7853 \\ +2635 \\ +\hline +5218 +\end{array}$ +\end{figure} +leaves~$8$; $3$~from~$4$ leaves~$1$; $6$~from~$8$ leaves~$2$; +and $2$~from~$7$ leaves~$5$, giving a total remainder of~$5218$,---I +say: $5$~the complement of~$5$ with respect to~$10$ +added to~$3$ gives~$8$,---I write down~$8$; $6$~the complement +of~$3$ with respect to~$9$ added to~$5$ gives~$11$,---I +write down~$1$ and carry~$1$; $3$~the complement of~$6$ +with respect to~$9$, plus~$9$, by reason of the $1$~carried, +gives~$12$,---I put down~$2$ and carry~$1$; lastly, $7$~the +complement of~$2$ with respect to~$9$ plus~$8$, on account +of the $1$~carried, gives~$15$,---I put down~$5$ and this time +carry nothing, for the operation is completed, and the +\PageSep{26} +last~$10$ which was borrowed in the course of the operation +must be rejected. In this manner we obtain the +same remainder as above,~$5218$. + +The foregoing method is extremely convenient +\MNote{Subtraction by complements.} +\index{Complements, subtraction by}% +when the numbers are large; for in the common +method of subtraction, where borrowing is necessary +in subtracting single numbers from one another, mistakes +are frequently made, whereas in the method +with which we are here concerned we never borrow +but simply carry, the subtraction being converted into +addition. With regard to the complements they are +discoverable at the merest glance, for every one knows +that $3$~is the complement of~$7$ with respect to~$10$, $4$~the +complement of~$5$ with respect to~$9$,~etc. And as +to the reason of the method, it too is quite palpable. +The different complements taken together form the +total complement of the number to be subtracted +either with respect to~$10$ or~$100$ or~$1000$, etc., according +as the number has $1$,~$2$,~$3$~$\dots$ figures; so that the +operation performed is virtually equivalent to first +adding $10$,~$100$, $1000$~$\dots$ to the minuend and then +taking the subtrahend from the minuend as so augmented. +Whence it is likewise apparent why the~$10$ +of the sum found by the last partial addition must be +rejected. + +As to multiplication, there are various abridged +\index{Multiplication!abridged methods of|EtSeq}% +methods possible, based on the decimal system of +numbers. In multiplying by~$10$, for example, we have, +as we know, simply to add a cipher; in multiplying +\PageSep{27} +by~$100$ we add two ciphers; by~$1000$, three ciphers,~etc. +Consequently, to multiply by any aliquot part of~$10$, +for example~$5$, we have simply to multiply by~$10$ +\MNote{Abridged multiplication.} +and then divide by~$2$; to multiply by~$25$ we multiply +by~$100$ and divide by~$4$, and so on for all the products +of~$5$. + +When decimal numbers are to be multiplied by +\index{Decimal!numbers|EtSeq}% +decimal numbers, the general rule is to consider the +two numbers as integers and when the operation is +finished to mark off from the right to the left as many +places in the product as there are decimal places in +the multiplier and the multiplicand together. But in +practice this rule is frequently attended with the inconvenience +of unnecessarily lengthening the operation, +for when we have numbers containing decimals +these numbers are ordinarily exact only to a certain +number of places, so that it is necessary to retain in +the product only the decimal places of an equivalent +order. For example, if the multiplicand and the multiplier +each contain two places of decimals and are exact +only to two decimal places, we should have in the +product by the ordinary method four decimal places, +the two last of which we should have to reject as useless +and inexact. I shall give you now a method for +obtaining in the product only just so many decimal +places as you desire. + +I observe first that in the ordinary method of multiplying +we begin with the units of the multiplier which +we multiply with the units of the multiplicand, and so +\PageSep{28} +continue from the right to the left. But there is nothing +compelling us to begin at the right of the multiplier. +\MNote{Inverted multiplication.} +\index{Multiplication!inverted}% +We may equally well begin at the left. And +I cannot in truth understand why the latter method +should not be preferred, since it possesses the advantage +of giving at once the figures having the greatest +value, and since, in the majority of cases where large +numbers are multiplied together, it is just these last +and highest places that concern us most; we frequently, +in fact, perform multiplications only to find +what these last figures are. And herein, be it parenthetically +remarked, consists one of the great advantages +in calculating by logarithms, which always +\index{Logarithms!advantages in calculating by}% +give, be it in multiplication or division, in involution +or evolution, the figures in the descending order of +their value, beginning with the highest and proceeding +from the left to the right. + +By performing multiplication in this manner, no +difference is caused in the total product. The sole +distinction is, that by the new method the first line, +the first partial product, is that which in the ordinary +method is last, and the second partial product is that +which in the ordinary method is next to the last, and +so with the rest. + +Where whole numbers are concerned and the exact +product is required, it is indifferent which method we +employ. But when decimal places are involved the +prime essential is to have the figures of the whole +numbers first in the product and to descend afterwards +\PageSep{29} +successively to the figures of the decimal parts, +instead of, as in the ordinary method, beginning with +the last decimal places and successively ascending to +the figures forming the whole numbers. + +In applying this method practically, we write the +multiplier underneath the multiplicand so that the +units' figure of the multiplier falls beneath the last +\MNote{Approximate multiplication.} +\index{Multiplication!approximate}% +figure of the multiplicand. We then begin with the +last left-hand figure of the multiplier which we multiply +as in the ordinary method by all the figures of the +multiplicand, beginning with the last to the right and +proceeding successively to the left; observing that the +first figure of the product is to be placed underneath +the figure with which we are multiplying, while the +others follow in their successive order to the left. We +proceed in the same manner with the second figure of +the multiplier, likewise placing beneath this figure the +first figure of the product, and so on with the rest. +The place of the decimal point in these different products +will be the same as in the multiplicand, that is +to say, the units of the products will all fall in the +same vertical line with those of the multiplicand and +consequently those of the sum of all the products or +of the total product will also fall in that line. In this +manner it is an easy matter to calculate only as many +decimal places as we wish. I give below an example +of this method in which the multiplicand is~$437.25$ +and the multiplier~$27.34$: +\PageSep{30} +\MNote{The new method exemplified.} +\[ +\begin{array}{r@{\,}l} +437\PadTo[l]{\,}{.} & 25 \\ + & 27.34 \\ +\hline +\MultRow{8745}{0} \\ +\MultRow{3060}{75} \\ +\MultRow{131}{17\phantom{.}5} \\ +\MultRow{17}{49\phantom{.}00} \\ +\hline +\MultRow{11954}{41\phantom{.}50} +\end{array} +\] + +I have written all the decimals in the product, but +\index{Decimals!multiplication of}% +it is easy to see how we may omit calculating the decimals +which we wish to neglect. The vertical line is +used to mark more distinctly the place of the decimal +point. + +The preceding rule appears to me simpler and +more natural than that which is attributed to Oughtred +\index{Oughtred}% +and which consists in writing the multiplier underneath +the multiplicand in the reverse order. + +There is one more point, finally, to be remarked +in connexion with the multiplication of numbers containing +\index{Multiplication!decimals@of decimals}% +decimals, and that is that we may alter the +place of the decimal point of either number at will. +For seeing that moving the decimal point from the +right to the left in one of the numbers is equivalent to +dividing the number by~$10$, by~$100$, or by~$1000\dots$, and +that moving the decimal point back in the other number +the same number of places from the left to the +right is tantamount to multiplying that number by~$10$, +$100$, or~$1000$,~$\dots$, it follows that we may push the +decimal point forward in one of the numbers as many +places as we please provided we move it back in the +other number the same number of places, without in +\PageSep{31} +any wise altering the product. In this way we can +always so arrange it that one of the two numbers shall +contain no decimals---which simplifies the question. + +Division is susceptible of a like simplification, for +\index{Decimals!division of}% +\index{Division!decimals@of decimals}% +since the quotient is not altered by multiplying or dividing +\MNote{Division of decimals.} +the dividend and the divisor by the same number, +it follows that in division we may move the decimal +point of both numbers forwards or backwards as +many places as we please, provided we move it the +same distance in each case. Consequently, we can +always reduce the divisor to a whole number---which +facilitates infinitely the operation for the reason that +when there are decimal places in the dividend only, +we may proceed with the division by the common +method and neglect all places giving decimals of a +lower order than those we desire to take account of. + +You know the remarkable property of the number~$9$, +\index{Nine!property of the number|EtSeq}% +whereby if a number be divisible by~$9$ the sum of +its digits is also divisible by~$9$. This property enables +us to tell at once, not only whether a number is divisible +by~$9$ but also what is its remainder from such division. +For we have only to take the sum of its digits +and to divide that sum by~$9$, when the remainder will +be the same as that of the original number divided +by~$9$. + +The demonstration of the foregoing proposition is +not difficult. It reposes upon the fact that the numbers +$10$~less~$1$, $100$~less~$1$, $1000$~less~$1$,~$\dots$ are all divisible +\PageSep{32} +by~$9$,---which seeing that the resulting numbers +are $9$,~$99$, $999$,~$\dots$ is quite obvious. + +If, now, you subtract from a given number the +sum of all its digits, you will have as your remainder +\MNote{Property of the number~$9$.} +the tens' digit multiplied by~$9$, the hundreds' digit +multiplied by~$99$, the thousands' digit multiplied by~$999$, +and so on,---a remainder which is plainly divisible +by~$9$. Consequently, if the sum of the digits is +divisible by~$9$, the original number itself will be so +divisible, and if it is not divisible by~$9$ the original +number likewise will not be divisible thereby. But +the remainder in the one case will be the same as in +the other. + +In the case of the number~$9$, it is evident immediately +that $10$~less~$1$, $100$~less~$1$,~$\dots$ are divisible by~$9$; +but algebra demonstrates that the property in +question holds good for every number~$a$. For it can +be shown that +\[ +a - 1,\quad a^{2} - 1,\quad a^{3} - 1,\quad a^{4} - 1, \dots +\] +are all quantities divisible by~$a - 1$, actual division +giving the quotients +\[ +1,\quad a + 1,\quad a^{2} + a + 1,\quad a^{3} + a^{2} + a + 1, \dots. +\] + +The conclusion is therefore obvious that the aforesaid +property of the number~$9$ holds good in our decimal +system of arithmetic because $9$~is $10$~less~$1$, and +that in any other system founded upon the progression +$a$,~$a^{2}$,~$a^{3}$,~$\dots$ the number~$a - 1$ would enjoy the +same property. Thus in the duodecimal system it +\index{Duodecimal system}% +\PageSep{33} +would be the number~$11$; and in this system every +number, the sum of whose digits was divisible by~$11$, +would also itself be divisible by that number. + +The foregoing property of the number~$9$, now, admits +\index{Nine!property of the number generalised}% +of generalisation, as the following consideration +\MNote{Property of the number~$9$ generalised.} +will show. Since every number in our system is represented +by the sum of certain terms of the progression +$1$,~$10$, $100$, $1000$,~$\dots$, each multiplied by one of +the nine digits $1$,~$2$, $3$, $4$,~$\dots$\Add{,}~$9$, it is easy to see that +the remainder resulting from the division of any number +by a given divisor will be equal to the sum of the +remainders resulting from the division of the terms $1$, +$10$, $100$, $1000$,~$\dots$ by that divisor, each multiplied by +the digit showing how many times the corresponding +term has been taken. Hence, generally, if the given +divisor be called~$D$, and if $m$,~$n$,~$p$,~$\dots$ be the remainders +of the division of the numbers $1$, $10$, $100$, $1000$ +by~$D$, the remainder from the division of any number +whatever~$N$, of which the characters proceeding from +the right to the left are $a$,~$b$,~$c$,~$\dots$, by~$D$ will obviously +be equal to +\[ +ma + nb + pc + \dots. +\] +Accordingly, if for a given divisor~$D$ we know the remainders +$m$,~$n$,~$p$,~$\dots$, which depend solely upon that +divisor and which are always the same for the same +divisor, we have only to write the remainders underneath +the original number, proceeding from the right +to the left, and then to find the different products of +\PageSep{34} +each digit of the number by the digit which is underneath +it. The sum of all these products will be the +\MNote{Theory of remainders\Add{.}} +\index{Remainders!theory of|EtSeq}% +total remainder resulting from the division of the proposed +number by the same divisor~$D$. And if the sum +found is greater than~$D$, we can proceed in the same +manner to seek its remainder from division by~$D$, and +so on until we arrive finally at a remainder which is +less than~$D$, which will be the true remainder sought. +It follows from this that the proposed number cannot +be exactly divisible by the given divisor unless the +last remainder found by this method is zero. + +The remainders resulting from the division of the +terms $1$, $10$, $100$,~$\dots$\Add{,} $1000$, by~$9$ are always unity. +\index{Division!nine@by \textit{nine}}% +Hence, the sum of the digits of any number whatever +is the remainder resulting from the division of that +number by~$9$. The remainders resulting from the division +of the same terms by~$8$ are $1$,~$2$, $4$, $0$, $0$, $0$,~$\dots$. +\index{Division!eight@by \textit{eight}}% +We shall obtain, accordingly, the remainder resulting +from dividing any number by~$8$, by taking the sum +of the first digit to the right, the second digit next +thereto to the left multiplied by~$2$, and the third digit +multiplied by~$4$. + +The remainders resulting from the divisions of the +\index{Division!seven@by \textit{seven}|EtSeq}% +terms $1$, $10$, $100$, $1000$,~$\dots$ by~$7$ are $1$, $3$, $2$, $6$, $4$, $5$, +$1$, $3$,~$\dots$, where the same remainders continually recur +in the same order. If I have, now, the number +$13527541$ to be divided by~$7$, I write it thus with the +above remainders underneath it: +\PageSep{35} +\index{Seven, tests of divisibility by}% +\MNote{Test of divisibility by~$7$.} +\[ +\begin{array}{@{\,}*{2}{r@{}}r@{\,}} +13527&5&41 \\ +31546&2&31 \\ +\hline +&& 1 \\ +&& 12 \\ +&& 10 \\ +&& 42 \\ +&& 8 \\ +&& 25 \\ +&& 3 \\ +&& 3 \\ +\cline{2-3} +& 1&04 \\ +& 2&31 \\ +\cline{2-3} +&& 4 \\ +&& 0 \\ +&& 2 \\ +\cline{3-3} +&& 6 +\end{array} +\] + +Taking the partial products and adding them, I +obtain~$104$, which would be the remainder from the +division of the given number by~$7$, were it not greater +than the divisor. I accordingly repeat the operation +with this remainder, and find for my second remainder~$6$, +which is the real remainder in question. + +I have still to remark with regard to the preceding +remainders and the multiplications which result from +them, that they may be simplified by introducing negative +remainders in the place of remainders which are +greater than half the divisor, and to accomplish this +we have simply to subtract the divisor from each of +such remainders. We obtain thus, instead of the remainders +$6$,~$5$,~$4$, the following: +\[ +-1,\quad -2,\quad -3. +\] +\PageSep{36} +The remainders for the divisor~$7$, accordingly, are +\[ +1,\quad 3,\quad 2,\quad -1,\quad -3,\quad -2,\quad 1,\quad 3, \dots +\] +and so on to infinity. + +\MNote{Negative remainders\Add{.}} +\index{Remainders!negative|EtSeq}% +The preceding example, then, takes the following +form: +\[ +\begin{array}{@{\,}*{3}{r@{}}r@{\,}} +135&27&5&41 \\ +31\underline{2}&\underline{31}&2&31 \\ +\hline + & 7& & 1 \\ + & 6& &12 \\ + &10& &10 \\ +\cline{2-2} + &23& & 3 \\ + & & & 3 \\ +\cline{4-4} + & & &29 \\ +\multicolumn{2}{r}{\llap{\text{subtract}}} & &23 \\ +\cline{4-4} + & & & 6 +\end{array} +\] + +I have placed a bar beneath the digits which are +to be taken negatively, and I have subtracted the sum +of the products of these numbers by those above them +from the sum of the other products. + +The whole question, therefore, resolves itself into +finding for every divisor the remainders resulting from +dividing $1$, $10$, $100$, $1000$\Add{,~$\dots$} by that divisor. This can be +readily done by actual division; but it can be accomplished +more simply by the following consideration. +If $r$~be the remainder from the division of~$10$ by a +given divisor, $r^{2}$~will be the remainder from the division +of~$100$, the square of~$10$, by that divisor; and +consequently it will be necessary merely to subtract +the given divisor from~$r^{2}$ as many times as is requisite +to obtain a positive or negative remainder less than +\PageSep{37} +half of that divisor. Let $s$ be that remainder; we shall +then only have to multiply $s$~by~$r$, the remainder from +the division of~$10$, to obtain the remainder from the +division of~$1000$ by the given divisor, because $1000$~is +$100 × 10$, and so~on. + +For example, dividing $10$ by~$7$ we have a remainder +of~$3$; hence, the remainder from dividing $100$ by~$7$ +will be~$9$, or, subtracting from~$9$ the given divisor~$7$,~$2$. +The remainder from dividing $1000$ by~$7$, then, will +be the product of~$2$ by $3$~or~$6$, or, subtracting the divisor,~$7$,~$-1$. +Again, the remainder from dividing +%[** TN: Removed comma in 10,000 for consistency] +$\Typo{10,000}{10000}$ by~$7$ will be the product of $-1$~and~$3$, or~$-3$, +and so~on. + +Let us now take the divisor~$11$. The remainder +\index{Eleven, the number, test of divisibility by}% +from dividing~$1$ by~$11$ is~$1$, from dividing~$10$ by~$11$ is~$10$, +\MNote{Test of divisibility by~$11$.} +or, subtracting the divisor,~$-1$. The remainder +from dividing~$100$ by~$11$, then, will be the square of~$-1$, +or~$1$; from dividing $1000$ by~$11$ it will be $1$~multiplied +by~$-1$ or\Add{ }$-1$~again, and so on forever, the remainders +forming the infinite series +\[ +1,\quad -1,\quad 1,\quad -1,\quad 1,\quad -1,\dots\Add{.} +\] + +Hence results the remarkable property of the number~$11$, +that if the digits of any number be alternately +added and subtracted, that is to say, if we take the +sum of the first, the third, and the fifth, etc., and subtract +from it the sum of the second, the fourth, the +sixth, etc., we shall obtain the remainder which results +from dividing that number by the number~$11$. +\PageSep{38} + +The preceding theory of remainders is fraught +\index{Remainders!theory of}% +with remarkable consequences, and has given rise to +\MNote{Theory of remainders\Add{.}} +many ingenious and difficult investigations. We can +demonstrate, for example, that if the divisor is a prime +number, the remainders of any progression $1$, $a$, $a^{2}$, +$a^{3}$, $a^{4}$,~$\dots$ form periods which will recur continually +to infinity, and all of which, like the first, begin with +unity; in such wise that when unity reappears among +the remainders we may continue them to infinity by +simply repeating the remainders which precede. It +has also been demonstrated that these periods can +only contain a number of terms which is equal to the +divisor less~$1$ or to an aliquot part of the divisor less~$1$. +But we have not yet been able to determine \textit{à~priori} +this number for any divisor whatever. + +As to the utility of this method for finding the remainder +\index{Theory of remainders, utility of the}% +resulting from dividing a given number by a +given divisor, it is frequently very useful when one +has several numbers to divide by the same number, +and it is required to prepare a table of the remainders. +While as to division by $9$~and~$11$, since that is very +simple, it can be employed as a check upon multiplication +and division. Having found the remainders +from dividing the multiplicand and the multiplier by +either of these numbers it is simply necessary to take +the product of the two remainders so resulting, from +which, after subtracting the divisor as many times as +is requisite, we shall obtain the remainder from dividing +their product by the given divisor,---a remainder +\PageSep{39} +which should agree with the remainder obtained +from treating the actual product in this manner. And +since in division the dividend less the remainder should +\MNote{checks on multiplication and division.} +\index{Checks on multiplication and division}% +be equal to the product of the divisor and the quotient, +the same check may also be applied here to advantage. + +The supposition which I have just made that the +product of the remainders from dividing two numbers +by the same divisor is equal to the remainder from +dividing the product of these numbers by the same +divisor is easily proved, and I here give a general +demonstration of it. + +Let $M$~and~$N$ be two numbers, $D$~the divisor, $p$~and~$q$ +the quotients, and $r$,~$s$ the two remainders. We +shall plainly have +\[ +M = pD + r,\quad +N = qD + s, +\] +from which by multiplying we obtain +\[ +MN = pqD^{2} + spD + rqD + rs; +\] +where it will be seen that all the terms are divisible +by~$D$ with the exception of the last,~$rs$, whence it follows +that $rs$~will be the remainder from dividing~$MN$ +by~$D$. It is further evident that if any multiple whatever +of~$D$, as~$mD$, be subtracted from~$rs$, the result +$rs - mD$ will also be the remainder from dividing~$MN$ +by~$D$. For, putting the value of~$MN$ in the following +form: +\[ +pqD^{2} + spD + rqD + mD + rs - mD, +\] +it is obvious that the remaining terms are all divisible +\PageSep{40} +by~$D$. And this remainder $rs - mD$ can always be +made less than~$D$, or, by employing negative remainders, +less even than~$\dfrac{D}{2}$. + +This is all that I have to say upon multiplication +\MNote{Evolution.} +\index{Evolution}% +and division. I shall not speak of the \emph{extraction of +roots}. The rule is quite simple for square roots; it +leads directly to its goal; trials are unnecessary. As +to cube and higher roots, the occasion rarely arises +for extracting them, and when it does arise the extraction +can be performed with great facility by means +of logarithms, where the degree of exactitude can be +\index{Logarithms}% +carried to as many decimal places as the logarithms +themselves have decimal places. Thus, with seven-place +logarithms we can extract roots having seven +figures, and with the large tables where the logarithms +have been calculated to ten decimal places we +can obtain even ten figures of the result. + +One of the most important operations in arithmetic +\index{Rule!three@of three|EtSeq}% +is the so-called \emph{rule of three}, which consists in +finding the fourth term of a proportion of which the +first three terms are given. + +In the ordinary text-books of arithmetic this rule +has been unnecessarily complicated, having been divided +into simple, direct, inverse, and compound rules +of three. In general it is sufficient to comprehend the +conditions of the problem thoroughly, for the common +rule of three is always applicable where a quantity increases +or diminishes in the same proportion as another. +\PageSep{41} +For example, the price of things augments in +proportion to the quantity of the things, so that the +quantity of the thing being doubled, the price also +\MNote{Rule of three.} +will be doubled, and so on. Similarly, the amount of +work done increases proportionally to the number of +persons employed. Again, things may increase simultaneously +in two different proportions. For example, +the quantity of work done increases with the +number of the persons employed, and also with the +time during which they are employed. Further, there +are things that decrease as others increase. + +Now all this may be embraced in a single, simple +proposition. If a quantity increases both in the ratio +in which one or several other quantities increase and +in that in which one or several other quantities decrease, +it is the same thing as saying that the proposed +quantity increases proportionally to the product of the +quantities which increase with it, divided by the product +of the quantities which simultaneously decrease. +For example, since the quantity of work done increases +proportionally with the number of laborers +\index{Laborers, work of}% +and with the time during which they work and since +it diminishes in proportion as the work becomes more +difficult, we may say that the result is proportional to +the number of laborers multiplied by the number +measuring the time during which they labor, divided +by the number which measures or expresses the difficulty +of the work. + +The further fact should not be lost sight of that +\PageSep{42} +the rule of three is properly applicable only to things +which increase in a constant ratio. For example, it is +\index{Ratios, constant}% +\MNote{Applicability of the rule of three.} +assumed that if a man does a certain amount of work +in one day, two men will do twice that amount in one +day, three men three times that amount, four men +four times that amount,~etc. In reality this is not the +case, but in the rule of proportion it is assumed to be +such, since otherwise we should not be able to employ +it. + +When the law of augmentation or diminution varies, +the rule of three is not applicable, and the ordinary +methods of arithmetic are found wanting. We +must then have recourse to algebra. + +A cask of a certain capacity empties itself in a certain +\index{Efflux, law of}% +time. If we were to conclude from this that a +cask of double that capacity would empty itself in +double the time, we should be mistaken, for it will +empty itself in a much shorter time. The law of efflux +does not follow a constant ratio but a variable +ratio which diminishes with the quantity of liquid remaining +in the cask. + +We know from mechanics that the spaces traversed +\index{Falling stone, spaces traversed by a}% +by a body in uniform motion bear a constant ratio to +the times elapsed. If we travel one mile in one hour, +in two hours we shall travel two miles. But the spaces +traversed by a falling stone are not in a fixed ratio to +the time. If it falls sixteen feet in the first second, it +will fall forty-eight feet in the second second. + +The rule of three is applicable when the ratios are +\PageSep{43} +constant only. And in the majority of affairs of ordinary +life constant ratios are the rule. In general, the +price is always proportional to the quantity, so that if +\MNote{Theory and practice.} +\index{Practice, theory and}% +\index{Theory and practice}% +a given thing has a certain value, two such things will +have twice that value, three three times that value, +four four times that value,~etc. It is the same with +the product of labor relatively to the number of laborers +and to the duration of the labor. Nevertheless, +cases occur in which we may be easily led into error. +If two horses, for example, can pull a load of a certain +\index{Horses}% +weight, it is natural to suppose that four horses +could pull a load of double that weight, six horses a +load of three times that weight. Yet, strictly speaking, +such is not the case. For the inference is based +upon the assumption that the four horses pull alike in +amount and direction, which in practice can scarcely +ever be the case. It so happens that we are frequently +led in our reckonings to results which diverge widely +from reality. But the fault is not the fault of mathematics; +\index{Mathematics!exactness of}% +for mathematics always gives back to us exactly +what we have put into it. The ratio was constant +according to the supposition. The result is founded +upon that supposition. If the supposition is false the +result is necessarily false. Whenever it has been attempted +to charge mathematics with inexactitude, the +accusers have simply attributed to mathematics the +error of the calculator. False or inexact data having +been employed by him, the result also has been necessarily +false or inexact. +\PageSep{44} + +Among the other rules of arithmetic there is one +called \emph{alligation} which deserves special consideration +\index{Alligation!generally|EtSeq}% +\MNote{Alligation.} +from the numerous applications which it has. Although +alligation is mainly used with reference to the +mingling of metals by fusion, it is yet applied generally +\index{Metals, mingling of, by fusion}% +to mixtures of any number of articles of different +values which are to be compounded into a whole of a +like number of parts having a mean value. The rule +\index{Mixtures, rule of|EtSeq}% +\index{Rule!mixtures@of mixtures|EtSeq}% +of alligation, or mixtures, accordingly, has two parts. + +In one we seek the mean and common value of +each part of the mixture, having given the number +of the parts and the particular value of each. In the +second, having given the total number of the parts +and their mean value, we seek the composition of the +mixture itself, or the proportional number of parts of +each ingredient which must be mixed or alligated together. + +Let us suppose, for example, that we have several +\index{Grain, of different prices}% +bushels of grain of different prices, and that we are +desirous of knowing the mean price. The mean price +must be such that if each bushel were of that price the +total price of all the bushels together would still be +the same. Whence it is easy to see that to find the +mean price in the present case we have first simply to +find the total price and to divide it by the number of +bushels. + +In general if we multiply the number of things of +each kind by the value of the unit of that kind and +then divide the sum of all these products by the total +\PageSep{45} +number of things, we shall have the mean value, because +that value multiplied by the number of the +things will again give the total value of all the things +taken together. + +This mean or average value as it is called, is of +\index{Mean values|EtSeq}% +\index{Values!mean|EtSeq}% +great utility in almost all the affairs of life. Whenever +\MNote{Mean values.} +we arrive at a number of different results, we +always like to reduce them to a mean or average expression +which will yield the same total result. + +You will see when you come to the calculus of +\index{Probabilities, calculus of|EtSeq}% +probabilities that this science is almost entirely based +upon the principle we are discussing. + +The registration of births and deaths has rendered +\index{Average life|EtSeq}% +\index{Life insurance|EtSeq}% +\index{Mortality, tables of}% +possible the construction of so-called \emph{tables of mortality} +which show what proportion of a given number of +children born at the same time or in the same year +survive at the end of one year, two years, three years,~etc. +So that we may ask upon this basis what is the +mean or average value of the life of a person at any +given age. If we look up in the tables the number of +people living at a certain age, and then add to this +the number of persons living at all subsequent ages, +it is clear that this sum will give the total number of +years which all living persons of the age in question +have still to live. Consequently, it is only necessary +to divide this sum by the number of living persons of +a certain age in order to obtain the average duration +of life of such persons, or better, the number of years +which each person must live that the total number of +\PageSep{46} +years lived by all shall be the same and that each +person shall have lived an equal number. It has been +\MNote{Probability of life.} +\index{Life, probability of}% +found in this manner by taking the mean of the results +of different tables of mortality, that for an infant +one year old the average duration of life is about +$40$~years; for a child ten years old it is still $40$~years; +for~$20$ it is~$34$; for~$30$ it is~$26$; for~$40$ it is~$23$; for~$50$ +it is~$17$; for~$60$ it is~$12$; for~$70$,~$8$; and for~$80$,~$5$. + +To take another example, a number of different +experiments are made. Three experiments have given~$4$ +\index{Experiments!average of}% +as a result; two experiments have given~$5$; and one +has given~$6$. To find the mean we multiply~$4$ by~$3$, $5$~by~$2$, +and $1$~by~$6$, add the products which gives~$28$, +and divide~$28$ by the number of experiments or~$6$, +which gives~$4\frac{2}{3}$ as the mean result of all the experiments. + +But it will be apparent that this result can be regarded +as exact only upon the condition of our having +supposed that the experiments were all conducted with +equal precision. But it is impossible that such could +have been the case, and it is consequently imperative +to take account of these inequalities, a requirement +which would demand a far more complicated calculus +than that which we have employed, and one which is +now engaging the attention of mathematicians. + +The foregoing is the substance of the first part of +the rule of alligation; the second part is the opposite +of the first. Given the mean value, to find how much +\PageSep{47} +must be taken of each ingredient to produce the required +mean value. + +The problems of the first class are always determinate, +because, as we have just seen, the number of +\MNote{Alternate alligation.} +\index{Alligation!alternate}% +units of each ingredient has simply to be multiplied +by the value of each ingredient and the sum of all +these products divided by the number of the ingredients. + +The problems of the second class, on the other +\index{Analysis!indeterminate|EtSeq}% +\index{Indeterminate analysis|EtSeq}% +hand, are always indeterminate. But the condition +that only positive whole numbers shall be admitted +in the result serves to limit the number of the solutions. + +Suppose that we have two kinds of things, that +the value of the unit of one kind is~$a$, and that of the +unit of the second is~$b$, and that it is required to find +how many units of the first kind and how many units +of the second must be taken to form a mixture or +whole of which the mean value shall be~$m$. + +Call $x$~the number of units of the first kind that +must enter into the mixture, and $y$~the number of units +of the second kind. It is clear that $ax$~will be the +value of the $x$~units of the first kind, and $by$~the value +of the $y$~units of the second. Hence $ax + by$ will be +the total value of the mixture. But the mean value +of the mixture being by supposition~$m$, the sum~$x + y$ +of the units of the mixture multiplied by~$m$, the mean +value of each unit, must give the same total value. +We shall have, therefore, the equation +\PageSep{48} +\[ +ax + by = mx + my. +\] +Transposing to one side the terms multiplied by~$x$ +and to the other the terms multiplied by~$y$, we obtain: +\MNote{Two ingredients.} +\index{Ingredients}% +\[ +(a - m)x = (m - b)y, +\] +and dividing by~$a - m$ we get +\[ +x = \frac{(m - b)y}{a - m}, +\] +whence it appears that the number~$y$ may be taken at +pleasure, for whatever be the value given to~$y$, there +will always be a corresponding value of~$x$ which will +satisfy the problem. + +Such is the general solution which algebra gives. +But if the condition be added that the two numbers $x$~and~$y$ +shall be integers, then $y$~may not be taken at +pleasure. In order to see how we can satisfy this last +condition in the simplest manner, let us divide the +last equation by~$y$, and we shall have +\[ +\frac{x}{y} = \frac{m - b}{a - m}. +\] +For $x$~and~$y$ both to be positive, it is necessary that +the quantities +\[ +m - b \quad\text{and}\quad a - m +\] +should both have the same sign; that is to say, if $a$~is +greater or less than~$m$, then conversely $b$~must be less +or greater than~$m$; or again, $m$~must lie between $a$~and~$b$, +which is evident from the condition of the +problem. Suppose $a$, then, to be the greater and $b$~the +\PageSep{49} +smaller of the two prices. It remains to find the +value of the fraction +\MNote{Rule of mixtures.} +\index{Mixtures, rule of}% +\[ +\frac{m - b}{a - m}, +\] +which if necessary is to be reduced to its lowest terms. +Let~$\dfrac{B}{A}$ be that fraction reduced to its lowest terms. It +is clear that the simplest solution will be that in which +\[ +x = B \quad\text{and}\quad y = A. +\] +But since a fraction is not altered by multiplying its +numerator and denominator by the same number, it +is clear that we may also take $x = nB$ and $y = nA$, $n$~being +any number whatever, provided it is an integer, +for by supposition $x$~and~$y$ must be integers. And it +is easy to prove that these expressions of $x$~and~$y$ are +the only ones which will resolve the proposed problem. +According to the ordinary rule of mixtures, $x$, +the quantity of the dearer ingredient, is made equal +to~$m - b$, the excess of the average price above the +lower price, and $y$~the quantity of the cheaper ingredient +is made equal to~$a - m$, the excess of the higher +price above the average price,---a rule which is contained +directly in the general solution above given. + +Suppose, now, that instead of two kinds of things, +we have three kinds, the values of which beginning +with the highest are $a$,~$b$, and~$c$. Let $x$,~$y$,~$z$ be the +quantities which must be taken of each to form a mixture +or compound having the mean value~$m$. The +sum of the values of the three quantities $x$,~$y$,~$z$ will +then be +\[ +ax + by + cz. +\] +\PageSep{50} +But this total value must be the same as that produced +if all the individual values were~$m$, in which +\MNote{Three ingredients.} +case the total value is obviously +\[ +mx + my + mz. +\] +The following equation, therefore, must be satisfied: +\[ +ax + by + cz = mx + my + mz, +\] +or, more simply, +\[ +(a - m)x + (b - m)y + (c - m)z = 0. +\] +Since there are three unknown quantities in this equation, +two of them may be taken at pleasure. But if +the condition is that they shall be expressed by positive +integers, it is to be observed first that the numbers +\[ +a - m \quad\text{and}\quad m - c +\] +are necessarily positive; so that putting the equation +in the form +\[ +(a - m)x - (m - c)z = (m - b)y, +\] +the question resolves itself into finding two multiples +of the given numbers +\[ +a - m \quad\text{and}\quad m - c +\] +whose difference shall be equal to~$(m - b)y$. + +This question is always resolvable in whole numbers +whatever the given numbers be of which we seek +the multiples, and whatever be the difference between +these multiples. As it is sufficiently remarkable in itself +and may be of utility in many emergencies, we +shall give here a general solution of it, derived from +the properties of continued fractions. +\index{Continued fractions, solution of alligation by|EtSeq}% +\PageSep{51} + +Let $M$~and~$N$ be two whole numbers. Of these +numbers two multiples $xM$,~$zN$ are sought whose difference +is given and equal to~$D$. The following equation +\MNote{General solution.} +will then have to be satisfied +\[ +xM - zN = D, +\] +where $x$~and~$z$ by supposition are whole numbers. In +the first place, it is plain that if $M$~and~$N$ are not +prime to each other, the number~$D$ is divisible by the +greatest common divisor of $M$~and~$N$; and the division +having been performed, we should have a similar +equation in which the numbers $M$~and~$N$ are prime +to each other, so that we are at liberty always to suppose +them reduced to that condition. I now observe +that if we know the solution of the equation for the +case in which the number~$D$ is equal to $+1$~or~$-1$, +we can deduce the solution of it for any value whatever +of~$D$. For example, suppose that we know two +multiples of $M$~and~$N$, say $pM$~and~$qN$, the difference +of which $pM - qN$ is equal to~$±1$. Then obviously +we shall merely have to multiply both these multiples +by the number~$D$ to obtain a difference equal to~$±D$. +For, multiplying the preceding equation by~$D$, we +have +\[ +pDM - qDN = ±D; +\] +and subtracting the latter equation from the original +equation +\[ +xM - zN = D, +\] +or adding it, according as the term~$D$ has the sign +$+$~or~$-$ before it, we obtain +\PageSep{52} +\[ +(x \mp pD)M - (z \mp qD)N = 0, +\] +which gives at once, as we saw above in the rule for +the mixture of two different ingredients, +\MNote{Development.} +\[ +(x \mp pD) = nN,\quad +(z \mp qD) = nM, +\] +$n$~being any number whatever. So that we have generally +\[ +x = nN ± pD \quad\text{and}\quad z = nM ± qD +\] +where $n$~is any whole number, positive or negative. +It remains merely to find two numbers $p$~and~$q$ such +that +\[ +pM - qN = ±1. +\] +Now this question is easily resolvable by continued +fractions. For we have seen in treating of these fractions +that if the fraction~$\dfrac{M}{N}$ be reduced to a continued +fraction, and all the successive fractions approximating +to its value be calculated, the last of these successive +fractions being the fraction~$\dfrac{M}{N}$ itself, then the series +of fractions so reached is such that the difference +between any two consecutive fractions is always equal +to a fraction of which the numerator is unity and the +denominator the product of the two denominators. +For example, designating by~$\dfrac{K}{L}$ the fraction which +immediately precedes the last fraction~$\dfrac{M}{N}$ we obtain +necessarily +\[ +LM - KN = 1 \quad\text{or}\quad -1, +\] +according as $\dfrac{M}{N}$~is greater or less than~$\dfrac{K}{L}$, in other +\PageSep{53} +words, according as the place occupied by the last +fraction~$\dfrac{M}{N}$ in the series of fractions successively approximating +to its value is even or odd; for, the first +\MNote{Resolution by continued fractions.} +fraction of the approximating series is always smaller, +the second larger, the third smaller,~etc., than the +original fraction which is identical with the last fraction +of the series. Making, therefore, +\[ +p = L \quad\text{and}\quad q = K, +\] +the problem of the two multiples will be resolved in +all its generality. + +It is now clear that in order to apply the foregoing +solution to the initial question regarding alligation we +have simply to put +\[ +M = a - m,\quad N = m - c, \quad\text{and}\quad D = (m - b)y; +\] +so that the number~$y$ remains undetermined and may +be taken at pleasure, as may also the number~$N$ which +appears in the expressions for $x$~and~$z$. +\PageSep{54} + + +\Lecture[On Algebra.]{III.}{On Algebra, Particularly the Resolution of +Equations of the Third and +Fourth Degree.} +\index{Algebra!history of|EtSeq}% +\index{Diophantus|EtSeq}% +\index{Geometers, ancient|EtSeq}% +\index{Greeks, mathematics of the|EtSeq}% +\index{Romans, mathematics of the}% +\PgLabel{54} + +\First{Algebra} is a science almost entirely due to the +moderns. I say almost entirely, for we have +\MNote{Algebra among the ancients.} +one treatise from the Greeks, that of Diophantus, who +flourished in the third\footnote + {The period is uncertain. Some say in the fourth century. See Cantor, + \index{Cantor|FN}% + \textit{Geschichte der Mathematik}, 2nd.~ed., Vol.~I., p.~434.---\textit{Trans.}} +century of the Christian era. +This work is the only one which we owe to the ancients +in this branch of mathematics. When I speak +of the ancients I speak of the Greeks only, for the +Romans have left nothing in the sciences, and to all +appearances did nothing. + +Diophantus may be regarded as the inventor of +algebra.\footnote + {On this point, see \textit{Appendix}, \PgRef{151}.---\textit{Trans.}} +From a word in his preface, or rather in his +letter of dedication, (for the ancient geometers were +wont to address their productions to certain of their +friends, a practice exemplified in the prefaces of Apollonius +\index{Apollonius}% +and Archimedes), from a word in his preface, I +\index{Archimedes}% +say, we learn that he was the first to occupy himself +\PageSep{55} +with that branch of arithmetic which has since been +called algebra. + +His work contains the first elements of this science. +He employed to express the unknown quantity a Greek +\index{Unknown quantity}% +\MNote{Diophantus\Add{.}} +letter which corresponds to our~$st$\footnote + {According to a recent conjecture, the character in question is an abbreviation + of~\textgreek{ar} the first letters of \textgreek{>arijm'os}, \textit{number}, the appellation technically + applied by Diophantus to the unknown quantity.---\textit{Trans.}} +and which has +been replaced in the translations by~$N$. To express +the known quantities he employed numbers solely, for +algebra was long destined to be restricted entirely to +the solution of numerical problems. We find, however, +that in setting up his equations consonantly with +the conditions of the problem he uses the known and +the unknown quantities alike. And herein consists +\index{Algebra!essence of}% +virtually the essence of algebra, which is to employ +unknown quantities, to calculate with them as we do +with known quantities, and to form from them one +or several equations from which the value of the unknown +quantities can be determined. Although the +work of Diophantus contains indeterminate problems +\index{Analysis!indeterminate}% +\index{Indeterminate analysis}% +almost exclusively, the solution of which he seeks in +rational numbers,---problems which have been designated +after him \emph{Diophantine problems},---we nevertheless +\index{Diophantine problems}% +find in his work the solution of a number of determinate +problems of the first degree, and even of such +as involve several unknown quantities. In the latter +case, however, the author invariably has recourse to +particular artifices for reducing the problem to a single +unknown quantity,---which is not difficult. He gives, +\PageSep{56} +also, the solution of \emph{equations of the second degree}, but +\index{Equations!second@of the second degree}% +is careful so to arrange them that they never assume +the affected form containing the square and the first +power of the unknown quantity. + +He proposed, for example, the following question +\MNote{Equations of the second degree.} +which involves the general theory of equations of the +second degree: + +\textit{To find two numbers the sum and the product of which +are given.} +\index{Sum and difference, of two numbers}% + +If we call the sum~$a$ and the product~$b$ we have at +once, by the theory of equations, the equation +\[ +x^{2} - ax + b = 0. +\] + +Diophantus resolves this problem in the following +manner. The sum of the two numbers being given, +he seeks their difference, and takes the latter as the +unknown quantity. He then expresses the two numbers +in terms of their sum and difference,---the one +by half the sum plus half the difference, the other by +half the sum less half the difference,---and he has +then simply to satisfy the other condition by equating +their product to the given number. Calling the given +sum~$a$, the unknown difference~$x$, one of the numbers +will be~$\dfrac{a + x}{2}$ and the other will be~$\dfrac{a - x}{2}$. Multiplying +these together we have~$\dfrac{a^{2} - x^{2}}{4}$. The term containing~$x$ +is here eliminated, and equating the quantity +last obtained to the given product, we have the +simple equation +\[ +\frac{a^{2} - x^{2}}{4} = b, +\] +\PageSep{57} +from which we obtain +\[ +x^{2} = a^{2} - 4b, +\] +and from the latter +\[ +x = \sqrt{a^{2} - 4b}. +\] + +Diophantus resolves several other problems of this +class. By appropriately treating the sum or difference +\MNote{Other problems solved by Diophantus.} +as the unknown quantity he always arrives at an +equation in which he has only to extract a square root +to reach the solution of his problem. + +But in the books which have come down to us +(for the entire work of Diophantus has not been preserved) +this author does not proceed beyond equations +of the second degree, and we do not know if he +or any of his successors (for no other work on this +subject has been handed down from antiquity) ever +pushed their researches beyond this point. + +I have still to remark in connexion with the work +\index{Signs $+$ and $-$}% +of Diophantus that he enunciated the principle that +$+$~and~$-$ give~$-$ in multiplication, and $-$~and~$-$,~$+$, +in the form of a definition. But I am of opinion that +this is an error of the copyists, since he is more likely +to have considered it as an axiom, as did Euclid some +\index{Euclid}% +of the principles of geometry. However that may be, +it will be seen that Diophantus regarded the rule of +the signs as a self-evident principle not in need of demonstration. + +The work of Diophantus is of incalculable value +from its containing the first germs of a science which +because of the enormous progress which it has since +\PageSep{58} +made constitutes one of the chiefest glories of the human +intellect. Diophantus was not known in Europe +\MNote{Translations of Diophantus\Add{.}} +until the end of the sixteenth century, the first translation +having been a wretched one by Xylander made +\index{Xylander}% +in~1575 and based upon a manuscript found about the +middle of the sixteenth century in the Vatican library, +\index{Vatican library}% +where it had probably been carried from Greece when +the Turks took possession of Constantinople. +\index{Constantinople}% +\index{Turks}% + +Bachet de Méziriac, one of the earliest members +\index{Bachet de Méziriac}% +\index{Meziriac@Méziriac, Bachet de}% +of the French Academy, and a tolerably good mathematician +for his time, subsequently published~(1621) +a new translation of the work of Diophantus accompanied +by lengthy commentaries, now superfluous. +Bachet's translation was afterwards reprinted with observations +and notes by Fermat, one of the most celebrated +\index{Fermat}% +mathematicians of France, who flourished +\index{France}% +about the middle of the seventeenth century, and of +whom we shall have occasion to speak in the sequel +for the important discoveries which he has made in +analysis. Fermat's edition bears the date of~1670.\footnote + {There have since been published a new critical edition of the text by + M.~Paul Tannery (Leipsic, 1893), and two German translations, one by O.~Schulz + \index{Tannery, M. Paul|FN}% + \index{Wertheim, G.|FN}% + (Berlin, 1822) and one by G.~Wertheim (Leipsic, 1890). Fermat's notes + on Diophantus have been republished in Vol.~I. of the new edition of Fermat's + works (Paris, Gauthier-Villars et Fils, 1891).---\textit{Trans.}} + +It is much to be desired that good translations +\index{Geometers, ancient}% +should be made, not only of the work of Diophantus, +but also of the small number of other mathematical +works which the Greeks have left us.\footnote + {Since Lagrange's time this want has been partly supplied. Not to mention + Euclid, we have, for example, of Archimedes the German translation of + \index{Archimedes|FN}% + Nizze (Stralsund, 1824) and the French translation of Peyrard (Paris, 1807); of + \index{Nizze|FN}% + \index{Peyrard}% + Apollonius, several translations; also modern translations of Hero, Ptolemy, + \index{Apollonius}% + \index{Geometers, ancient}% + \index{Hero}% + \index{Pappus}% + \index{Proclus}% + \index{Ptolemy}% + \index{Theon}% + Pappus, Theon, Proclus, and several others.} +\PageSep{59} + +Prior to the discovery and publication of Diophantus, +however, algebra had already found its way into +\index{Algebra!name@the name of}% +\index{Algebra!among the Arabs|EtSeq}% +Europe. Towards the end of the fifteenth century +there appeared in Venice a work by an Italian Franciscan +monk named Lucas Paciolus on arithmetic and +\index{Paciolus, Lucas}% +geometry in which the elementary rules of algebra +were stated. This book was published (1494) in the +\MNote{Algebra among the Arabs.} +\index{Arabs!Algebra among the|EtSeq}% +early days of the invention of printing, and the fact +\index{Printing, invention of}% +that the name of \emph{algebra} was given to the new science +shows clearly that it came from the Arabs. It is true +that the signification of this Arabic word is still disputed, +but we shall not stop to discuss such matters, +for they are foreign to our purpose. Let it suffice +that the word has become the name for a science that +is universally known, and that there is not the slightest +ambiguity concerning its meaning, since up to the +present time it has never been employed to designate +anything else. + +We do not know whether the Arabs invented algebra +\PgLabel{59} +themselves or whether they took it from the +Greeks.\footnote + {See Appendix, \PgRef{152}.} +There is reason to believe that they possessed +the work of Diophantus, for when the ages of +barbarism and ignorance which followed their first +conquests had passed by, they began to devote themselves +to the sciences and to translate into Arabic all +the Greek works which treated of scientific subjects. +It is reasonable to suppose, therefore, that they also +\PageSep{60} +translated the work of Diophantus and that the same +work stimulated them to push their inquiries farther +in this science. + +Be that as it may, the Europeans, having received +\MNote{Algebra in Europe.} +\index{Algebra!Europe@in Europe}% +\index{Europe, algebra in}% +algebra from the Arabs, were in possession of it one +hundred years before the work of Diophantus was +known to them. They made, however, no progress +beyond equations of the first and second degree. In +\index{Equations!third@of the third degree}% +the work of Paciolus, which we mentioned above, the +\index{Paciolus, Lucas}% +general resolution of equations of the second degree, +such as we now have it, was not given. We find in +this work simply rules, expressed in bad Latin verses, +for resolving each particular case according to the +different combinations of the signs of the terms of +equation, and even these rules applied only to the +case where the roots were real and positive. Negative +\index{Negative roots}% +\index{Roots!negative}% +roots were still regarded as meaningless and superfluous. +It was geometry really that suggested to us the +\index{Geometry}% +use of negative quantities, and herein consists one of +the greatest advantages that have resulted from the +application of algebra to geometry,---a step which we +owe to Descartes. +\index{Descartes}% +\PgLabel{60} + +In the subsequent period the resolution of \emph{equations +of the third degree} was investigated and the discovery +for a particular case ultimately made by a mathematician +\index{Ferrous, Scipio|EtSeq}% +of Bologna named Scipio Ferreus (1515).\footnote + {The date is uncertain. Tartaglia gives 1506, Cardan 1515. Cantor prefers + \index{Cantor|FN}% + \index{Cardan}% + \index{Tartaglia}% + the latter.---\textit{Trans.}} +Two +other Italian mathematicians, Tartaglia and Cardan, +\PageSep{61} +subsequently perfected the solution of Ferreus and +rendered it general for all equations of the third degree. +At this period, Italy, which was the cradle of +\index{Italy, cradle of algebra in Europe}% +\MNote{Tartaglia (1500--1559). Cardan (1501--1576).} +\index{Cardan}% +\index{Tartaglia}% +algebra in Europe, was still almost the sole cultivator +of the science, and it was not until about the middle +of the sixteenth century that treatises on algebra began +to appear in France, Germany, and other countries. +\index{France}% +\index{Germany}% +The works of Peletier and Buteo were the first +\index{Buteo}% +\index{Peletier}% +which France produced in this science, the treatise of +the former having been printed in~1554 and that of +the latter in~1559. + +Tartaglia expounded his solution in bad Italian +verses in a work treating of divers questions and inventions +printed in~1546, a work which enjoys the +distinction of being one of the first to treat of modern +fortifications by bastions. + +About the same time (1545) Cardan published his +treatise \textit{Ars Magna}, or \textit{Algebra}, in which he left +scarcely anything to be desired in the resolution of +equations of the third degree. Cardan was the first to +perceive that equations had several roots and to distinguish +them into positive and negative. But he is +particularly known for having first remarked the so-called +\emph{irreducible case} in which the expression of the +\index{Irreducible case}% +real roots appears in an imaginary form. Cardan convinced +himself from several special cases in which the +equation had rational divisors that the imaginary form +did not prevent the roots from having a real value. +But it remained to be proved that not only were the +\PageSep{62} +roots real in the irreducible case, but that it was impossible +for all three together to be real except in that +case. This proof was afterwards supplied by Vieta, +\index{Vieta}% +and particularly by Albert Girard, from considerations +\index{Girard, Albert}% +touching the trisection of an angle. +\index{Angle, trisection of an}% +\index{Trisection of an angle}% + +We shall revert later on to the \emph{irreducible case of +equations of the third degree}, not solely because it presents +\MNote{The irreducible case.} +a new form of algebraical expressions which +have found extensive application in analysis, but because +it is constantly giving rise to unprofitable inquiries +with a view to reducing the imaginary form to +a real form and because it thus presents in algebra a +problem which may be placed upon the same footing +with the famous problems of the duplication of the +\index{Problems!solution@for solution}% +cube and the squaring of the circle in geometry. +\index{Circle!squaring of the}% +\index{Cube, duplication of the}% +\index{Squaring of the circle}% + +The mathematicians of the period under discussion +\index{Academies, rise of}% +were wont to propound to one another problems +for solution. These problems were in the nature of +public challenges and served to excite and to maintain +in the minds of thinkers that fermentation which +is necessary for the pursuit of science. The challenges +in question were continued down to the beginning of +the eighteenth century by the foremost mathematicians +of Europe, and really did not cease until the rise +of the Academies which fulfilled the same end in a +manner even more conducive to the progress of science, +partly by the union of the knowledge of their +various members, partly by the intercourse which they +maintained between them, and not least by the publication +\PageSep{63} +of their memoirs, which served to disseminate +the new discoveries and observations among all persons +interested in science. + +The challenges of which we speak supplied in a +\index{Academies, rise of}% +measure the lack of Academies, which were not yet +\MNote{Biquadratic equations.} +\index{Biquadratic equations}% +\index{Equations!fourth@of the fourth degree}% +in existence, and we owe to these passages at arms +many important discoveries in analysis. Such was +the resolution of \emph{equations of the fourth degree}, which +was propounded in the following problem. + +%[** TN: Next paragraph centered in the original] +\textit{To find three numbers in continued proportion of which +the sum is~$10$, and the product of the first two~$6$.} + +Generalising and calling the sum of the three numbers~$a$, +the product of the first two~$b$, and the first two +numbers themselves $x$,~$y$, we shall have, first, $xy = b$. +Owing to the continued proportion, the third number +will then be expressed by~$\dfrac{y^{2}}{x}$, so that the remaining +condition will give +\[ +x + y + \frac{y^{2}}{x} = a. +\] +From the first equation we obtain $x = \dfrac{b}{y}$, which substituted +in the second gives +\[ +\frac{b}{y} + y + \frac{y^{2}}{b} = a\Typo{,}{.} +\] +Removing the fractions and arranging the terms, we +get finally +\[ +y^{4} + by^{2} - aby + b^{2} = 0, +\] +an equation of the fourth degree with the second term +missing. + +According to Bombelli, of whom we shall speak +\index{Bombelli}% +\PageSep{64} +again, Louis Ferrari of Bologna resolved the problem +\index{Ferrari, Louis}% +by a highly ingenious method, which consists in +\MNote{Ferrari (1522-1565). Bombelli.} +\index{Bombelli}% +dividing the equation into two parts both of which +permit of the extraction of the square root. To do +this it is necessary to add to the two numbers quantities +whose determination depends on an equation of +the third degree, so that the resolution of equations +\index{Equations!fifth@of the fifth degree}% +of the fourth degree depends upon the resolution of +equations of the third and is therefore subject to the +same drawbacks of the irreducible case. + +The \textit{Algebra} of Bombelli was printed in Bologna +\index{Algebra!Italy@in Italy}% +in~1579\footnote + {This was the second edition. The first edition appeared in Venice in~1572.---\textit{Trans.}} +in the Italian language. It contains not only +the discovery of Ferrari but also divers other important +remarks on equations of the second and third +degree and particularly on the theory of radicals by +means of which the author succeeded in several cases +in extracting the imaginary cube roots of the two +binomials of the formula of the third degree in the irreducible +case, so finding a perfectly real result and +furnishing thus the most direct proof possible of the +reality of this species of expressions. + +Such is a succinct history of the first progress of +algebra in Italy. The solution of equations of the +\index{Italy, cradle of algebra in Europe}% +third and fourth degree was quickly accomplished. +But the successive efforts of mathematicians for over +two centuries have not succeeded in surmounting the +difficulties of the equation of the fifth degree. +\PageSep{65} + +Yet these efforts are far from having been in vain. +They have given rise to the many beautiful theorems +which we possess on the formation of equations, on +\MNote{Theory of equations.} +\index{Equations!theory of}% +the character and signs of the roots, on the transformation +of a given equation into others of which the +roots may be formed at pleasure from the roots of the +given equation, and finally, to the beautiful considerations +concerning the metaphysics of the resolution +of equations from which the most direct method of +arriving at their solution, when possible, has resulted. +All this has been presented to you in previous lectures +and would leave nothing to be desired if it were +but applicable to the resolution of equations of higher +degree. + +Vieta and Descartes in France, Harriot in England, +\index{Descartes}% +\index{Harriot}% +\index{Vieta}% +and Hudde in Holland, were the first after the +\index{Hudde}% +Italians whom we have just mentioned to perfect the +theory of equations, and since their time there is +scarcely a mathematician of note that has not applied +himself to its investigation, so that in its present state +this theory is the result of so many different inquiries +that it is difficult in the extreme to assign the author +of each of the numerous discoveries which constitute it. + +I promised to revert to the irreducible case. To +\index{Irreducible case}% +this end it will be necessary to recall the method +which seems to have led to the original resolution of +equations of the third degree and which is still employed +in the majority of the treatises on algebra. +\PageSep{66} +Let us consider the general equation of the third degree +deprived of its second term, which can always be +removed; in a word, let us consider the equation +\MNote{Equations of the third degree.} +\index{Equations!third@of the third degree}% +\[ +x^{3} + px + q = 0. +\] +Suppose +\[ +x = y + z, +\] +where $y$~and~$z$ are two new unknown quantities, of +which one consequently may be taken at pleasure and +determined as we think most convenient. Substituting +this value for~$x$, we obtain \emph{the transformed equation} +\[ +y^{3} + 3y^{2}z + 3yz^{2} + z^{3} + p(y + z) + q = 0. +\] +Factoring the two terms $3y^{2}z + 3yz^{2}$ we get +\[ +3yz(y + z), +\] +and the transformed equation may be written as follows: +\[ +y^{3} + z^{3} + (3yz + p)(y + z) + q = 0. +\] +Putting the factor multiplying $y + z$ equal to zero,---which +is permissible owing to the two undetermined +quantities involved,---we shall have the two equations +\[ +3yz + p = 0\Typo{.}{} +\] +and +\[ +y^{3} + z^{3} + q = 0\Typo{.}{,} +\] +from which $y$~and~$z$ can be determined. The means +which most naturally suggests itself to this end is to +take from the first equation the value of~$z$, +\[ +z = -\frac{p}{3y}, +\] +and to substitute it in the second equation, removing +the fractions by multiplication. So proceeding, we +\PageSep{67} +obtain the following equation of the sixth degree in~$y$, +called \emph{the reduced equation}, +\MNote{The reduced equation.} +\[ +y^{6} + qy^{3} - \frac{p^{3}}{27} = 0, +\] +which, since it contains two powers only of the unknown +quantity, of which one is the square of the +other, is resolvable after the manner of equations of +the second degree and gives immediately +\[ +y^{3} = -\frac{q}{2} + \sqrt{\frac{q^{2}}{4} + \frac{p^{3}}{27}}, +\] +from which, by extracting the cube root, we get +\[ +y = \sqrt[3]{-\frac{q}{2} + \sqrt{\frac{q^{2}}{4} + \frac{p^{3}}{27}}}, +\] +and finally, +\[ +x = y + z = y - \frac{p}{3y}\Add{.} +\] +This expression for~$x$ may be simplified by remarking +that the product of~$y$ by the radical +\[ + \sqrt[3]{-\frac{q}{2} - \sqrt{\frac{q^{2}}{4} + \frac{p^{3}}{27}}}\Add{,} +\] +supposing all the quantities under the sign to be multiplied +together, is +\[ +\sqrt[3]{-\frac{p^{3}}{27}} = -\frac{p}{3}. +\] +The term $\dfrac{p}{3y}$, accordingly, takes the form +\[ +-\sqrt[3]{-\frac{q}{2} - \sqrt{\frac{q^{2}}{4} + \frac{p^{3}}{27}}}, +\] +and we have +\[ +x = \sqrt[3]{-\frac{q}{2} + \sqrt{\frac{q^{2}}{4} + \frac{p^{3}}{27}}} + + \sqrt[3]{-\frac{q}{2} - \sqrt{\frac{q^{2}}{4} + \frac{p^{3}}{27}}}, +\] +\PageSep{68} +an expression in which the square root underneath the +cubic radical occurs in both its plus and minus forms +and where consequently there can, on this score, be +no occasion for ambiguity. + +This last expression is known as the \emph{Rule of Cardan}, +\index{Cardan}% +\index{Rule!Cardan's}% +\MNote{Cardan's rule.} +and there has hitherto been no method devised +for the resolution of equations of the third degree +which does not lead to it. Since cubic radicals naturally +present but a single value, it was long thought +that Cardan's rule could give but one of the roots of +the equation, and that in order to find the two others +we must have recourse to the original equation and divide +it by~$x - a$, $a$~being the first root found. The +resulting quotient being an equation of the second degree +may be resolved in the usual manner. The division +in question is not only always possible, but it is +also very easy to perform. For in the case we are +considering the equation being +\[ +x^{3} + px + q = 0, +\] +if $a$~is one of the roots we shall have +\[ +a^{3} + pa + q = 0, +\] +which subtracted from the preceding will give +\[ +x^{3} - a^{3} + p(x - a) = 0, +\] +a quantity divisible by~$x - a$ and having as its resulting +quotient +\[ +x^{2} + ax + a^{2} + p = 0; +\] +so that the new equation which is to be resolved for +finding the two other roots will be +\PageSep{69} +\[ +x^{2} + ax + a^{2} + p = 0, +\] +from which we have at once +\[ +x = -\frac{a}{2} ± \sqrt{-p - \frac{3a^{2}}{4}}. +\] + +I see by the \textit{Algebra} of Clairaut, printed in~1746, +\index{Clairaut}% +and by D'Alem\-bert's article on the \emph{Irreducible Case} in +\index{Irreducible case}% +\MNote{The generality of algebra.} +the first \textit{Encyclopædia} that the idea referred to prevailed +even in that period. But it would be the height +of injustice to algebra to accuse it of not yielding results +\index{Algebra!generality@the generality of}% +which were possessed of all the generality of +which the question was susceptible. The sole requisite +is to be able to read the peculiar hand-writing +\index{Algebra!hand-writing of}% +\index{Hand-writing of algebra}% +of algebra, and we shall then be able to see in it everything +which by its nature it can be made to contain. +In the case which we are considering it was forgotten +that every cube root may have three values, as every +square root has two. For the extraction of the cube +root of~$a$ for example is merely equivalent to the resolution +of the equation of the third degree $x^{3} - a = 0$. +Making $x = y\sqrt[3]{a}$, this last equation passes into the +simpler form $y^{3} - 1 = 0$, which has the root $y = 1$. +Then dividing by~$y - 1$ we have +\[ +y^{2} + y + 1 = 0, +\] +from which we deduce directly the two other roots +\[ +y = \frac{-1 ± \sqrt{-3}}{2}. +\] +These three roots, accordingly, are the three cube +roots of unity, and they may be made to give the three +cube roots of any other quantity~$a$ by multiplying +\PageSep{70} +them by the ordinary cube root of that quantity. It +is the same with roots of the fourth, the fifth, and all +the following degrees. For brevity, let us designate +the two roots +\MNote{The three cube roots of a quantity.} +\index{Cube roots of a quantity, the three}% +\[ +\frac{-1 + \sqrt{-3}}{2} \quad\text{and}\quad \frac{-1 - \sqrt{-3}}{2}\Typo{,}{} +\] +by $m$~and~$n$. It will be seen that they are imaginary, +although their cube is real and equal to~$1$, as we may +readily convince ourselves by raising them to the +third power. We have, therefore, for the three cube +roots of~$a$, +\[ +\sqrt[3]{a},\quad m\sqrt[3]{a},\quad n\sqrt[3]{a}. +\] + +Now, in the resolution of the equation of the third +degree above considered, on coming to the reduced +expression $y^{3} = A$, where for brevity we suppose +\[ +A = -\frac{q}{2} + \sqrt{\frac{q^{2}}{4} + \frac{p^{3}}{27}}, +\] +we deduced the following result only: +\[ +y = \sqrt[3]{A}. +\] +But from what we have just seen, it is clear that we +shall have not only +\[ +y = \sqrt[3]{A}, +\] +but also +\[ +y = m\sqrt[3]{A} \quad\text{and}\quad y = n\sqrt[3]{A}. +\] +The root~$x$ of the equation of the third degree which +we found equal to +\[ +y - \frac{p}{3y}, +\] +will therefore have the three following values +\PageSep{71} +\[ +\sqrt[3]{A} - \frac{p}{3\sqrt[3]{A}},\quad +m\sqrt[3]{A} - \frac{p}{3m\sqrt[3]{A}},\quad +n\sqrt[3]{A} - \frac{p}{3n\sqrt[3]{A}}, +\] +\MNote{The roots of equations of the third degree.} +\index{Roots!equations@of equations of the third degree}% +\index{Third degree, equations of the}% +which will be the three roots of the equation proposed. +But making +\[ +B = -\frac{q}{2} - \sqrt{\frac{q^{2}}{4} + \frac{p^{3}}{27}}, +\] +it is clear that +\[ +AB = -\frac{p^{3}}{27}, +\] +whence +\[ +\sqrt[3]{A} × \sqrt[3]{B} = -\frac{p}{3}. +\] +Substituting $\sqrt[3]{B}$ for $-\dfrac{p}{3\sqrt[3]{A}}$, and remarking that +$mn = 1$, and that consequently +\[ +\frac{1}{m} = n,\quad \frac{1}{n} = m, +\] +the three roots which we are considering will be expressed +as follows: +%[** TN: Set on two lines in the original] +\[ +x = \sqrt[3]{A} + \sqrt[3]{B},\quad +x = m\sqrt[3]{A} + n\sqrt[3]{B},\quad +x = n\sqrt[3]{A} + m\sqrt[3]{B}. +\] + +We see, accordingly, that when properly understood +the ordinary method gives the three roots directly, +and gives three only. I have deemed it necessary +to enter upon these slight details for the reason +that if on the one hand the method was long taxed +with being able to give but one root, on the other +hand when it was seen that it really gave three it was +thought that it should have given six, owing to the +\PageSep{72} +false employment of all the possible combinations of +the three cubic roots of unity, viz., $1$,~$m$,~$n$, with the +\index{Unity, three cubic roots of}% +two cubic radicals $\sqrt[3]{A}$~and~$\sqrt[3]{B}$. + +We could have arrived directly at the results which +\MNote{A direct method of reaching the roots.} +we have just found by remarking that the two equations +\[ +y^{3} + z^{3} + q = 0 \quad\text{and}\quad 3yz + p = 0 +\] +give +\[ +y^{3} + z^{3} = -q \quad\text{and}\quad y^{3}z^{3} = -\frac{p^{3}}{27}; +\] +where it will be seen at once that $y^{3}$~and~$z^{3}$ are the +roots of an equation of the second degree of which +the second term is~$q$ and the third~$-\dfrac{p^{3}}{27}$. This equation, +which is called \emph{the reduced equation}, will accordingly +have the form +\[ +u^{2} + qu - \frac{p^{3}}{27} = 0; +\] +and calling $A$~and~$B$ its two roots we shall have immediately +\[ +y = \sqrt[3]{A},\quad z = \sqrt[3]{B}, +\] +where it will be observed that $A$~and~$B$ have the same +values that they had in the previous discussion. Now, +from what has gone before, we shall likewise have +\[ +y = m\sqrt[3]{A} \quad\text{or}\quad y = n\sqrt[3]{A}, +\] +and the same will also hold good for~$z$. But the equation +\[ +zy = -\frac{p}{3}, +\] +of which we have employed the cube only, limits these +\PageSep{73} +values and it is easy to see that the restriction requires +the three corresponding values of~$z$ to be +\[ +\sqrt[3]{B},\quad m\sqrt[3]{B},\quad n\sqrt[3]{B}; +\] +whence follow for the value of~$x$, which is equal to~$y + z$, +the same three values which we found above. + +As to the form of these values it is apparent, first, +that so long as $A$~and~$B$ are real quantities, one only +\MNote{The form of the roots\Add{.}} +of them can be real, for $m$~and~$n$ are imaginary. They +can consequently all three be real only in the case +where the roots $A$~and~$B$ of the reduced equation are +imaginary, that is, when the quantity +\[ +\frac{q^{2}}{4} + \frac{p^{3}}{27} +\] +beneath the radical sign is negative, which happens +only when $p$~is negative and greater than +\[ +3\sqrt[3]{\frac{q^{2}}{4}}. +\] +And this is the so-called \emph{irreducible case}. +\index{Irreducible case}% + +Since in this event +\[ +\frac{q^{2}}{4} + \frac{p^{3}}{27} +\] +is a negative quantity, let us suppose it equal to~$-g^{2}$, +$g$~being any real quantity whatever. Then making, +for the sake of simplicity, +\[ +-\frac{q}{2} = f, +\] +the two roots $A$~and~$B$ of the reduced equation assume +the form +\[ +A = f + g\sqrt{-1},\quad B = f - g\sqrt{-1}. +\] +\PageSep{74} + +Now I say that if $\sqrt[3]{A} + \sqrt[3]{B}$, which is one of the +\MNote{The reality of the roots\Add{.}} +\index{Roots!reality@the reality of the}% +roots of the equation of the third degree, is real, then +the two other roots, expressed by +\[ +m\sqrt[3]{A} + n\sqrt[3]{B} \quad\text{and}\quad n\sqrt[3]{A} + m\sqrt[3]{B}, +\] +will also be real. Put +\[ +\sqrt[3]{A} = t,\quad \sqrt[3]{B} = u; +\] +we shall have +\[ +t + u = h, +\] +where $h$~by hypothesis is a real quantity. Now, +\[ +tu = \sqrt[3]{AB} \quad\text{and}\quad AB = f^{2} + g^{2}, +\] +therefore +\[ +tu = \sqrt[3]{f^{2} + g^{2}}; +\] +squaring the equation $t + u = h$ we have +\[ +t^{2} + 2tu + u^{2} = h^{2}; +\] +from which subtracting~$4tu$ we obtain +\[ +(t - u)^{2} = h^{2} - 4\sqrt[3]{f^{2} + g^{2}}. +\] +I observe that this quantity must necessarily be negative, +for if it were positive and equal to~$k^{2}$ we should +have +\[ +(t - u)^{2} = k^{2}, +\] +whence +\[ +t - u = k. +\] +Then since +\[ +t + u = h, +\] +it would follow that +\[ +t = \frac{h + k}{2} \quad\text{and}\quad u = \frac{h - k}{2}, +\] +\PageSep{75} +both of which are real quantities. But then $t^{3}$~and~$u^{3}$ +would also be real quantities, which is contrary to +our hypothesis, since these quantities are equal to $A$~and~$B$, +both of which are imaginary. + +The quantity +\[ +h^{2} - 4\sqrt[3]{f^{2} + g^{2}} +\] +therefore, is necessarily negative. Let us suppose it +equal to~$-k^{2}$; we shall have then +\[ +(t - u)^{2} = -k^{2}, +\] +and extracting the square root +\[ +t - u = k\sqrt{-1}; +\] +\MNote{The form of the two cubic radicals.} +\index{Cubic radicals}% +\index{Radicals, cubic}% +whence +\[ +t = \frac{h + k\sqrt{-1}}{2} = \sqrt[3]{A},\quad +u = \frac{h - k\sqrt{-1}}{2} = \sqrt[3]{B}. +\] + +Such necessarily will be the form of the two cubic +radicals +\[ +\sqrt[3]{f + g\sqrt{-1}} \quad\text{and}\quad \sqrt[3]{f - g\sqrt{-1}}, +\] +a form at which we can arrive directly by expanding +these roots according to the Newtonian theorem into +series. But since proofs by series are apt to leave +some doubt in the mind, I have sought to render the +preceding discussion entirely independent of them. + +If, therefore, +\[ +\sqrt[3]{A} + \sqrt[3]{B} = h, +\] +we shall have +\[ +\sqrt[3]{A} = \frac{h + k\sqrt{-1}}{2} \quad\text{and}\quad +\sqrt[3]{B} = \frac{h - k\sqrt{-1}}{2}. +\] +Now we have found above that +\[ +m = \frac{-1 + \sqrt{-3}}{2},\quad n = \frac{-1 - \sqrt{-3}}{2}; +\] +\PageSep{76} +wherefore, multiplying these quantities together, we +have +\begin{align*} +m\sqrt[3]{A} + n\sqrt[3]{B} &= \frac{-h + k\sqrt{-3}}{2} \\ +\intertext{and} +n\sqrt[3]{A} + m\sqrt[3]{B} &= \frac{-h - k\sqrt{-3}}{2}, +\end{align*} +which are real quantities. Consequently, if the root~$h$ +\MNote{Condition of the reality of the roots.} +\index{Reality of roots}% +\index{Roots!reality@the reality of the}% +is real, the two other roots also will be real in the +irreducible case and they will be real in that case only. + +But the invariable difficulty is, to demonstrate directly +that +\[ +\sqrt[3]{f + g\sqrt{-1}} + \sqrt[3]{f - g\sqrt{-1}}, +\] +which we have supposed equal to~$h$, is always a real +quantity whatever be the values of $f$~and~$g$. In particular +cases the demonstration can be effected by the +extraction of the cube root, when that is possible. For +example, if $f = 2$, $g = 11$, we shall find that the cube +root of~$2 + 11\sqrt{-1}$ will be~$2 + \sqrt{-1}$, and similarly +that the cube root of~$2 - 11\sqrt{-1}$ will be~$2 - \sqrt{-1}$, +and the sum of the radicals will be~$4$. An infinite +number of examples of this class may be constructed +and it was through the consideration of such instances +that Bombelli became convinced of the reality of the +imaginary expression in the formula for the irreducible +case. But forasmuch as the extraction of cube roots +is in general possible only by means of series, we cannot +arrive in this way at a general and direct demonstration +of the proposition under consideration. +\PageSep{77} + +It is otherwise with square roots and with all roots +of which the exponents are powers of~$2$. For example, +\MNote{Extraction of the square roots of two imaginary binomials.} +\index{Binomials, extraction of the square roots of two imaginary}% +\index{Imaginary binomials, square roots of}% +if we have the expression +\[ +\sqrt{f + g\sqrt{-1}} + \sqrt{f - g\sqrt{-1}}, +\] +composed of two imaginary radicals, its square will be +\[ +2f + 2\sqrt{f^{2} + g^{2}}, +\] +a quantity which is necessarily positive. Extracting +the square root, so as to obtain the equivalent expression, +we have +\[ +\sqrt{2f + 2\sqrt{f^{2} + g^{2}}}, +\] +for the real value of the imaginary quantity we started +with. But if instead of the sum we had had the difference +between the two proposed imaginary radicals +we should then have obtained for its square the following +expression +\[ +2f - 2\sqrt{f^{2} + g^{2}}, +\] +a quantity which is necessarily negative; and, taking +the square root of the latter, we should have obtained +the simple imaginary expression +\[ +\sqrt{2f - 2\sqrt{f^{2} + g^{2}}}. +\] + +Further, if the quantity +\[ +\sqrt[4]{f + g\sqrt{-1}} + \sqrt[4]{f - g\sqrt{-1}} +\] +were given, we should have, by squaring, the form +\begin{multline*} +%[** TN: Moved equality sign to second line] +\sqrt{f + g\sqrt{-1}} + \sqrt{f - g\sqrt{-1}} + 2\sqrt[4]{f^{2} + g^{2}} \\ += \sqrt{2f + 2\sqrt{f^{2} + g^{2}}} + 2\sqrt[4]{f^{2} + g^{2}}, +\end{multline*} +a real and positive quantity. Extracting the square +\PageSep{78} +root of this expression we should obtain a real value +for the original quantity; and so on for all the other +remaining even roots. But if we should attempt to +apply the preceding method to cubic radicals we +should be led again to equations of the third degree +in the irreducible case. + +For example, let +\MNote{Extraction of the cube roots of two imaginary binomials.} +\[ +\sqrt[3]{f + g\sqrt{-1}} + \sqrt[3]{f - g\sqrt{-1}} = x. +\] +Cubing, we get +\[ +2f + 3\sqrt[3]{f^{2} + g^{2}}\left( +\sqrt[3]{f + g\sqrt{-1}} + \sqrt[3]{f - g\sqrt{-1}} +\right) = x^{3}; +\] +that is +\[ +2f + 3x\sqrt[3]{f^{2} + g^{2}} = x^{3}, +\] +or, with the terms properly arranged, +\[ +x^{3} - 3x\sqrt[3]{f^{2} + g^{2}} - 2f = 0, +\] +the general formula of the irreducible case, for +\[ +\frac{1}{4}(2f)^{2} + \frac{1}{27}\bigl(-3\sqrt[3]{f^{2} + g^{2}}\bigr)^{3} + = -g^{2}. +\] +If $g = 0$ we shall have $x = 2\sqrt[3]{f}$. The sole \textit{desideratum}, +therefore, is to demonstrate that if $g$~have any value +whatever, $x$~has a corresponding real value. Now the +second last equation gives +\[ +\sqrt[3]{f^{2} + g^{2}} = \frac{x^{3} - 2f}{3x}\Add{,} +\] +and cubing we get +\[ +f^{2} + g^{2} = \frac{x^{9} - 6x^{6}f + 12x^{3}f^{2} - 8f^{3}}{27x^{3}}, +\] +whence +\[ +g^{2} = \frac{x^{9} - 6x^{6}f - 15x^{3}f^{2} - 8f^{3}}{27x^{3}}, +\] +\PageSep{79} +an equation which may be written as follows +\[ +g^{2} = \frac{(x^{3} - 8f)(x^{3} + f)^{2}}{27x^{3}}, +\] +or, better, thus: +\[ +g^{2} = \frac{1}{27}\left(1 - \frac{8f}{x^{3}}\right)(x^{3} + f)^{2}. +\] + +It is plain from the last expression that $g$~is zero +when $x^{3} = 8f$; further, that $g$~constantly and uninterruptedly +\MNote{General theory of the reality of the roots\Add{.}} +\index{Roots!reality@the reality of the}% +increases as $x$~increases; for the factor +$(x^{3} + f)^{2}$ augments constantly, and the other factor +$1 - \dfrac{8f}{x^{3}}$ also keeps increasing, seeing that as the denominator~$x^{3}$ +increases the negative part~$\dfrac{8f}{x^{3}}$, which is +originally equal to~$1$, keeps constantly growing less +than~$1$. Therefore, if the value of~$x^{3}$ be increased by +insensible degrees from~$8f$ to infinity, the value of~$g^{2}$ +will also augment by insensible and corresponding +degrees from zero to infinity. And therefore, reciprocally, +to every value of~$g^{2}$ from zero to infinity there +must correspond some value of~$x^{3}$ lying between the +limits of~$8f$ and infinity, and since this is so whatever +be the value of~$f$ we may legitimately conclude that, +be the values of $f$~and~$g$ what they may, the corresponding +value of~$x^{3}$ and consequently also of~$x$ is +always real. + +But how is this value of~$x$ to be assigned? It would +\index{Imaginary expressions|EtSeq}% +seem that it can be represented only by an imaginary +expression or by a series which is the development of +an imaginary expression. Are we to regard this class +of imaginary expressions, which correspond to real +\PageSep{80} +values, as constituting a new species of algebraical expressions +which although they are not, like other expressions, +\MNote{Imaginary expressions\Add{.}} +susceptible of being numerically evaluated +in the form in which they exist, yet possess the indisputable +advantage---and this is the chief requisite---that +they can be employed in the operations of algebra +exactly as if they did not contain imaginary expressions. +They further enjoy the advantage of having a +wide range of usefulness in geometrical constructions, +as we shall see in the theory of angular sections, so +\index{Angular sections, theory of}% +that they can always be exactly represented by lines; +while as to their numerical value, we can always find +it approximately and to any degree of exactness that +we desire, by the approximate resolution of the equation +on which they depend, or by the use of the common +trigonometrical tables. + +It is demonstrated in geometry that if in a circle +having the radius~$r$ an arc be taken of which the chord +is~$c$, and that if the chord of the third part of that arc +be called~$x$, we shall have for the determination of~$x$ +the following equation of the third degree +\[ +x^{3} - 3r^{2}x + r^{2}c = 0, +\] +an equation which leads to the irreducible case since +$c$~is always necessarily less than~$2r$, and which, owing +to the two undetermined quantities $r$~and~$c$, may be +taken as the type of all equations of this class. For, +if we compare it with the general equation +\[ +x^{3} + px + q = 0, +\] +we shall have +\PageSep{81} +\[ +r = \sqrt{-\frac{p}{3}} \quad\text{and}\quad c = -\frac{3q}{p} +\] +so that by trisecting the arc corresponding to the +chord~$c$ in a circle of the radius~$r$ we shall obtain at +\MNote{Trisection of an angle.} +\index{Angle, trisection of an}% +\index{Trisection of an angle}% +once the value of a root~$x$, which will be the chord of +the third part of that arc. Now, from the nature of a +circle the same chord~$c$ corresponds not only to the +arc~$s$ but (calling the entire circumference~$u$) also to +the arcs +\[ +u - s,\quad 2u + s,\quad 3u - s, \dots\Add{.} +\] +Also the arcs +\[ +u + s,\quad 2u - s,\quad 3u + s, \dots +\] +have the same chord, but taken negatively, for on +completing a full circumference the chords become +zero and then negative, and they do not become positive +again until the completion of the second circumference, +as you may readily see. Therefore, the values +of~$x$ are not only the chord of the arc~$\dfrac{s}{3}$ but also +the chords of the arcs +\[ +\frac{u - s}{3},\quad \frac{2u + s}{3}, +\] +and these chords will be the three roots of the equation +proposed. If we were to take the succeeding arcs +which have the same chord~$c$ we should be led simply +to the same roots, for the arc~$3u - s$ would give the +chord of~$\dfrac{3u - s}{3}$, that is, of~$u - \dfrac{s}{3}$, which we have already +seen is the same as that of~$\dfrac{s}{3}$, and so with the +rest. +\PageSep{82} + +Since in the irreducible case the coefficient~$p$ is +\index{Irreducible case}% +necessarily negative, the value of the given chord~$c$ +\MNote{Trigonometrical solution.} +will be positive or negative according as $q$~is positive +or negative. In the first case, we take for~$s$ the arc +subtended by the positive chord $c = -\dfrac{3q}{p}$. The second +case is reducible to the first by making $x$~negative, +whereby the sign of the last term is changed; so +that if again we take for~$s$ an arc subtended by the +positive chord~$\dfrac{3q}{p}$, we shall have simply to change +the sign of the three roots. + +Although the preceding discussion may be deemed +sufficient to dispel all doubts concerning the nature +of the roots of equations of the third degree, we propose +\index{Equations!third@of the third degree}% +\index{Third degree, equations of the}% +adding to it a few reflexions concerning the +method by which the roots are found. The method +which we have propounded in the foregoing and which +is commonly called \emph{Cardan's method}, although it seems +\index{Cardan}% +to me that we owe it to Hudde, has been frequently +\index{Hudde}% +criticised, and will doubtless always be criticised, for +giving the roots in the irreducible case in an imaginary +form, solely because a supposition is here made which +is contradictory to the nature of the equation. For +the very gist of the method consists in its supposing +\index{Undetermined quantities}% +the unknown quantity equal to two undetermined +quantities $y + z$, in order to enable us afterwards to +separate the resulting equation +\[ +y^{3} + z^{3} + (3yz + p)(y + z) + q = 0 +\] +into the two following: +\PageSep{83} +\[ +3yz + p = 0 \quad\text{and}\quad y^{3} + z^{3} + q = 0. +\] +Now, throwing the first of these into the form +\MNote{The method of indeterminates.} +\index{Indeterminates, the method of}% +\[ +y^{3}z^{3} = -\frac{p^{3}}{27} +\] +it is plain that the question reduces itself to finding +two numbers $y^{3}$~and~$z^{3}$ of which the sum is~$-q$ and +the product~$-\dfrac{p^{3}}{27}$, which is impossible unless the +square of half the sum exceed the product, for the +difference between these two quantities is equal to the +square of half the difference of the numbers sought. + +The natural conclusion was that it was not at all +astonishing that we should reach imaginary expressions +\index{Imaginary expressions}% +when proceeding from a supposition which it +was impossible to express in numbers, and so some +writers have been induced to believe that by adopting +a different course the expression in question could be +avoided and the roots all obtained in their real form. +\index{Reality of roots}% +\index{Roots!reality@the reality of the}% + +Since pretty much the same objection can be advanced +against the other methods which have since +been found and which are all more or less based upon +the method of indeterminates, that is, the introduction +of certain arbitrary quantities to be determined +so as to satisfy the conditions of the problem,---we +propose to consider the question of the reality of the +roots by itself and independently of any supposition +whatever. Let us take again the equation +\[ +x^{3} + px + q = 0; +\] +and let us suppose that its three roots are $a$,~$b$,~$c$. +\PageSep{84} + +By the theory of equations the left-hand side of +\index{Equations!theory of}% +the preceding expression is the product of three quantities +\MNote{An independent consideration.} +\[ +x - a,\quad x - b,\quad x - c, +\] +which, multiplied together, give +\[ +x^{3} - (a + b + c)x^{2} + (ab + ac + bc)x - abc; +\] +and comparing the corresponding terms, we have +\[ +a + b + c = 0,\quad +ab + ac + bc = p,\quad +abc = -q. +\] +As the degree of the equation is odd we may be certain, +as you doubtless already know and in any event +will clearly see from the lecture which is to follow, +that it has necessarily one real root. Let that root +be~$c$. The first of the three equations which we have +just found will then give +\[ +c = -a - b, +\] +whence it is plain that $a + b$ is also necessarily a real +quantity. Substituting the last value of~$c$ in the second +and third equations, we have +\[ +ab - a^{2} - ab - ab - b^{2} = p,\quad -ab(a + b) = -q, +\] +or +\[ +a^{2} + ab + b^{2} = -p,\quad ab(a + b) = q, +\] +from which are to be found $a$~and~$b$. The last equation +gives $ab = \dfrac{q}{a + b}$ from which I conclude that $ab$ +also is necessarily a real quantity. Let us consider +now the quantity $\dfrac{q^{2}}{4} + \dfrac{p^{3}}{27}$ or, clearing of fractions, the +quantity $27q^{2} + 4p^{3}$, upon the sign of which the irreducible +case depends. Substituting in this for $p$~and~$q$ +their value as given above in terms of $a$~and~$b$, +\PageSep{85} +we shall find that when the necessary reductions are +made the quantity in question is equal to the square of +\MNote{New view of the reality of the roots.} +\index{Reality of roots}% +\index{Roots!reality@the reality of the}% +\[ +2a^{3} - 2b^{3} + 3a^{2}b - 3ab^{2} +\] +taken negatively; so that by changing the signs and +extracting the square root we shall have +\[ +2a^{3} - 2b^{3} + 3a^{2}b - 3ab^{2} = \sqrt{-27q^{2} - 4p^{3}}, +\] +whence it is easy to infer that the two roots $a$~and~$b$ +cannot be real unless the quantity $27q^{2} + 4p^{3}$ be negative. +But I shall show that in that case, which is as +we know the irreducible case, the two roots $a$~and~$b$ +are necessarily real. The quantity +\[ +2a^{3} - 2b^{3} + 3a^{2}b - 3ab^{2} +\] +may be reduced to the form +\[ +(a - b)(2a^{2} + 2b^{2} + 5ab), +\] +as multiplication will show. Now, we have already +seen that the two quantities $a + b$ and $ab$ are necessarily +real, whence it follows that +\[ +2a^{2} + 2b^{2} + 5ab = 2(a + b)^2 + ab +\] +is also necessarily real. Hence the other factor~$a - b$ +is also real when the radical $\sqrt{-27q^{2} - 4p^{3}}$ is real. +Therefore $a + b$ and $a - b$ being real quantities, it follows +that $a$~and~$b$ are real. + +We have already derived the preceding theorems +from the form of the roots themselves. But the present +demonstration is in some respects more general +and more direct, being deduced from the fundamental +principles of the problem itself. We have made no +\PageSep{86} +suppositions, and the particular nature of the irreducible +case has introduced no imaginary quantities. + +\MNote{Final solution on the new view.} +But the values of $a$~and~$b$ still remain to be found +from the preceding equations. And to this end I observe +that the left-hand side of the equation +\[ +a^{3} - b^{3} + \frac{3}{2}(a^{2}b - ab^{2}) + = \frac{1}{2}\sqrt{-27q^{2} - 4p^{3}} +\] +can be made a perfect cube by adding the left-hand +side of the equation +\[ +ab(a + b) = q, +\] +multiplied by $\dfrac{3\sqrt{-3}}{2}$, and that the root of this cube is +\[ +\frac{1 - \sqrt{-3}}{2}b - \frac{1 + \sqrt{-3}}{2}a +\] +so that, extracting the cube root of both sides, we +shall have the expression +\[ +\frac{1 - \sqrt{-3}}{2}b - \frac{1 + \sqrt{-3}}{2}a +\] +expressed in known quantities. And since the radical +$\sqrt{-3}$ may also be taken negatively, we shall also +have the expression +\[ +\frac{1 + \sqrt{-3}}{2}b - \frac{1 - \sqrt{-3}}{2}a +\] +expressed in known quantities, from which the values +of $a$~and~$b$ can be deduced. And these values will +contain the imaginary quantity~$\sqrt{-3}$, which was introduced +by multiplication, and will be reducible to +the same form with the two roots +\PageSep{87} +\[ +m\sqrt[3]{A} + n\sqrt[3]{B} \quad\text{and}\quad n\sqrt[3]{A} + m\sqrt[3]{B}, +\] +which we found above. The third root +\MNote{Office of imaginary quantities.} +\[ +c = -a - b +\] +will then be expressed by $\sqrt[3]{A} + \sqrt[3]{B}$. + +By this method we see that the imaginary quantities +\index{Imaginary quantities, office of the}% +employed have simply served to facilitate the extraction +of the cube root without which we could not +determine separately the values of $a$~and~$b$. And since +it is apparently impossible to attain this object by a +different method, we may regard it as a demonstrated +truth that the general expression of the roots of an +equation of the third degree in the irreducible case +cannot be rendered independent of imaginary quantities. + +Let us now pass to \emph{equations of the fourth degree}. +\index{Equations!fourth@of the fourth degree}% +We have already said that the artifice which was originally +employed for resolving these equations consisted +in so arranging them that the square root of +the two sides could be extracted, by which they were +reduced to equations of the second degree. The following +is the procedure employed. Let +\[ +x^{4} + px^{2} + qx + r = 0 +\] +be the general equation of the fourth degree deprived +of its second term, which can always be eliminated, +as you know, by increasing or diminishing the roots +by a suitable quantity. Let the equation be put in +the form +\[ +x^{4} = -px^{2} - qx - r, +\] +\PageSep{88} +and to each side let there be added the terms $2x^{2}y + y^{2}$, +which contain a new undetermined quantity~$y$ but +\MNote{Biquadratic equations.} +\index{Biquadratic equations}% +\index{Equations!biquadratic}% +which still leave the left-hand side of the equation a +square. We shall then have +\[ +(x^{2} + y)^{2} = (2y - p)x^{2} - qx + y^{2} - r. +\] +We must now make the right-hand side also a square. +To this end it is necessary that +\[ +4(2y - p)(y^{2} - r) = q^{2}, +\] +in which case the square root of the right-hand side +will have the form +\[ +x\sqrt{2y - p} - \frac{q}{2\sqrt{2y - p}}. +\] +Supposing then that the quantity~$y$ satisfies the equation +\[ +4(2y - p)(y^{2} - r) = q^{2}, +\] +which developed becomes +\[ +y^{3} - \frac{py^{2}}{2} - ry + \frac{pr}{2} - \frac{q^{2}}{8} = 0, +\] +and which, as we see, is an equation of the third degree, +the equation originally given may be reduced to +the following by extracting the square root of its two +members,~viz.: +\[ +x^{2} + y = x\sqrt{2y - p} - \frac{q}{2\sqrt{2y - p}}, +\] +where we may take either the plus or the positive +value for the radical $\sqrt{2y - p}$, and shall consequently +have two equations of the second degree to which the +given equation has been reduced and the roots of +which will give the four roots of the original equation. +\PageSep{89} +All of which furnishes us with our first instance of the +decomposition of equations into others of lower degree. + +The method of Descartes which is commonly followed +\index{Descartes}% +in the elements of algebra is based upon the +\MNote{The method of Descartes.} +same principle and consists in assuming at the outset +that the proposed equation is produced by the multiplication +of two equations of the second degree, as +\[ +x^{2} - ux + s = 0 \quad\text{and}\quad x^{2} + ux + t = 0, +\] +where $u$,~$s$, and~$t$ are indeterminate coefficients. Multiplying +\index{Coefficients!indeterminate}% +\index{Indeterminate coefficients}% +them together we have +\[ +x^{4} + (s + t - u^{2})x + (s - t)ux + st = 0, +\] +comparison of which with the original equation gives +\[ +s + t - u^{2} = p,\quad (s - t)u = q \quad\text{and}\quad st = r. +\] +The first two equations give +\[ +2s = p + u^{2} + \frac{q}{u},\quad 2t = p + u^{2} - \frac{q}{u}. +\] +And if these values be substituted in the third equation +of condition $st = r$, we shall have an equation of +the sixth degree in~$u$, which owing to its containing +only even powers of~$u$ is resolvable by the rules for +cubic equations. And if we substitute in this equation +$2y - p$ for~$u^{2}$, we shall obtain in~$y$ the same reduced +equation that we found above by the old method. + +Having the value of~$u^{2}$ we have also the values of +$s$~and~$t$, and our equation of the fourth degree will be +decomposed into two equations of the second degree +which will give the four roots sought. This method, +as well as the preceding, has been the occasion of some +\PageSep{90} +hesitancy as to which of the three roots of the reduced +cubic equation in $u^{2}$ or~$y$ should be employed. +\MNote{The determined character of the roots\Add{.}} +The difficulty has been well resolved in Clairaut's +\index{Clairaut}% +\textit{Algebra}, where we are led to see directly that we always +obtain the same four roots or values of~$x$ whatever +root of the reduced equation we employ. But +this generality is needless and prejudicial to the simplicity +which is to be desired in the expression of +the roots of the proposed equation, and we should +prefer the formulæ which you have learned in the +principal course and in which the three roots of the +reduced equation are contained in exactly the same +manner. + +The following is another method of reaching the +same formulæ, less direct than that which has already +been expounded to you, but which, on the other hand +has the advantage of being analogous to the method +of Cardan for equations of the third degree. +\index{Cardan}% + +I take up again the equation +\[ +x^{4} + px^{2} + qx + r = 0, +\] +and I suppose +\[ +x = y + z + t. +\] +Squaring I obtain +\[ +x^{2} = y^{2} + z^{2} + t^{2} + 2(yz + yt + zt). +\] +Squaring again I have +\[ +%[** TN: Set on two lines in original] +x^{4} = (y^{2} + z^{2} + t^{2})^{2} + 4(y^{2} + z^{2} + t^{2})(yz + yt + zt) ++ 4(yz + yt + zt)^{2}; +\] +but +\begin{align*} +%[** TN: Re-broken] +(yz + yt + zt)^{2} + &= y^{2}z^{2} + y^{2}t^{2} + z^{2}t^{2} + + 2y^{2}zt + 2yz^{2}t + 2yzt^{2} \\ + &= y^{2}z^{2} + y^{2}t^{2} + z^{2}t^{2} + 2yzt(y + z + t). +\end{align*} +\PageSep{91} +Substituting these three values of $x$,~$x^{2}$, and~$x^{4}$ in the +original equation, and bringing together the terms +multiplied by~$y + z + t$ and the terms multiplied by~$yz + yt + zt$, +\MNote{A third method.} +I have the transformed equation +\begin{gather*} +%[** TN: Re-broken] +(y^{2} + z^{2} + t^{2})^{2} + p(y^{2} + z^{2} + t^{2}) \\ + + \bigl[4(y^{2} + z^{2} + t^{2}) + 2p\bigr](yz + yt + zt) \\ + + 4(y^{2}z^{2} + y^{2}t^{2} + z^{2}t^{2}) + + (8yzt + q)(y + z + t) + r = 0. +\end{gather*} +We now proceed as we did with equations of the third +degree, where we caused the terms containing $y + z$ +to vanish, and in the same manner cause here the +terms containing $y + z + t$ and $yz + yt + zt$ to disappear, +which will give us the two equations of condition +\[ +8yzt + q = 0 \quad\text{and}\quad 4(y^{2} + z^{2} + t^{2}) + 2p = 0. +\] + +There remains the equation +\[ +(y^{2} + z^{2} + t^{2})^{2} + p(y^{2} + z^{2} + t^{2}) + + 4(y^{2}z^{2} + y^{2}t^{2} + z^{2}t^{2}) + r = 0; +\] +and the three together will determine the quantities +$y$,~$z$, and~$t$. The second gives immediately +\[ +y^{2} + z^{2} + t^{2} = -\frac{p}{2}, +\] +which substituted in the third gives +\[ +y^{2}z^{2} + y^{2}t^{2} + z^{2}t^{2} = \frac{p^{2}}{16} - \frac{r}{4}\Add{.} +\] +The first, raised to its square, gives +\[ +y^{2}z^{2}t^{2} = \frac{q^{2}}{64}. +\] +Hence, by the general theory of equations the three +\PageSep{92} +quantities $y^{2}$,~$z^{2}$,~$t^{2}$ will be the roots of an equation of +the third degree having the form +\MNote{The reduced equation.} +\[ +u^{3} + \frac{p}{2} u^{2} + + \left(\frac{p^{2}}{16} - \frac{r}{4}\right)u + - \frac{q^{2}}{64} = 0; +\] +so that if the three roots of this equation, which we +will call \emph{the reduced equation}, be designated by $a$,~$b$,~$c$, +we shall have +\[ +y = \sqrta,\quad z = \sqrt{b},\quad t = \sqrtc, +\] +and the value of~$x$ will be expressed by +\[ +\sqrta + \sqrt{b} + \sqrtc. +\] +Since the three radicals may each be taken with the +plus sign or the minus sign, we should have, if all +possible combinations were taken, eight different values +for~$x$. It is to be observed, however, that in the +preceding analysis we employed the equation $y^{2}z^{2}t^{2} = \dfrac{q^{2}}{64}$, +whereas the equation immediately given is $yzt = -\dfrac{q}{8}$. +Hence the product of the three quantities $y$,~$z$,~$t$, +that is to say of the three radicals +\[ +\sqrta,\quad \sqrt{b}, \quad \sqrtc, +\] +must have the contrary sign to that of the quantity~$q$. +Therefore, if $q$~be a negative quantity, either three +positive radicals or one positive and two negative radicals +must be contained in the expression for~$x$. And +in this case we shall have the following four combinations +only: +\begin{alignat*}{2} + &\sqrta + \sqrt{b} + \sqrtc,\qquad && \sqrta - \sqrt{b} - \sqrtc,\\ +-&\sqrta + \sqrt{b} - \sqrtc, &\Typo{}{-}&\sqrta - \sqrt{b} + \sqrtc, +\end{alignat*} +\PageSep{93} +which will be the four roots of the proposed equation +of the fourth degree. But if $q$~be a positive quantity, +either three negative radicals or one negative and two +\MNote{Euler's formulæ.} +positive radicals must be contained in the expression +for~$x$, which will give the following four other combinations +as the roots of the proposed equation:\footnote + {These simple and elegant formulæ are due to Euler. But M.~Bret, Professor + \index{Bret, M.|FN}% + \index{Euler}% + of Mathematics at Grenoble, has made the important observation (see + the \textit{Correspondance sur l'\Typo{Ecole}{École} Polytechnique}, t.~II., 3\ieme~Cahier, p.~217) that + they can give false values when imaginary quantities occur among the four + roots. + + In order to remove all difficulty and ambiguity we have only to substitute + for one of these radicals its value as derived from the equation $\sqrta\sqrt{b}\sqrtc = -\dfrac{q}{8}$. + Then the formula + \[ + \sqrta + \sqrt{b} - \frac{q}{8\sqrta\sqrt{b}} + \] + will give the four roots of the original equation by taking for $a$~and~$b$ any two + of the three roots of the reduced equation, and by taking the two radicals + successively positive and negative. + + The preceding remark should be added to article~777 of Euler's \textit{Algebra} + and to article~37 of the author's Note~XIII of the \textit{Traité de la résolution des + équations numériques}.} +\begin{alignat*}{2} +-&\sqrta - \sqrt{b} - \sqrtc,\qquad & -&\sqrta + \sqrt{b} + \sqrtc, \displaybreak[1] \\ + &\sqrta - \sqrt{b} + \sqrtc, &&\sqrta + \sqrt{b} - \sqrtc. +\end{alignat*} + +Now if the three roots $a$,~$b$,~$c$ of the reduced equation +\index{Reality of roots}% +\index{Roots!reality@the reality of the}% +\index{Three roots, reality of the}% +of the third degree are all real and positive, it is +evident that the four preceding roots will also all be +real. But if among the three real roots $a$,~$b$,~$c$, any +are negative, obviously the four roots of the given +biquadratic equation will be imaginary. Hence, besides +the condition for the reality of the three roots of +the reduced equation it is also requisite in the first +case, agreeably to the well-known rule of Descartes, +\index{Descartes}% +\PageSep{94} +that the coefficients of the terms of the reduced equation +should be alternatively positive and negative, and +\MNote{Roots of a biquadratic equation.} +\index{Biquadratic equations}% +\index{Roots!biquadratic@of a biquadratic equation}% +consequently that $p$~should be negative and $\dfrac{p^{2}}{16} - \dfrac{r}{4}$ +positive, that is, $p^{2} > 4r$. If one of these conditions +is not realised the proposed biquadratic equation cannot +have four real roots. If the reduced equation have +but one real root, it will be observed, first, that by +reason of its last term being negative the one real root +of the equation must necessarily be positive. It is +then easy to see from the general expressions which +we gave for the roots of cubic equations deprived of +their second term,---a form to which the reduced equation +in~$u$ can easily be brought by simply increasing +all the roots by the quantity~$\dfrac{p}{6}$,---it is easy to see, I +say, that the two imaginary roots of this equation will +be of the form +\[ +f + g\sqrt{-1} \quad\text{and}\quad f - g\sqrt{-1}. +\] +Therefore, supposing $a$~to be the real root and $b$,~$c$ the +two imaginary roots, $\sqrta$~will be a real quantity and +$\sqrt{b} + \sqrtc$ will also be real for reasons which we have +given above; while $\sqrt{b} - \sqrtc$ on the other hand will +be imaginary. Whence it follows that of the four +roots of the proposed biquadratic equation, the two +first will be real and the two others will be imaginary. + +As for the rest, if we make $u = s - \dfrac{p}{6}$ in the reduced +equation in~$u$, so as to eliminate the second +term and to reduce it to the form which we have above +\PageSep{95} +examined, we shall have the following transformed +equation in~$s$: +\[ +s^{3} - \left(\frac{p^{2}}{48} + \frac{r}{4}\right)s + - \frac{p^{3}}{864} + \frac{pr}{24} - \frac{q^{2}}{64} = 0; +\] +and the condition for the reality of the three roots of +the reduced equation will be +\[ +4\left(\frac{p^{2}}{48} + \frac{r}{4}\right)^{3} + > 27\left(\frac{p^{3}}{864} - \frac{pr}{24} + \frac{q^{2}}{64}\right)^{2}. +\] +\PageSep{96}%XXXX + + +\Lecture{IV.}{On the Resolution of Numerical Equations.} +\index{Numerical equations!resolution of|(}% + +\First{We} have seen how equations of the second, the +third, and the fourth degree can be resolved. +\MNote{Limits of the algebraical resolution of equations.} +\index{Algebraical resolution of equations!limits of the}% +\index{Equations!limits of the algebraical resolution of}% +The fifth degree constitutes a sort of barrier to analysts, +\index{Equations!fifth@of the fifth degree}% +\index{Fifth degree, equations of the}% +which by their greatest efforts they have never +yet been able to surmount, and the general resolution +of equations is one of the things that are still to be +desired in algebra. I say in algebra, for if with the +third degree the analytical expression of the roots is +insufficient for determining in all cases their numerical +value, \textit{a~fortiori} must it be so with equations of a +higher degree; and so we find ourselves constantly +under the necessity of having recourse to other means +for determining numerically the roots of a given equation,---for +to determine these roots is in the last resort +the object of the solution of all problems which +necessity or curiosity may offer. + +I propose here to set forth the principal artifices +which have been devised for accomplishing this important +object. Let us consider any equation of the +\index{Equations!mth@of the $m$th degree}% +$m$th~degree, represented by the formula +\PageSep{97} +\[ +x^{m} + px^{m-1} + qx^{m-2} + rx^{m-3} + \dots + u = 0, +\] +in which $x$~is the unknown quantity, $p$,~$q$,~$r$,~$\dots$ the +known positive or negative coefficients, and $u$~the +\MNote{Conditions of the resolution of numerical equations.} +\index{Numerical equations!conditions of the resolution of}% +last term, not containing~$x$ and consequently also a +known quantity. It is assumed that the values of +these coefficients are given either in numbers or in +lines; (it is indifferent which, seeing that by taking a +given line as the unit or common measure of the rest +we can assign to all the lines numerical values;) and it +is clear that this assumption is always permissible +when the equation is the result of a real and determinate +problem. The problem set us is to find the value, +or, if there be several, the values, of~$x$ which satisfy the +equation, i.e.\Add{,} which render the sum of all its terms +zero. Now any other value which may be given to~$x$ +will render that sum equal to some positive or negative +quantity, for since only integral powers of~$x$ enter +the equation, it is plain that every real value of~$x$ +will also give a real value for the quantity in question. +The more that value approaches to zero, the more +will the value of~$x$ which has produced it approach to +a root of the equation. And if we find two values of~$x$, +of which one renders the sum of the terms equal to +a positive quantity and the other to a negative quantity, +we may be assured in advance that between these +two values there will of necessity be at least one value +which will render the expression zero and will consequently +be a root of the equation. + +Let $P$~stand for the sum of all the terms of the +\PageSep{98} +equation having the sign~$+$ and $Q$~for the sum of all +the terms having the sign~$-$; then the equation will +be represented by +\[ +P - Q = 0. +\] +Let us suppose, for further simplicity, that the two +\MNote{Position of the roots of numerical equations.} +\index{Numerical equations!position of the roots of}% +values of~$x$ in question are positive, that $A$~is the +smaller, $B$~the greater, and that the substitution of~$A$ +for~$x$ gives a negative result and the substitution of~$B$ +for~$x$ a positive result; i.e., that the value of~$P - Q$ +is negative when $x = A$, and positive when $x = B$. + +Consequently, when $x = A$, $P$~will be less than~$Q$, +and when $x = B$, $P$~will be greater than~$Q$. Now, +from the very form of the quantities $P$~and~$Q$, which +contain only positive terms and whole positive powers +of~$x$, it is clear that these quantities augment continuously +as $x$~augments, and that by making $x$ augment by +insensible degrees through all values from $A$~to~$B$, they +also will augment by insensible degrees but in such +wise that $P$~will increase more than~$Q$, seeing that +from having been smaller than~$Q$ it will have become +greater. Therefore, there must of necessity be some +expression for the value of~$x$ between $A$~and~$B$ which +will make $P = Q$; just as two moving bodies which +\index{Moving bodies, two}% +we suppose to be travelling along the same straight +line and which having started simultaneously from +two different points arrive simultaneously at two other +points but in such wise that the body which was at first +in the rear is now in advance of the other,---just as +two such bodies, I say, must necessarily meet at some +\PageSep{99} +point in their path. That value of~$x$, therefore, which +will make $P = Q$ will be one of the roots of the equation, +and such a value will lie of necessity between $A$~and~$B$. + +The same reasoning may be employed for the +\MNote{Position of the roots of numerical equations.} +other cases, and always with the same result. + +The proposition in question is also demonstrable +by a direct consideration of the equation itself, which +may be regarded as made up of the product of the +factors, +\[ +x - a,\quad x - b,\quad x - c,\dots, +\] +where $a$,~$b$,~$c$,~$\dots$ are the roots. For it is obvious +that this product cannot, by the substitution of two +different values for~$x$, be made to change its sign, unless +at least one of the factors changes its sign. And +it is likewise easy to see that if more than one of the +factors changes its sign, their number must be odd. +Thus, if $A$~and~$B$ are two values of~$x$ for which the +factor $x - b$, for example, has opposite signs, then if +$A$~be larger than~$b$, necessarily $B$~must be smaller +than~$b$, or \textit{vice versa}. Perforce, then, the root~$b$ will +fall between the two quantities $A$~and~$B$. + +As for imaginary roots, if there be any in the equation, +\index{Imaginary roots, occur in pairs}% +since it has been demonstrated that they always +occur in pairs and are of the form +\[ +f + g\sqrt{-1},\quad f - g\sqrt{-1}, +\] +therefore if $a$~and~$b$ are imaginary, the product of the +factors $x - a$ and $x - b$ will be +\PageSep{100} +\[ +(x - f - g\sqrt{-1})(x - f + g\sqrt{-1}) = (x - f)^{2} + g^{2}, +\] +a quantity which is always positive whatever value be +given to~$x$. From this it follows that alterations in +the sign can be due only to real roots. But since the +theorem respecting the form of imaginary roots cannot +be rigorously demonstrated without employing the +other theorem that every equation of an odd degree +has necessarily one real root, a theorem of which the +general demonstration itself depends on the proposition +which we are concerned in proving, it follows +that that demonstration must be regarded as a sort of +vicious circle, and that it must be replaced by another +which is unassailable. + +But there is a more general and simpler method +\MNote{Application of geometry to algebra.} +\index{Algebra!application of geometry to|EtSeq}% +\index{Geometry!application of to algebra|EtSeq}% +of considering equations, which enjoys the advantage +\index{Equations!constructions for solving|EtSeq}% +of affording direct demonstration to the eye of the +principal properties of equations. It is founded upon +a species of application of geometry to algebra which +is the more deserving of exposition as it finds extended +employment in all branches of mathematics. + +Let us take up again the general equation proposed +above and let us represent by straight lines all +the successive values which are given to the unknown +quantity~$x$ and let us do the same for the corresponding +values which the left-hand side of the equation +assumes in this manner. To this end, instead of supposing +the right-hand side of the equation equal to +zero, we suppose it equal to an undetermined quantity~$y$. +We lay off the values of~$x$ upon an indefinite +\PageSep{101} +straight line~$AB$ (Fig.~1), starting from a fixed point~$O$ +at which $x$~is zero and taking the positive values of~$x$ +in the direction~$OB$ to the right of~$O$ and the negative +values of~$x$ in the opposite direction to the left of~$O$. +Then let~$OP$ be any value of~$x$. To represent +the corresponding value of~$y$ we erect at~$P$ a perpendicular +to the line~$OB$ and lay off on it the value of~$y$ +in the direction~$PQ$ above the straight line~$OB$ if it is +positive, and on the same perpendicular below~$OB$ if +it is negative. We do the same for all the values of~$x$, +\MNote{Representation of equations by curves.} +\index{Curves!representation of equations by|EtSeq}% +\Figure{1}{0.8\textwidth} +positive as well as negative; that is, we lay off +corresponding values of~$y$ upon perpendiculars to the +straight line through all the points whose distance +from the point~$O$ is equal to~$x$. The extremities of all +these perpendiculars will together form a straight line +or a curve, which will furnish, so to speak, a picture +of the equation +\[ +x^{m} + px^{m-1} + qx^{m-2} + \dots + u = y. +\] +The line~$AB$ is called the axis of the curve, $O$~the origin +of the abscissæ, $OP = x$ an abscissa, $PQ = y$ the corresponding +\PageSep{102} +ordinate, and the equations in $x$~and~$y$ the +\index{Equations!general remarks upon the roots of|EtSeq}% +equations of the curve. A curve such as that of Fig.~1 +having been described in the manner indicated, it is +clear that its intersections with the axis~$AB$ will give +the roots of the proposed equation +\MNote{Graphic resolution of equations.} +\index{Equations!graphic resolution of}% +\index{Intersections, with the axis give roots|EtSeq}% +\[ +x^{m} + px^{m-1} + qx^{m-2} + \dots + u = 0. +\] +For seeing that this equation is realised only when in +the equation of the curve $y$~becomes zero, therefore +those values of~$x$ which satisfy the equation in question +and which are its roots can only be the abscissæ +\ifthenelse{\not\boolean{ForPrinting}}{% +\Figure{1}{0.8\textwidth} %[** TN: [sic], figure repeated] +}{}% [Discard second copy if formatting for printing] +that correspond to the points at which the ordinates +are zero, that is, to the points at which the curve cuts +the axis~$AB$. Thus, supposing the curve of the equation +in $x$~and~$y$ is that represented in Fig.~1, the roots +of the proposed equation will be +\[ +OM,\quad ON,\quad OR,\dots \quad\text{and}\quad -OI,\quad -OG,\dots. +\] +I give the sign~$-$ to the latter because the intersections +$I$,~$G$,~$\dots$ fall on the other side of the point~$O$. +The consideration of the curve in question gives rise +to the following general remarks upon equations: +\PageSep{103} + +(1) Since the equation of the curve contains only +whole and positive powers of the unknown quantity~$x$ +it is clear that to every value of~$x$ there must correspond +\MNote{The consequences of the graphic resolution.} +a determinate value of~$y$, and that the value in +question will be unique and finite so long as $x$~is finite. +But since there is nothing to limit the values of~$x$ they +may be supposed infinitely great, positive as well as +negative, and to them will correspond also values of~$y$ +which are infinitely great. Whence it follows that +the curve will have a continuous and single course, +and that it may be extended to infinity on both sides +of the origin~$O$. + +(2) It also follows that the curve cannot pass from +one side of the axis to the other without cutting it, +and that it cannot return to the same side without +having cut it twice. Consequently, between any two +points of the curve on the same side of the axis there +will necessarily be either no intersections or an even +number of intersections; for example, between the +points $H$~and~$Q$ we find two intersections $I$~and~$M$, +and between the points $H$~and~$S$ we find four, $I$, $M$ +$N$, $R$, and so on. Contrariwise, between a point on +one side of the axis and a point on the other side, the +curve will have an odd number of intersections; for +example, between the points $L$~and~$Q$ there is one intersection~$M$, +and between the points $H$~and~$K$ there +are three intersections, $I$, $M$, $N$, and so on. + +For the same reason there can be no simple intersection +unless on both sides of the point of intersection, +\PageSep{104} +above and below the axis, points of the curve are +situated as are the points $L$,~$Q$ with respect to the intersection~$M$. +\MNote{Intersections indicate the roots.} +But two intersections, such as $N$~and~$R$, +may approach each other so as ultimately to coincide +at~$T$. Then the branch~$QKS$ will take the form +of the dotted line~$QTS$ and touch the axis at~$T$, and +will consequently lie in its whole extent above the +axis; this is the case in which the two roots $ON$,~$OR$ +are equal. If three intersections coincide at a point,---a +coincidence which occurs when there are three +equal roots,---then the curve will cut the axis in one +additional point only, as in the case of a single point +of intersection, and so on. + +Consequently, if we have found for~$y$ two values +having the same sign, we may be assured that between +the two corresponding values of~$x$ there can fall only +an even number of roots of the proposed equation; +that is, that there will be none or there will be two, or +there will be four, etc. On the other hand, if we have +found for~$y$ two values having contrary signs, we may +be assured that between the corresponding values of~$x$ +there will necessarily fall an odd number of roots of +the proposed equation; that is, there will be one, or +there will be three, or there will be five, etc.; so that, +in the case last mentioned, we may infer immediately +that there will be at least one root of the proposed +equation between the two values of~$x$. + +Conversely, every value of~$x$ which is a root of the +equation will be found between some larger and some +\PageSep{105} +smaller value of~$x$ which on being substituted for~$x$ in +the equation will yield values of~$y$ with contrary signs. + +This will not be the case, however, if the value of~$x$ +is a double root; that is, if the equation contains +\MNote{Case of multiple roots.} +\index{Multiple roots}% +\index{Roots!multiple}% +two roots of the same value. On the other hand, if +the value of~$x$ is a triple root, there will again exist +a larger and a smaller value for~$x$ which will give to +the corresponding values of~$y$ contrary signs, and so +on with the rest. + +If, now, we consider the equation of the curve, it +is plain in the first place, that by making $x = 0$ we +shall have $y = u$; and consequently that the sign of +the ordinate~$y$ will be the same as that of the quantity~$u$, +the last term of the proposed equation. It is also +easy to see that there can be given to~$x$ a positive or +negative value sufficiently great to make the first term~$x^{m}$ +of the equation exceed the sum of all the other +terms which have the opposite sign to~$x^{m}$; with the +result that the corresponding value of~$y$ will have the +same sign as the first term~$x^{m}$. Now, if $m$~is odd $x^{m}$~will +be positive or negative according as $x$~is positive +or negative, and if $m$~is even, $x^{m}$~will always be positive +whether $x$~be positive or not. + +Whence we may conclude: + +(1) That every equation of an odd degree of which +\index{Equations!odd@of an odd degree, roots of}% +the last term is negative has an odd number of roots +between $x = 0$ and some very large positive value of~$x$, +and an even number of roots between $x = 0$ and +some very large negative value of~$x$, and consequently +\PageSep{106} +that it has at least one real positive root. That, contrariwise, +if the last term of the equation is positive it +\MNote{General conclusions as to the character of the roots.} +will have an odd number of roots between $x = 0$ and +some very large negative value of~$x$, and an even +number of roots between $x = 0$ and some very large +positive value of~$x$, and consequently that it will have +at least one real negative root. + +(2) That every equation of an even degree, of +\index{Equations!even@of an even degree, roots of}% +which the last term is negative, has an odd number of +roots between $x = 0$ and some very large positive value +of~$x$, as well as an odd number of roots between $x = 0$ +and some very large negative value of~$x$, and consequently +that it has at least one real positive root and +one real negative root. That, on the other hand, if +the last term is positive there will be an even number +of roots between $x = 0$ and some very large positive +value of~$x$, and also an even number of roots between +$x = 0$ and some very large negative value of~$x$; with +the result that in this case the equation may have no +real root, whether positive or negative. + +We have said that there could always be given to~$x$ +a value sufficiently great to make the first term~$x^{m}$ of +the equation exceed the sum of all the terms of contrary +sign. Although this proposition is not in need +of demonstration, seeing that, since the power~$x^{m}$ is +higher than any of the other powers of~$x$ which enter +the equation, it is bound, as $x$~increases, to increase +much more rapidly than these other powers; nevertheless, +in order to leave no doubts in the mind, we +\PageSep{107} +shall offer a very simple demonstration of it,---a demonstration +which will enjoy the collateral advantage +of furnishing a limit beyond which we may be certain +no root of the equation can be found. + +To this end, let us first suppose that $x$~is positive, +\index{Limits of roots|(}% +and that $k$~is the greatest of the coefficients of the +\index{Coefficients!greatest negative|EtSeq}% +\MNote{Limits of the real roots of equations.} +\index{Equations!real roots of, limits of the|EtSeq}% +negative terms. If we make $x = k + 1$ we shall have +\[ +x^{m} = (k + 1)^{m} = k(k + 1)^{m-1} + (k + 1)^{m-1}. +\] +Similarly, +\begin{align*} +(k + 1)^{m-1} &= k(k + 1)^{m-2} + (k + 1)^{m-2}, \\ +(k + 1)^{m-2} &= k(k + 1)^{m-3} + (k + 1)^{m-3} +\end{align*} +and so on; so that we shall finally have +\[ +(k + 1)^{m} + = k(k + 1)^{m-1} + + k(k + 1)^{m-2} + + k(k + 1)^{m-3} + \dots + k + 1. +\] +Now this quantity is evidently greater than the sum +of all the negative terms of the equation taken positively, +on the supposition that $x = k + 1$. Therefore, +the supposition $x = k + 1$ necessarily renders the first +term~$x^{m}$ greater than the sum of all the negative terms. +Consequently, the value of~$y$ will have the same sign +as~$x$. + +The same reasoning and the same result hold good +when $x$~is negative. We have here merely to change~$x$ +into~$-x$ in the proposed equation, in order to change +the positive roots into negative roots, and \textit{vice versa}. + +In the same way it may be proved that if any value +be given to~$x$ greater than~$k + 1$, the value of~$y$ will +still have the same sign. From this and from what +has been developed above, it follows immediately that +\PageSep{108} +the equation can have no root equal to or greater than~$k + 1$. + +Therefore, in general, if $k$~is the greatest of the +\MNote{Limits of the positive and negative roots.} +coefficients of the negative terms of an equation, and +changing the unknown quantity~$x$ into~$-x$, $h$~is +the greatest of the coefficients of the negative terms +of the new equation,---the first term always being supposed +positive,---then all the real roots of the equation +will necessarily be comprised between the limits +\[ +k + 1 \quad\text{and}\quad -h - 1. +\] + +But if there are several positive terms in the equation +preceding the first negative term, we may take +for~$k$ a quantity less than the greatest negative coefficient. +In fact it is easy to see that the formula given +above can be put into the form +\[ +(k + 1)^{m} + = k(k + 1)(k + 1)^{m-2} + + k(k + 1)(k + 1)^{m-3} + \dots + (k + 1)^{2} +\] +and similarly into the following +\[ +(k + 1)^{m} + = k(k + 1)^{2}(k + 1)^{m-3} + + k(k + 1)^{2}(k + 1)^{m-4} + \dots + (k + 1)^{3} +\] +and so on. + +Whence it is easy to infer that if $m - n$ is the exponent +of the first negative term of the proposed equation +of the $m$th~degree, and if $l$~is the largest coefficient +of the negative terms, it will be sufficient if $k$~is +so determined that +\[ +k(k + 1)^{n-1} = l. +\] +And since we may take for~$k$ any larger value that we +please, it will be sufficient to take +\PageSep{109} +\[ +k^{n} = l,\quad\text{or}\quad k = \sqrt[n]{l}. +\] +And the same will hold good for the quantity~$h$ as the +limit of the negative roots. +\index{Positive roots, superior and inferior limits of the}% +\index{Roots!superior and inferior limits of the positive}% + +If, now, the unknown quantity~$x$ be changed into~$\dfrac{1}{z}$, +the largest roots of the equation in~$x$ will be converted +\MNote{Superior and inferior limits of the positive roots.} +into the smallest in the new equation in~$z$, and +conversely. Having effected this transformation, and +having so arranged the terms according to the powers +of~$z$ that the first term of the equation is~$z^{m}$, we may +then in the same manner seek for the limits $K + 1$ and +$-H - 1$ of the positive and negative roots of the +equation in~$z$. + +Thus $K + 1$ being larger than the largest value of~$z$ +or of~$\dfrac{1}{x}$, therefore, by the nature of fractions, $\dfrac{1}{K + 1}$ +will be smaller than the smallest value of~$x$ and similarly +$\dfrac{1}{H + 1}$ will be smaller than the smallest negative +value of~$x$. + +Whence it may be inferred that all the positive +real roots will necessarily be comprised between the +limits +\[ +\frac{1}{K + 1} \quad\text{and}\quad k + 1, +\] +and that the negative real roots will fall between the +limits +\[ +-\frac{1}{H + 1} \quad\text{and}\quad -h - 1. +\] + +There are methods for finding still closer limits; +but since they require considerable labor, the preceding +\PageSep{110} +method is, in the majority of cases, preferable, as +being more simple and convenient. + +For example, if in the proposed equation $l + z$ be +\MNote{A further method for finding the limits.} +\index{Roots!method for finding the limits of}% +substituted for~$x$, and if after having arranged the +terms according to the powers of~$z$, there be given to~$l$ +a value such that the coefficients of all the terms +become positive, it is plain that there will then be no +positive value of~$z$ that can satisfy the equation. The +equation will have negative roots only, and consequently +$l$~will be a quantity greater than the greatest +value of~$x$. Now it is easy to see that these coefficients +will be expressed as follows: +\begin{gather*} +%[** TN: Re-broken] +p + ml, \\ +q + (m - 1)pl + \frac{m(m - 1)}{2}\, l^{2}, \\ +r + (m - 2)ql + \frac{(m - 1)(m - 2)}{2}\, pl^{2} + + \frac{m(m - 1)(m - 2)}{2·3}\, l^{3}, +\end{gather*} +and so on. Accordingly, it is only necessary to seek +by trial the smallest value of~$l$ which will render them +all positive. + +But in the majority of cases it is not sufficient to +\index{Problems}% +know the limits of the roots of an equation; the thing +necessary is to know the values of those roots, at +least as approximately as the conditions of the problem +require. For every problem leads in its last analysis +to an equation which contains its solution; and +if it is not in our power to resolve this equation, all +\PageSep{111} +the pains expended upon its formulation are a sheer +loss. We may regard this point, therefore, as the +most important in all analysis, and for this reason I +\MNote{The real problem, the finding of the roots.} +have felt constrained to make it the principal subject +of the present lecture. + +From the principles established above regarding +\index{Substitutions|EtSeq}% +the nature of the curve of which the ordinates~$y$ represent +all the values which the left-hand side of an +equation assumes, it follows that if we possessed +some means of describing this curve we should obtain +at once, by its intersections with the axis, all the roots +of the proposed equation. But for this purpose it is +not necessary to have all of the curve; it is sufficient +to know the parts which lie immediately above and +below each point of intersection. Now it is possible +to find as many points of a curve as we please, and as +near to one another as we please by successively substituting +for~$x$ numbers which are very little different +from one another, but which are still near enough for +our purpose, and by taking for~$y$ the results of these +substitutions in the left-hand side of the equation. If +among the results of these substitutions two be found +having contrary signs, we may be certain, by the principles +established above, that there will be between +these two values of~$x$ at least one real root. We can +then by new substitutions bring these two limits still +closer together and approach as nearly as we wish to +the roots sought. + +Calling the smaller of the two values of~$x$ which +\PageSep{112} +have given results with contrary signs,~$A$, and the +larger~$B$, and supposing that we wish to find the +\MNote{Separation of the roots.} +\index{Roots!separation of the}% +\index{Roots!arithmetical@the arithmetical progression revealing the|EtSeq}% +value of the root within a degree of exactness denoted +by~$n$, where $n$~is a fraction of any degree of smallness +we please, we proceed to substitute successively for~$x$ +the following numbers in arithmetical progression: +\index{Arithmetical progression revealing the roots|EtSeq}% +\[ +A + n,\quad A + 2n,\quad A + 3n, \dots, +\] +or +\[ +B - n,\quad B - 2n,\quad B - 3n, \dots, +\] +until a result is reached having the contrary sign to +that obtained by the substitution of~$A$ or of~$B$. Then +one of the two successive values of~$x$ which have given +results with contrary signs will necessarily be larger +than the root sought, and the other smaller; and since +by hypothesis these values differ from one another +only by the quantity~$n$, it follows that each of them +approaches to within less than~$n$ of the root sought, +and that the error is therefore less than~$n$. + +But how are the initial values substituted for~$x$ to +be determined, so as on the one hand to avoid as +many useless trials as possible, and on the other to +make us confident that we have discovered by this +method all the real roots of this equation. If we examine +the curve of the equation it will be readily seen +that the question resolves itself into so selecting the +values of~$x$ that at least one of them shall fall between +two adjacent intersections, which will be necessarily +the case if the difference between two consecutive values +\PageSep{113} +is less than the smallest distance between two +adjacent intersections. + +Thus, supposing that $D$~is a quantity smaller than +the smallest distance between two intersections immediately +\MNote{To find a quantity less than the difference between any two roots.} +\index{Roots!quantity less than the difference between any two}% +following each other, we form the arithmetical +progression +\[ +0,\quad D,\quad 2D,\quad 3D,\quad 4D,\dots, +\] +and we select from this progression only the terms +which fall between the limits +\[ +\frac{1}{K + 1} \quad\text{and}\quad k + 1, +\] +as determined by the method already given. We obtain, +in this manner, values which on being substituted +for~$x$ ultimately give us all the positive roots of +the equation, and at the same time give the initial +limits of each root. In the same manner, for obtaining +the negative roots we form the progression +\[ +0,\quad -D,\quad -2D,\quad -3D,\quad -4D,\dots, +\] +from which we also take only the terms comprised +between the limits +\[ +-\frac{1}{H + 1} \quad\text{and}\quad -h - 1. +\] + +Thus this difficulty is resolved. But it still remains +to find the quantity~$D$,---that is, a quantity +smaller than the smallest interval between any two adjacent +intersections of the curve with the axis. Since +the abscissæ which correspond to the intersections are +\index{Intersections, with the axis give roots}% +the roots of the proposed equation, it is clear that the +question reduces itself to finding a quantity smaller +\PageSep{114} +than the smallest difference between two roots, neglecting +the signs. We have, therefore, to seek, by the +methods which were discussed in the lectures of the +principal course, the equation whose roots are the differences +between the roots of the proposed equation. +And we must then seek, by the methods expounded +above, a quantity smaller than the smallest root of +this last equation, and take that quantity for the value +of~$D$. + +This method, as we see, leaves nothing to be desired +\MNote{The equation of differences.} +\index{Differences, the equation of|EtSeq}% +as regards the rigorous solution of the problem, +but it labors under great disadvantage in requiring +extremely long calculations, especially if the proposed +equation is at all high in degree. For example, if $m$~is +the degree of the original equation, that of the equation +of differences will be~$m(m - 1)$, because each root +can be subtracted from all the remaining roots, the +number of which is~$m - 1$,---which gives $m(m - 1)$ +differences. But since each difference can be positive +or negative, it follows that the equation of differences +must have the same roots both in a positive and in a +negative form; that consequently the equation must +be wanting in all terms in which the unknown quantity +is raised to an odd power; so that by taking the +square of the differences as the unknown quantity, this +unknown quantity can occur only in the $\dfrac{m(m - 1)}{2}$th +degree. For an equation of the $m$th~degree, accordingly, +there is requisite at the start a transformed +\PageSep{115} +equation of the $\dfrac{m(m - 1)}{2}$th degree, which necessitates +an enormous amount of tedious labor, if $m$~is at all +large. For example, for an equation of the $10$th~degree, +\MNote{Impracticability of the method.} +the transformed equation would be of the~$45$th. +And since in the majority of cases this disadvantage +renders the method almost impracticable, it is of great +importance to find a means of remedying it. + +To this end let us resume the proposed equation of +the $m$th~degree, +\[ +x^{m} + px^{m-1} + qx^{m-2} + \dots + u = 0, +\] +of which the roots are $a$,~$b$,~$c$,~$\dots$. We shall have +then +\[ +a^{m} + pa^{m-1} + qa^{m-2} + \dots + u = 0 +\] +and also +\[ +b^{m} + pb^{m-1} + qb^{m-2} + \dots + u = 0. +\] +Let $b - a = i$. Substitute this value of~$b$ in the second +equation, and after developing the different powers of~$a + i$ +according to the well known binomial theorem, +\index{Binomial theorem}% +arrange the resulting equation according to the powers +of~$i$, beginning with the lowest. We shall have the +transformed equation +\[ +P + Qi + Ri^{2} + \dots + i^{m} = 0, +\] +in which the coefficients $P$,~$Q$,~$R$,~$\dots$ have the following +values +\begin{align*} +P &= a^{m} + pa^{m-1} + qa^{m-2} + \dots + u, \displaybreak[1] \\ +Q &= ma^{m-1} + (m - 1)pa^{m-2} + (m - 2)qa^{m-3} + \dots\Add{,} \displaybreak[1] \\ +\PageSep{116} +R &= \begin{aligned}[t] + \frac{m(m - 1)}{2}\, a^{m-2} + &+ \frac{(m - 1)(m - 2)}{2}\, pa^{m-3} \\ + &+ \frac{(m - 2)(m - 3)}{2}\, qa^{m-4} + \dots\Add{,} +\end{aligned} +\end{align*} +\MNote{Attempt to remedy the method.} +and so on. The law of formation of these expressions +is evident. + +Now, by the first equation in~$a$ we have~$P = 0$. +Rejecting, therefore, the term~$P$ of the equation in~$i$ +and dividing all the remaining terms by~$i$, the equation +in question will be reduced to the $(m - 1)$th~degree, +and will have the form +\[ +Q + Ri + Si^{2} + \dots + i^{m-1} = 0. +\] + +This equation will have for its roots the $m - 1$~differences +between the root~$a$ and the remaining roots +$b$,~$c$,~$\dots$\Add{.} Similarly, if $b$~be substituted for~$a$ in the expressions +for the coefficients $Q$,~$R$,~$\dots$, we shall obtain +an equation of which the roots are the difference +between the root~$b$ and the remaining roots $a$,~$c$,~$\dots$, +and so on. + +Accordingly, if a quantity can be found smaller +\index{Roots!smallest|EtSeq}% +than the smallest root of all these equations, it will +possess the property required and may be taken for +the quantity~$D$, the value of which we are seeking. + +If, by means of the equation $P = 0$, $a$~be eliminated +from the equation in~$i$, we shall get a new equation in~$i$ +which will contain all the other equations of which +we have just spoken, and of which it would only be +necessary to seek the smallest root. But this new +\PageSep{117} +equation in~$i$ is nothing else than the equation of differences +which we sought to dispense with. + +\MNote{Further improvement.} +In the above equation in~$i$ let us put it $i = \dfrac{1}{z}$. We +shall have then the transformed equation in~$z$, +\[ +z^{m-1} + + \frac{R}{Q}\, z^{m-2} + + \frac{S}{Q}\, z^{m-3} + \dots + \frac{1}{Q} = 0, +\] +and the greatest negative coefficient of this equation +will, from what has been demonstrated above, give a +value greater than its greatest root; so that calling~$L$ +this greatest coefficient, $L + 1$~will be a quantity +greater than the greatest value of~$z$. Consequently, +$\dfrac{1}{L + 1}$ will be a quantity smaller than the smallest +positive value of~$i$; and in like manner we shall find +a quantity smaller than the smallest negative value +of~$i$. Accordingly, we may take for~$D$ the smallest of +these two quantities, or some quantity smaller than +either of them. + +For a simpler result, and one which is independent +of signs, we may reduce the question to finding a +quantity~$L$ numerically greater than any of the coefficients +\index{Coefficients!greatest negative}% +of the equation in~$z$, and it is clear that if we +find a quantity~$N$ numerically smaller than the smallest +value of~$Q$ and a quantity~$M$ numerically greater +than the greatest value of any of the quantities $R$, +$S$,~$\dots$, we may put $L = \dfrac{M}{N}$. + +Let us begin with finding the values of~$M$. It is +not difficult to demonstrate, by the principles established +above, that if $k + 1$~is the limit of the positive +\PageSep{118} +roots and $-h - 1$~the limit of the negative roots of +the proposed equation, and if for~$a$, $k + 1$~and~$-h - 1$ +\MNote{Final resolution.} +be successively substituted in the expressions for $R$, +$S$,~$\dots$, considering only the terms which have the +same sign as the first,---it is easy to demonstrate that +we shall obtain in this manner quantities which are +greater than the greatest positive and negative values +of $R$, $S$,~$\dots$ corresponding to the roots $a$,~$b$, $c$\Add{,}~$\dots$ of +the proposed equation; so that we may take for~$M$ +the quantity which is numerically the greatest of +these. + +It accordingly only remains to find a value smaller +than the smallest value of~$Q$. Now it would seem +that we could arrive at this in no other way than by +employing the equation of which the different values +of~$Q$ are the roots,---an equation which can only be +reached by eliminating~$a$ from the following equations: +\begin{gather*} +a^{m} + pa^{m-1} + qa^{m-2} + \dots + u = 0, \\ +ma^{m-1} + (m - 1)pa^{m-2} + (m - 2)qa^{m-3} + \dots = Q. +\end{gather*} + +It can be easily demonstrated by the theory of +elimination that the resulting equation in~$Q$ will be of +the $m$th~degree, that is to say, of the same degree with +the proposed equation; and it can also be demonstrated +from the form of the roots of this equation +that its next to the last term will be missing. If, accordingly, +we seek by the method given above a quantity +numerically smaller than the smallest root of this +equation, the quantity found can be taken for~$N$. The +\PageSep{119} +problem is therefore resolved by means of an equation +of the same degree as the proposed equation. + +The upshot of the whole is \Typo{a}{as} follows,---where for +\MNote{Recapitulation.} +the sake of simplicity I retain the letter~$x$ instead of +the letter~$a$. + +Let the following be the proposed equation of the +$m$th~degree: +\[ +x^{m} + px^{m-1} + qx^{m-2} + rx^{m-3} + \dots = 0; +\] +let $k$~be the largest coefficient of the negative terms, +and $m - n$~the exponent of~$x$ in the first negative term. +Similarly, let $h$ be the greatest coefficient of the terms +having a contrary sign to the first term after $x$~has +been changed into~$-x$; and let $m - n'$ be the exponent +of~$x$ in the first term having a contrary sign to +the first term of the equation as thus altered. Putting, then, +\[ +f = \sqrt[n]{k} + 1 \quad\text{and}\quad g = \sqrt[n]{h} + 1, +\] +we shall have $f$~and~$-g$ for the limits of the positive +and negative roots. These limits are then substituted +\index{Roots!limits of the positive and negative}% +successively for~$x$ in the following formulæ, neglecting +the terms which have the same sign as the first +term: +\begin{gather*} +%[** TN: Re-broken] +\begin{aligned} +\frac{m(m - 1)}{2}\, x^{m-2} + &+ \frac{(m - 1)(m - 2)}{2}\, px^{m-3} \\ + &+ \frac{(m - 2)(m - 3)}{2}\, qx^{m-4} + \dots, +\end{aligned} \\ +\frac{m(m - 1)(m - 2)}{2·3}\, x^{m-3} + + \frac{(m - 1)(m - 2)(m - 3)}{2·3}\, px^{m-4} + \dots, +\end{gather*} +\PageSep{120} +and so on. Of these formulæ there will be~$m - 2$. Let +the greatest of the numerical quantities obtained in +this manner be called M. We then take the equation +\MNote{The arithmetical progression revealing the roots.} +\index{Arithmetical progression revealing the roots}% +\index{Roots!arithmetical@the arithmetical progression revealing the}% +\[ +mx^{m-1} + (m - 1)px^{m-2} + (m - 2)qx^{m-3} + (m - 3)rx^{m-4} + \dots = y +\] +and eliminate~$x$ from it by means of the proposed +equation,---which gives an equation in~$y$ of the $m$th~degree +with its next to the last term wanting. Let $V$~be +the last term of this equation in~$y$, and $T$~the largest +coefficient of the terms having the contrary sign +to~$V$, supposing $y$~positive as well as negative. Then +taking these two quantities $T$~and~$V$ positive, $N$~will +be determined by the equation +\[ +\frac{N}{1 - N} = \sqrt[n]{\frac{V}{T}} +\] +where $n$~is equal to the exponent of the last term having +the contrary sign to~$V$. We then take $D$ equal to +or smaller than the quantity~$\dfrac{N}{M + N}$, and interpolate +the arithmetical progression: +\[ +0,\quad D,\quad 2D,\quad 3D,\dots,\quad +-D,\quad -2D,\quad -3D, \dots +\] +between the limits $f$~and~$-g$. The terms of these +progressions being successively substituted for~$x$ in +the proposed equation will reveal all the real roots, +positive as well as negative, by the changes of sign +in the series of results produced by these substitutions, +and they will at the same time give the first +limits of these roots,---limits which can be narrowed +as much as we please, as we already know. +\index{Limits of roots|)}% +\PageSep{121} + +If the last term~$V$ of the equation in~$y$ resulting +from the elimination of~$x$ is zero, then $N$~will be zero, +and consequently $D$~will be equal to zero. But in +\MNote{Method of elimination\Add{.}} +\index{Elimination!method of}% +this case it is clear that the equation in~$y$ will have +one root equal to zero and even two, because its next +to the last term is wanting. Consequently the equation +\[ +mx^{m-1} + (m - 1)px^{m-2} + (m - 2)qx^{m-3} + \dots = 0\Typo{.}{} +\] +will hold good at the same time with the proposed +equation. These two equations will, accordingly, have +\index{Common divisor of two equations}% +\index{Equations!common divisor of two}% +a common divisor which can be found by the ordinary +method, and this divisor, put equal to zero, will give +one or several roots of the proposed equation, which +roots will be double or multiple, as is easily apparent +from the preceding theory; for if the last term~$Q$ of +the equation in~$i$ is zero, it follows that +\[ +i = 0 \quad\text{and}\quad a = b. +\] +The equation in~$y$ is reduced, by the vanishing of its +last term, to the $(m - 2)$th~degree,---being divisible +by~$y^{2}$. If after this division its last term should still +be zero, this would be an indication that it had more +than two roots equal to zero, and so on. In such a +contingency we should divide it by~$y$ as many times +as possible, and then take its last term for~$V$, and the +greatest coefficient of the terms of contrary sign to~$V$ +for~$T$, in order to obtain the value of~$D$, which will +enable us to find all the remaining roots of the proposed +equation. If the proposed equation is of the +third degree, as +\PageSep{122} +\[ +x^{3} + qx + r = 0, +\] +we shall get for the equation in~$y$, +\[ +y^{3} + 3qy^{2} - 4q^{3} - 27r^{2} = 0. +\] + +If the proposed equation is +\[ +x^{4} + qx^{2} + rx + s = 0 +\] +we shall obtain for the equation in~$y$ the following +\begin{multline*} +%[** TN: Re-broken] +y^{4} + 8ry^{3} + (4q^{3} - 16qs + 18r^{2})y^{2} \\ + + 256s^{3} - 128s^{2}q^{2} + 16sq^{4} + 144r^{2}sq - 4r^{2}q^{3} - 27r^{4} + = 0 +\end{multline*} +and so on. + +Since, however, the finding of the equation in~$y$ by +\MNote{General formulæ for elimination.} +\index{Elimination!general formulæ for}% +the ordinary methods of elimination may be fraught +with considerable difficulty, I here give the general +formulæ for the purpose, derived from the known +properties of equations. We form, first, from the coefficients +$p$,~$q$,~$r$ of the proposed equation, the quantities +$x_{1}$,~$x_{2}$,~$x_{3}$,~$\dots$, in the following manner: +\[ +\begin{array}{r@{\,}l} +x_{1} &= -p, \\ +x_{2} &= -px_{1} - 2q, \\ +x_{3} &= -px_{2} - qx_{1} - 3r, \\ +\hdotsfor{2}. +\end{array} +\] +We then substitute in the expressions for $y$,~$y^{2}$,~$y^{3}$,~$\dots$ +up to~$y^{m}$, after the terms in~$x$ have been developed +the quantities $x_{1}$~for~$x$, $x_{2}$~for~$x^{}$, $x_{3}$~for~$x^{3}$, and so forth, +and designate by $y_{1}$,~$y_{2}$, $y_{3}$,~$\dots$ the values of $y$,~$y^{2}$, $y^{3}$,~$\dots$ +resulting from these substitutions. We have then +simply to form the quantities $A$,~$B$,~$C$ from the formulæ +\PageSep{123} +\index{Differences, the equation of}% +\[ +\begin{array}{r@{\,}l} +A &= y_{1}, \\ +B &= \dfrac{Ay_{1} - y_{2}}{2}, \\ +C &= \dfrac{By_{1} - Ay_{2} + y_{3}}{3}, \\ +\hdotsfor{2}, +\end{array} +\] +and we shall have the following equation in~$y$: +\[ +y^{m} - Ay^{m-1} + By^{m-2} - Cy^{m-3} + \dots = 0. +\] + +The value, or rather the limit of~$D$, which we find +by the method just expounded may often be much +\MNote{General result.} +smaller than is necessary for finding all the roots, but +there would be no further inconvenience in this than +to increase the number of successive substitutions for~$x$ +\index{Substitutions}% +in the proposed equation. Furthermore, when there +are as many results found as there are units in the +highest exponent of the equation, we can continue +these results as far as we wish by the simple addition +of the first, second, third differences, etc., because +the differences of the order corresponding to the degree +of the equation are always constant. + +We have seen above how the curve of the proposed +equation can be constructed by successively giving +different values to the abscissæ~$x$ and taking for the +ordinates~$y$ the values resulting from these substitutions +in the left-hand side of the equation. But these +values for~$y$ can also be found by another very simple +construction, which deserves to be brought to your +notice. Let us represent the proposed equation by +\[ +a + bx + cx^{2} + dx^{3} + \dots = 0 +\] +\PageSep{124} +where the terms are taken in the inverse order. The +equation of the curve will then be +\[ +y = a + bx + cx^{2} + dx^{3} + \dots\Add{.} +\] +Drawing (Fig.~2) the straight line~$OX$, which we take +\MNote{A second construction for solving equations.} +\index{Equations!constructions for solving}% +\index{Machine for solving equations|(}% +as the axis of abscissæ with $O$~as origin, we lay off on +this line the segment~$OI$ equal to the unit in terms of +which we may suppose the quantities $a$,~$b$,~$c$\Add{,}~$\dots$, to +be expressed; and we erect at the points~$OI$ the perpendiculars +\Figure{2}{0.5\textwidth} +$OD$,~$IM$. We then lay off upon the line~$OD$ +the segments +\[ +OA = a,\quad AB = b,\quad BC = c,\quad CD = d, \dots, +\] +and so on. Let $OP = x$, and at the point~$P$ let the +perpendicular~$PT$\Typo{}{ }be erected. Suppose, for example, +that $d$~is the last of the coefficients $a$,~$b$,~$c$,~$\dots$, so that +the proposed equation is only of the third degree, and +that the problem is to find the value of +\[ +y = a + bx + cx^{2} + dx^{3}. +\] +The point~$D$ being the last of the points determined +upon the perpendicular~$OD$, and the point~$C$ the next +\PageSep{125} +to the last, we draw through~$D$ the line~$DM$ parallel +to the axis~$OI$, and through the point~$M$ where this +line cuts the perpendicular~$IM$ we draw the straight +\MNote{The development and solution.} +line~$CM$ connecting $M$ with~$C$. Then through the +point~$S$ where this last straight line cuts the perpendicular~$PT$, +we draw $HSL$ parallel to~$OI$, and through +the point~$L$ where this parallel cuts the perpendicular~$IM$ +we draw to the point~$B$ the straight line~$BL$. +Similarly, through the point~$R$, where this last line +cuts the perpendicular~$PT$, we draw $GRK$ parallel to~$OI$, +and through the point~$K$, where this parallel cuts +the perpendicular~$IM$ we draw to the first division +point~$A$ of the perpendicular~$DO$ the straight line~$AK$. +The point~$Q$ where this straight line cuts the perpendicular~$PT$ +will give the segment $PQ = y$. + +Through $Q$ draw the line $FQ$ parallel to the axis~$OP$. +The two similar triangles $CDM$~and~$CHS$ give +\[ +DM(1) : DC(d) = HS(x) : CH(= dx). +\] +Adding $CB(c)$ we have +\[ +BH = c + dx. +\] +Also the two similar triangles $BHL$~and~$BGR$ give +\[ +HL(1) : HB(c + dx)= GR(x) : BG(= cx + dx^{2}). +\] +Adding $AB(b)$ we have +\[ +AG = b + cx + dx^{2}. +\] +Finally the similar triangles $AGK$~and~$AFQ$ give +\[ +%[** TN: Set on two lines in original] +GK(1) : GA(b + cx + dx^{2}) = FQ(x) : FA(= bx + cx^{2} + dx^{3}), +\] +and we obtain by adding $OA(a)$ +\[ +OF = PQ = a + bx + cx^{2} + dx^{3} = y. +\] +\PageSep{126} + +The same construction and the same demonstration +hold, whatever be the number of terms in the +proposed equation. When negative coefficients occur +among $a$,~$b$, $c$,~$\dots$, it is simply necessary to take +them in the opposite direction to that of the positive +coefficients. For example, if $a$~were negative we +should have to lay off the segment~$OA$ below the axis~$OI$. +Then we should start from the point~$A$ and add +to it the segment $AB = b$. If $b$~were positive, $AB$~would +be taken in the direction of~$OD$; but if $b$~were +negative, $AB$~would be taken in the opposite direction, +and so on with the rest. + +With regard to~$x$, $OP$~is taken in the direction of~$OI$, +which is supposed to be equal to positive unity, +when $x$~is positive; but in the opposite direction when +$x$~is negative. + +It would not be difficult to construct, on the foregoing +\MNote{A machine for solving equations.} +\index{Equations!machine@a machine for solving}% +model, an instrument which would be applicable +to all values of the coefficients $a$,~$b$, $c$,~$\dots$, and which +by means of a number of movable and properly jointed +rulers would give for every point~$P$ of the straight +line~$OP$ the corresponding point~$Q$, and which could +be even made by a continuous movement to describe +the curve. Such an instrument might be used for +solving equations of all degrees; at least it could be +used for finding the first approximate values of the +roots, by means of which afterwards more exact values +could be reached. +\index{Machine for solving equations|)}% +\index{Numerical equations!resolution of|)}% +\PageSep{127} + + +\Lecture[The Employment of Curves.] +{V.}{On the Employment of Curves in the Solution +of Problems.} +\index{Curves!employment of in the solution of problems|(}% +\index{Problems!employment of curves in the solution of|(}% + +\First{As long} as algebra and geometry travelled separate +\index{Algebra!application of geometry to|EtSeq}% +\index{Geometry!application of to algebra|EtSeq}% +paths their advance was slow and their +\MNote{Geometry applied to algebra.} +applications limited. But when these two sciences +joined company, they drew from each other fresh vitality +and thenceforward marched on at a rapid pace +towards perfection. It is to Descartes that we owe +\index{Descartes}% +the application of algebra to geometry,---an application +which has furnished the key to the greatest discoveries +in all branches of mathematics. The method +which I last expounded to you for finding and demonstrating +divers general properties of equations by considering +the curves which represent them, is, properly +speaking, a species of application of geometry to algebra, +and since this method has extended \Typo{applicacations}{applications}, +and is capable of readily solving problems +whose direct solution would be extremely difficult or +even impossible, I deem it proper to engage your attention +in this lecture with a further view of this subject,---especially +\PageSep{128} +since it is not ordinarily found in +elementary works on algebra. + +You have seen how an equation of any degree +\MNote{Method of resolution by curves.} +whatsoever can be resolved by means of a curve, of +which the abscissæ represent the unknown quantity +of the equation, and the ordinates the values which +the left-hand member assumes for every value of the +unknown quantity. It is clear that this method can be +applied generally to all equations, whatever their form, +and that it only requires them to be developed and +arranged according to the different powers of the unknown +quantity. It is simply necessary to bring all +the terms of the equation to one side, so that the other +side shall be equal to zero. Then taking the unknown +quantity for the abscissa~$x$, and the function of the +unknown quantity, or the quantity compounded of +that quantity and the known quantities, which forms +one side of the equation, for the ordinate~$y$, the curve +described by these co-ordinates $x$~and~$y$ will give by +its intersections with the axis those values of~$x$ which +are the required roots of the equation. And since +most frequently it is not necessary to know all possible +values of the unknown quantity but only such as +solve the problem in hand, it will be sufficient to describe +that portion of the curve which corresponds to +these roots, thus saving much unnecessary calculation. +We can even determine in this manner, from the shape +of the curve itself, whether the problem has possible +solutions satisfying the proposed conditions. +\PageSep{129} + +Suppose, for instance, that it is required to find on +\index{Light, law of the intensity of}% +\index{Lights, problem of the two|EtSeq}% +the line joining two luminous points of given intensity, +the point which receives a given quantity of light,---the +\MNote{Problem of the two lights.} +law of physics being that the intensity of light decreases +with the square of the distance. + +Let $a$~be the distance between the two lights and +$x$~the distance between the point sought and one of +the lights, the intensity' of which at unit distance is~$M$, +the intensity of the other at that distance being~$N$. +The expressions $\dfrac{M}{x^{2}}$ and $\dfrac{N}{(a - x)^{2}}$, accordingly, +give the intensity of the two lights at the point in +question, so that, designating the total given effect by~$A$, +we have the equation +\[ +\frac{M}{x^{2}} + \frac{N}{(a - x)^{2}} = A\Add{,} +\] +or +\[ +\frac{M}{x^{2}} + \frac{N}{(a - x)^{2}} - A = 0. +\] + +We will now consider the curve having the equation +\[ +\frac{M}{x^{2}} + \frac{N}{(a - x)^{2}} - A = y +\] +in which it will be seen at once that by giving to~$x$ a +very small value, positive or negative, the term~$\dfrac{M}{x^{2}}$, +while continuing positive, will grow very large, because +a fraction increases in proportion as its denominator +decreases, and it will be infinite when $x = 0$. +Further, if $x$~be made to increase, the expression~$\dfrac{M}{x^{2}}$ +will constantly diminish; but the other expression~$\dfrac{N}{(a - x)^{2}}$, +\PageSep{130} +which was $\dfrac{N}{a^{2}}$ when $x = 0$, will constantly increase +until it becomes very large or infinite when $x$ +has a value very near to or equal to~$a$. + +Accordingly, if, by giving to~$x$ values from zero to~$a$, +\MNote{Various solutions.} +the sum of these two expressions can be made to +become less than the given quantity~$A$, then the value +of~$y$, which at first was very large and positive, will +become negative, and afterwards again become very +large and positive. Consequently, the curve will cut +the axis twice between the two lights, and the problem +will have two solutions. These two solutions will +be reduced to a single solution if the smallest value of +\[ +\frac{M}{x^{2}} + \frac{N}{(a - x)^{2}} +\] +is exactly equal to~$A$, and they will become imaginary +if that value is greater than~$A$, because then the value +of~$y$ will always be positive from $x = 0$ to $x = a$. +Whence it is plain that if one of the conditions of the +problem be that the required point shall fall between +the two lights it is possible that the problem has no +solution. But if the point be allowed to fall on the +prolongation of the line joining the two lights, we +shall see that the problem is always resolvable in two +ways. In fact, supposing $x$~negative, it is plain that +the term~$\dfrac{M}{x^{2}}$ will always remain positive and from being +very large when $x$~is near to zero, it will commence +and keep decreasing as $x$~increases until it grows very +small or becomes zero when $x$~is very great or infinite. +\PageSep{131} +The other term~$\dfrac{N}{(a - x)^{2}}$, which at first was equal to~$\dfrac{N}{a^{2}}$, +also goes on diminishing until it becomes zero +when $x$~is negative infinity. It will be the same if $x$~is +positive and greater than~$a$; for when $x = a$, the +expression $\dfrac{N}{(a - x)^{2}}$ will be infinitely great; afterwards +it will keep on decreasing until it becomes zero when $x$~is +infinite, while the other expression $\dfrac{M}{x^{2}}$ will first be +equal to $\dfrac{M}{a^{2}}$ and will also go on diminishing towards +zero as $x$~increases. + +Hence, whatever be the value of the quantity~$A$, +it is plain that the values of~$y$ will necessarily pass +\MNote{General solution.} +from positive to negative, both for $x$~negative and for +$x$~positive and greater than~$a$. Accordingly, there +will be a negative value of~$x$ and a positive value of~$x$ +greater than~$a$ which will resolve the problem in all +cases. These values may be found by the general +method by successively causing the values of~$x$ which +give values of~$y$ with contrary signs, to approach +nearer and nearer to each other. + +With regard to the values of~$x$ which are less than~$a$ +we have seen that the reality of these values depends +on the smallest value of the quantity +\[ +\frac{M}{x^{2}} + \frac{N}{(a - x)^{2}}. +\] +Directions for finding the smallest and greatest values +of variable quantities are given in the Differential Calculus. +\index{Differential Calculus}% +We shall here content ourselves with remarking +\PageSep{132} +that the quantity in question will be a minimum +when +\MNote{Minimal values.} +\index{Minimal values}% +\index{Values!minimal}% +\[ +\frac{x}{a - x} = \sqrt[3]{\frac{M}{N}}; +\] +so that we shall have +\[ +x = \frac{a\sqrt[3]{M}}{\sqrt[3]{M} + \sqrt[3]{N}}, +\] +from which we get, as the smallest value of the expression +\[ +\frac{M}{x^{2}} + \frac{N}{(a - x)^{2}}, +\] +the quantity +\[ +\frac{(\sqrt[3]{M} + \sqrt[3]{N})^{3}}{a^{2}}. +\] +Hence there will be two real values for~$x$ if this quantity +is less than~$A$; but these values will be imaginary +if it is greater. The case of equality will give two +equal values for~$x$. + +I have dwelt at considerable length on the analysis +of this problem, (though in itself it is of slight importance,) +for the reason that it can be made to serve +as a type for all analogous cases. + +The equation of the foregoing problem, having +been freed from fractions, will assume the following +form: +\[ +Ax^{2}(a - x)^{2} - M(a - x)^{2} - Nx^{2} = 0. +\] +With its terms developed and properly arranged it +will be found to be of the fourth degree, and will consequently +have four roots. Now by the analysis which +we have just given, we can recognise at once the character +\PageSep{133} +of these roots. And since a method may spring +from this consideration applicable to all equations of +\index{Equations!fourth@of the fourth degree}% +\index{Fourth degree, equations of the}% +the fourth degree, we shall make a few brief remarks +\MNote{Preceding analysis applied to bi-quadratic equations.} +\index{Biquadratic equations}% +upon it in passing. Let the general equation be +\[ +x^{4} + px^{2} + qx + r = 0. +\] +We have already seen that if the last term of this +equation be negative it will necessarily have two real +roots, one positive and one negative; but that if the +last term be positive we can in general infer nothing +as to the character of its roots. If we give to this +equation the following form +\[ +(x^{2} - a^{2})^{2} + b(x + a)^{2} + c(x - a)^{2} = 0, +\] +a form which developed becomes +\[ +x^{4} + (b + c - 2a^{2})x^{2} + 2a(b - c)x + a^{4} + a^{2}(b + c) = 0, +\] +and from this by comparison derive the following +equations of condition +\[ +b + c - 2a^{2} = p,\quad 2a(b - c) = q,\quad a^{4} + a^{2}(b + c) = r, +\] +and from these, again, the following, +\[ +b + c = p + 2a^{2},\quad b - c = \frac{q}{2a},\quad 3a^{4} + pa^{2} = r, +\] +we shall obtain, by resolving the last equation, +\[ +a^{2} = -\frac{p}{6} + \sqrt{\frac{r}{3} + \frac{p^{2}}{36}}. +\] +If $r$~be supposed positive, $a^{2}$~will be positive and real, +and consequently $a$~will be real, and therefore, also, +$b$~and~$c$ will be real. + +Having determined in this manner the three quantities +$a$,~$b$,~$c$, we obtain the transformed equation +\[ +(x^{2} - a^{2})^{2} + b(x + a)^{2} + c(x - a)^{2} = 0. +\] +\PageSep{134} + +Putting the right-hand side of this equation equal +to~$y$, and considering the curve having for abscissæ +\MNote{Consideration of equations of the fourth degree.} +the different values of~$y$, it is plain, that when $b$~and~$c$ +are positive quantities this curve will lie wholly +above the axis and that consequently the equation +will have no real root. Secondly, suppose that $b$~is a +negative quantity and $c$~a positive quantity; then $x = a$ +will give $y = 4ba^{2}$,---a negative quantity. A very +large positive or negative~$x$ will then give a very large +positive~$y$,---whence it is easy to conclude that the +equation will have two real roots, one larger than~$a$ +and one less than~$a$. We shall likewise find that if +$b$~is positive and $c$~is negative, the equation will have +two real roots, one greater and one less than~$-a$. +Finally, if $b$~and~$c$ are both negative, then $y$~will become +negative by making +\[ +x = a \quad\text{and}\quad x = -a +\] +and it will be positive and very large for a very large +positive or negative value of~$x$,---whence it follows +that the equation will have two real roots, one greater +than~$a$ and one less than~$-a$. The preceding considerations +might be greatly extended, but at present we +must forego their pursuit. + +It will be seen from the preceding example that +the consideration of the curve does not require the +equation to be freed from fractional expressions. The +\index{Fractional expressions in equations}% +\index{Radical expressions in equations}% +same may be said of radical expressions. There is +an advantage even in retaining these expressions in +\PageSep{135} +the form given by the analysis of the problem; the +advantage being that we may in this way restrict our +attention to those signs of the radicals which answer +\MNote{Advantages of the method of curves.} +\index{Curves!advantages of the method of}% +to the special exigencies of each problem, instead of +causing the fractions and the radicals to disappear +and obtaining an equation arranged according to the +different whole powers of the unknown quantity in +which frequently roots are introduced which are entirely +foreign to the question proposed. It is true that +these roots are always part of the question viewed in +its entire extent; but this wealth of algebraical analysis, +although in itself and from a general point of view +extremely valuable, may be inconvenient and burdensome +in particular cases where the solution of which +we are in need cannot by direct methods be found independently +of all other possible solutions. When +the equation which immediately flows from the conditions +of the problem contains radicals which are essentially +ambiguous in sign, the curve of that equation +(constructed by making the side which is equal to +zero, equal to the ordinate~$y$) will necessarily have as +many branches as there are possible different combinations +of these signs, and for the complete solution it +would be necessary to consider each of these branches. +But this generality may be restricted by the particular +conditions of the problem which determine the branch +on which the solution is to be sought; the result being +that we are spared much needless calculation,---an +advantage which is not the least of those offered by +\PageSep{136} +the method of solving equations from the consideration +of curves. + +But this method can be still further generalised +\MNote{The curve of errors.} +\index{Errors, curve of|EtSeq}% +and even rendered independent of the equation of the +problem. It is sufficient in applying it to consider +the conditions of the problem in and for themselves, +to give to the unknown quantity different arbitrary +values, and to determine by calculation or construction +the errors which result from such suppositions +according to the original conditions. Taking these +errors as the ordinates~$y$ of a curve having for abscissæ +the corresponding values of the unknown quantity, +we obtain a continuous curve called \emph{the curve of errors}, +which by its intersections with the axis also gives all +solutions of the problem. Thus, if two successive errors +be found, one of which is an excess, and another +a defect, that is, one positive and one negative, we +may conclude at once that between these two corresponding +values of the unknown quantity there will +be one for which the error is zero, and to which we +can approach as near as we please by successive substitutions, +or by the mechanical description of the +curve. + +This mode of resolving questions by curves of errors +\index{Astronomy, mechanics, and physics, curves of errors in}% +\index{Mechanics, astronomy, and physics, curves of errors in}% +\index{Physics, astronomy, and mechanics, curves of errors in}% +is one of the most useful that have been devised. +It is constantly employed in astronomy when direct +solutions are difficult or impossible. It can be employed +for resolving important problems of geometry +and mechanics and even of physics. It is properly +\PageSep{137} +speaking the \textit{regula falsi}, taken in its most general +\index{False, rule of}% +\index{Regula@\textit{Regula falsi}}% +\index{Rule!false@of false}% +sense and rendered applicable to all questions where +there is an unknown quantity to be determined. It +\MNote{Solution of a problem by the curve of errors.} +can also be applied to problems that depend on two +or several unknown quantities by successively giving +to these unknown quantities different arbitrary values +and calculating the errors which result therefrom, afterwards +linking them together by different curves, or +reducing them to tables; the result being that we may +\index{Tables}% +by this method obtain directly the solution sought +\Figure{3}{0.4\textwidth} +without preliminary elimination of the unknown quantities. + +We shall illustrate its use by a few examples. + +\textit{Required a circle in which a polygon of given sides can +be inscribed.} + +This problem gives an equation which is proportionate +in degree to the number of sides of the polygon. +To solve it by the method just expounded we +describe any circle~$ABCD$ (Fig.~3) and lay off in this +circle the given sides $AB$,~$BC$, $CD$, $DE$,~$EF$ of the +\PageSep{138} +polygon, which for the sake of simplicity I here suppose +to be pentagonal. If the extremity of the last +\MNote{Problem of the circle and inscribed polygon.} +\index{Circle!and inscribed polygon, problem of the}% +\index{Polygon, problem of the circle and inscribed}% +side falls on~$A$, the problem is solved. But since it +is very improbable that this should happen at the first +trial we lay off on the straight line~$PR$ (Fig.~4) the +radius~$PA$ of the circle, and erect on it at the point~$A$ +the perpendicular~$AF$ equal to the chord~$AF$ of the +arc~$AF$ which represents the error in the supposition +\index{Supposition, rule of}% +\index{Trial and error, rule of}% +made regarding the length of the radius~$PA$. Since +this error is an excess, it will be necessary to describe +\Figure{4}{0.3\textwidth} +a circle having a larger radius and to perform the +same operation as before, and so on, trying circles of +various sizes. Thus, the circle having the radius~$PA$ +gives the error~$F'A'$ which, since it falls on the hither +side of the point~$A'$, should be accounted negative. It +will consequently be necessary in Fig.~4 in applying +the ordinate~$A'F'$ to the abscissa~$PA'$ to draw that +ordinate below the axis. In this manner we shall obtain +several points $F$,~$F'$,~$\dots$, which will lie on a +curve of which the intersection~$R$ with the axis~$PA$ +\PageSep{139} +will give the true radius~$PR$ of the circle satisfying +the problem, and we shall find this intersection by +successively causing the points of the curve lying on +\MNote{Solution of a second problem by the curve of errors.} +the two sides of the axis as $F$,~$F'$,~$\dots$ to approach +nearer and nearer to one another. + +\textit{From a point, the position of which is unknown, three +\index{Point in space, position of a}% +objects are observed, the distances of which from one another +are known. The three angles formed by the rays of +light from these three objects to the eye of the observer are +also known. Required the position of the observer with +respect to the three objects.} + +If the three objects be joined by three straight +lines, it is plain that these three lines will form with +the visual rays from the eye of the observer a triangular +pyramid of which the base and the three face angles +forming the solid angle at the vertex are given. +And since the observer is supposed to be stationed at +the vertex, the question is accordingly reduced to determining +the dimensions of this pyramid. + +Since the position of a point in space is completely +determined by its three distances from three given +points, it is clear that the problem will be resolved, if +the distances of the point at which the observer is +stationed from each of the three objects can be determined. +Taking these three distances as the unknown +quantities we shall have three equations of the second +degree, which after elimination will give a resultant +equation of the eighth degree; but taking only one of +these distances and the relations of the two others to it +\PageSep{140} +for the unknown quantities, the final equation will be +only of the fourth degree. We can accordingly rigorously +\MNote{Problem of the observer and three objects.} +solve this problem by the known methods; but +the direct solution, which is complicated and inconvenient +in practice, may be replaced by the following +which is reached by the curve of errors. + +Let the three successive angles $APB$, $BPC$, $CPD$ +\index{Observer, problem of the, and three objects}% +(Fig.~5) be constructed, having the vertex~$P$ and +respectively equal to the angles observed between the +first object and the second, the second and the third, +\Figure{5}{0.4\textwidth} +the third and the first; and let the straight line~$PA$ +be taken at random to represent the distance from the +observer to the first object. Since the distance of +that object to the second is supposed to be known, +let it be denoted by~$AB$, and let it be laid off on the +line~$AB$. We shall in this way obtain the distance~$BP$ +of the second object to the observer. In like manner, +let $BC$, the distance of the second object to the +third, be laid off on~$BC$, and we shall have the distance~$PC$ +of that object to the observer. If, now, the +\PageSep{141} +distance of the third object to the first be laid off on +the line~$CD$, we shall obtain~$PD$ as the distance of +the first object to the observer. Consequently, if the +\MNote{Employment of the curve of errors.} +distance first assumed is exact, the two lines $PA$~and~$PD$ +will necessarily coincide. Making, therefore, on +the line~$PA$, prolonged if necessary, the segment +$PE = PD$, if the point~$E$ does not fall upon the point~$A$, +the difference will be the error of the first assumption~$PA$. +Having drawn the straight line~$PR$ (Fig.~6) +we lay off upon it from the fixed point~$P$, the abscissa~$PA$, +and apply to it at right angles the ordinate~$EA$; +we shall have the point~$E$ of the curve of errors~$ERS$. +\Figure{6}{0.4\textwidth} +Taking other distances for~$PA$, and making the same +construction, we shall obtain other errors which can be +similarly applied to the line~$PR$, and which will give +other points in the same curve. + +We can thus trace this curve through several +points, and the point~$R$ where it cuts the axis~$PR$ will +give the distance~$PR$, of which the error is zero, and +which will consequently represent the exact distance +of the observer from the first object. This distance +being known, the others may be obtained by the same +construction. + +It is well to remark that the construction we have +been considering gives for each point~$A$ of the line~$PA$, +\PageSep{142} +two points $B$~and~$B'$ of the line~$PB$; for, since +the distance~$AB$ is given, to find the point~$B$ it is only +\MNote{Eight possible solutions of the preceding problem.} +necessary to describe from the point~$A$ as centre and +with radius~$AB$ an arc of a circle cutting the straight +line~$PB$ at the two points $B$~and~$B'$,---both of which +points satisfy the conditions of the problem. In the +same manner, each of these last-mentioned points will +give two more upon the straight line~$PC$, and each of +the last will give two more on the straight line~$PD$. +Whence it follows that every point~$A$ taken upon the +straight line~$PA$ will in general give eight upon the +straight line~$PD$, all of which must be separately and +successively considered to obtain all the possible solutions. +I have said, \emph{in general}, because it is possible +(1)~for the two points $B$~and~$B'$ to coincide at a single +point, which will happen when the circle described +with the centre~$A$ and radius~$AB$ touches the straight +line~$PB$; and (2)~that the circle may not cut the +straight line~$PB$ at all, in which case the rest of the +construction is impossible, and the same is also to be +said regarding the points $C$,~$D$. Accordingly, drawing +the line~$GF$ parallel to~$BP$ and at a distance from it +equal to the given line~$AB$, the point~$F$ at which this +line cuts the line~$PE$, prolonged if necessary, will be +the limit beyond which the points~$A$ must not be taken +if we desire to obtain possible solutions. There exist +also limits for the points $B$~and~$C$, which may be employed +in restricting the primitive suppositions made +with respect to the distance~$PA$. +\PageSep{143} + +The eight points~$D$, which depend in general on +each point~$A$, answer to the eight solutions of which +the problem is susceptible, and when one has no special +\MNote{Reduction of the possible solutions in practice.} +datum by means of which it can be determined +which of these solutions answer best to the case proposed, +it is indispensable to ascertain them all by employing +for each one of the eight combinations a special +curve of errors. But if it be known, for example, +that the distance of the observer to the second object +is greater or less than his distance to the first, it will +then be necessary to take on the line~$PB$ only the +point~$B$ in the first case and the point~$B'$ in the second,---a +course which will reduce the eight combinations +one-half. If we had the same datum with regard +to the third object relatively to the second, and with +regard to the first object relatively to the third, then +the points $C$~and~$D$ would be determined, and we +should have but a single solution. + +These two examples may suffice to illustrate the +uses to which the method of curves can be put in solving +\index{Curves!method of, submitted to analysis|EtSeq}% +problems. But this method, which we have presented, +so to speak, in a mechanical manner, can also +be submitted to analysis. + +The entire question in fact is reducible to the description +of a curve which shall pass through a certain +number of points, whether these points be given by +calculation or construction, or whether they be given +by observation or single experiences entirely independent +of one another. The problem is in truth indeterminate, +\PageSep{144} +for strictly speaking there can be made +to pass through a given number of points an infinite +\MNote{General conclusion on the method of curves.} +\index{Curves!advantages of the method of}% +number of different curves, regular or irregular, that +is, subject to equations or arbitrarily drawn by the +hand. But the question is not to find any solutions +whatever but the simplest and easiest in practice. + +Thus if there are only two points given, the simplest +solution is a straight line between the two points. +\index{Straight line}% +If there are three points given, the arc of a circle is +\index{Circle}% +drawn through these points, for the arc of a circle +after the straight line is the simplest line that can be +described. + +But if the circle is the simplest curve with respect +to description, it is not so with respect to the equation +between its abscissæ and rectangular ordinates. +In this latter point of view, those curves may be regarded +as the simplest of which the ordinates are expressed +by an integral rational function of the abscissæ, +as in the following equation +\[ +y = a + bx + cx^{2} + dx^{3} + \dots, +\] +where $y$~is the ordinate and $x$~the abscissa. Curves +of this class are called in general \emph{parabolic}, because +\index{Parabolic@\textit{Parabolic} curves|EtSeq}% +they may be regarded as a generalisation of the parabola,---a +curve represented by the foregoing equation +when it has only the first three terms. We have already +illustrated their employment in resolving equations, +and their consideration is always useful in the +approximate description of curves, for the reason that +a curve of this kind can always be made to pass +\PageSep{145} +through as many points of a given curve as we please,---it +being only necessary to take as many undetermined +coefficients $a$,~$b$,~$c$,~$\dots$ as there are points given, +\MNote{Parabolic curves.} +and to determine these coefficients so as to obtain the +abscissæ and ordinates for these points. Now it is +clear that whatever be the curve proposed, the parabolic +curve so described will always differ from it by +less and less according as the number of the different +points is larger and larger and their distance from +one another smaller and smaller. + +Newton was the first to propose this problem. The +\index{Newton, his problem}% +following is the solution which he gave of it: + +Let $P$,~$Q$, $R$,~$S$,~$\dots$ be the values of the ordinates~$y$ +corresponding to the values $p$,~$q$, $r$,~$s$,~$\dots$ of +the abscissæ~$x$; we shall have the following equations +\[ +\begin{array}{r@{\,}*{3}{l@{\,}}l} +P &= a + bp &+ cp^{2} &+ dp^{3} &+ \dots, \\ +Q &= a + bq &+ cq^{2} &+ dq^{3} &+ \dots, \\ +R &= a + br &+ cr^{2} &+ dr^{3} &+ \dots, \\ +\hdotsfor{5}\Add{.} +\end{array} +\] +The number of these equations must be equal to the +number of the undetermined coefficients $a$,~$b$,~$c$,~$\dots$. +Subtracting these equations from one another, the remainders +will be divisible by $q - p$, $r - q$,~$\dots$, and +we shall have after such division +\[ +\begin{array}{r@{\,}*{2}{l@{\,}}l} +\dfrac{Q - P}{q - p} &= b + c(q + p) &= d(q^{2} + qp + p^{2}) &+ \dots, \\[8pt] +\dfrac{R - Q}{r - q} &= b + c(r + q) &= d(r^{2} + rq + q^{2}) &+ \dots, \\ +\hdotsfor{4}\Add{.} +\end{array} +\] +\PageSep{146} + +Let +\[ +\frac{Q - P}{q - p} = Q_{1},\quad +\frac{R - Q}{r - q} = R_{1},\quad +\frac{S - R}{s - r} = S_{1},\dots\Add{.} +\] +\MNote{Newton's problem.} +We shall find in like manner, by subtraction and division, +the following: +\[ +\begin{array}{r@{\,}l@{\,}l} +\dfrac{R_{1} - Q_{1}}{r - p} &= c + d(r + q + p) &+ \dots, \\[8pt] +\dfrac{S_{1} - R_{1}}{s - q} &= c + d(s + r + q) &+ \dots, \\ +\hdotsfor{3}\Add{.} +\end{array} +\] + +Further let +\[ +\frac{R_{1} - Q_{1}}{r - p} = R_{2},\quad +\frac{S_{1} - R_{1}}{s - q} = S_{2},\dots. +\] +We shall have +\[ +\frac{S_{2} - R_{2}}{s - p} = d + \dots, +\] +and so on. + +In this manner we shall find the value of the coefficients +$a$,~$b$,~$c$,~$\dots$ commencing with the last; and, +substituting them in the general equation +\[ +y = a + bx + cx^{2} + dx^{3} + \dots, +\] +we shall obtain, after the appropriate reductions have +been made, the formula +\[ +y = P + + Q_{1}(x - p) + + R_{2}(x - p)(x - q) + + S_{3}(x - p)(x - q)(x - r) + \dots, +\Tag{(1)} +\] +which can be carried as far as we please. + +But this solution may be simplified by the following +consideration. + +Since $y$~necessarily becomes $P$,~$Q$,~$R$\Add{,}~$\dots$, when $x$~becomes +\PageSep{147} +$p$,~$q$,~$r$, it is easy to see that the expression +for~$y$ will be of the form +\MNote{Simplification of Newton's solution.} +\[ +y = AP + BQ + CR + DS + \dots +\Tag{(2)} +\] +where the quantities $A$,~$B$, $C$,~$\dots$ are so expressed in +terms of~$x$ that by making $x = p$ we shall have +\[ +A = 1,\quad B = 0,\quad C = 0,\dots, +\] +and by making $x = q$ we shall have +\[ +A = 0,\quad B = 1,\quad C = 0,\quad D = 0,\dots, +\] +and by making $x = r$ we shall similarly have +\[ +A = 0,\quad B = 0,\quad C = 1,\quad D = 0,\dots\ \text{etc.} +\] +Whence it is easy to conclude that the values of $A$, +$B$, $C$,~$\dots$ must be of the form +\begin{align*} +A &= \frac{(x - q)(x - r)(x - s)\dots}{(p - q)(p - r)(p - s)\dots}, \\ +B &= \frac{(x - p)(x - r)(x - s)\dots}{(q - p)(q - r)(q - s)\dots}, \\ +C &= \frac{(x - p)(x - q)(x - s)\dots}{(r - p)(r - q)(r - s)\dots}, +\end{align*} +where there are as many factors in the numerators +and denominators as there are points given of the +curve less one. + +The last expression for~$y$ (see equation~2), although +different in form, is the same as equation~1. To show +this, the values of the quantities $Q_{1}$,~$R_{2}$, $S_{3}$,~$\dots$ need +only be developed and substituted in equation~1 and +the terms arranged with respect to the quantities $P$, +$Q$, $R$,~$\dots$\Add{.} But the last expression for~$y$ (equation~2) +is preferable, partly because of the simplicity of the +\PageSep{148} +analysis from which it is derived, and also because of +its form, which is more convenient for computation. + +\MNote{Possible uses of Newton's problem.} +Now, by means of this formula, which it is not +difficult to reduce to a geometrical construction, we +are able to find the value of the ordinate~$y$ for any abscissa~$x$, +because the ordinates $P$,~$Q$, $R$,~$\dots$ for the +given abscissæ $p$,~$q$, $r$,~$\dots$ are known. Thus, if we +have several of the terms of any series, we can find +any intermediate term that we wish,---an expedient +which is extremely valuable for supplying lacunæ +which may arise in a series of observations or experiments, +\index{Experiments!expedient@an expedient for supplying lacunæ in a series of}% +\index{Observations, expedient for supplying lacunæ in series of}% +or in tables calculated by formulæ or in given +\index{Tables!expedient for supplying lacunæ in}% +constructions. + +If this theory now be applied to the two examples +\index{Regula@\textit{Regula falsi}}% +\index{Supposition, rule of}% +\index{Trial and error, rule of}% +discussed above and to similar examples in which we +have errors corresponding to different suppositions, we +can directly find the error~$y$ which corresponds to any +intermediate supposition~$x$ by taking the quantities +$P$,~$Q$, $R$,~$\dots$, for the errors found, and $p$,~$q$, $r$,~$\dots$ for +the suppositions from which they result. But since +in these examples the question is to find not the error +which corresponds to a given supposition, but the +supposition for which the error is zero, it is clear that +the present question is the opposite of the preceding +and that it can also be resolved by the same formula +by reciprocally taking the quantities $p$,~$q$, $r$,~$\dots$ for +the errors, and the quantities $P$,~$Q$, $R$,~$\dots$ for the +corresponding suppositions. Then $x$~will be the error +for the supposition~$y$; and consequently, by making +\PageSep{149} +$x = 0$, the value of~$y$ will be that of the supposition +for which the error is zero. + +Let $P$,~$Q$, $R$,~$\dots$ be the values of the unknown +quantity in the different suppositions, and $p$,~$q$, $r$\Add{,}~$\dots$ +\MNote{Application of Newton's problem to the preceding examples.} +the errors resulting from these suppositions, to which +the appropriate signs are given. We shall then have +for the value of the unknown quantity of which the +error is zero, the expression +\[ +AP + BQ + CR + \dots, +\] +in which the values of $A$,~$B$,~$C$\Add{,}~$\dots$ are +\begin{align*} +A &= \frac{q}{q - r} × \frac{r}{r - p} × \dots, \displaybreak[1] \\ +B &= \frac{P}{p - q} × \frac{r}{r - q} × \dots, \displaybreak[1] \\ +C &= \frac{p}{p - r} × \frac{q}{q - r} × \dots, +\end{align*} +where as many factors are taken as there are suppositions +less one. +\index{Curves!employment of in the solution of problems|)}% +\index{Problems!employment of curves in the solution of|)}% +\PageSep{150} +%[Blank page] +\PageSep{151} + + +\Appendix{Note on the Origin of Algebra.} +\PgLabel{151} +\index{Algebra!history of}% + +\First{The} impression (\PgRef{54}) that Diophantus was the +\index{Diophantus}% +``inventor'' of algebra, which sprang, in its Diophantine +form, full-fledged from his brain, was a widespread +one in the eighteenth and in the beginning of +the nineteenth century. But, apart from the intrinsic +improbability of this view which is at variance with +the truth that science is nearly always gradual and +organic in growth, modern historical researches have +traced the germs and beginnings of algebra to a much +remoter date, even in the line of European historical +continuity. The Egyptian book of Ahmes contains +\index{Ahmes}% +examples of equations of the first degree. The early +Greek mathematicians performed the partial resolution +\index{Greeks, mathematics of the}% +of equations of the second and third degree +by geometrical methods. According to Tannery, an +\index{Tannery, M. Paul}% +embryonic indeterminate analysis existed in Pre-Christian +times (Archimedes, Hero, Hypsicles). But +\index{Archimedes}% +\index{Hero}% +\index{Hypsicles}% +the merit of Diophantus as organiser and inaugurator +of a more systematic short-hand notation, at +least in the European line, remains; he enriched +whatever was handed down to him with the most +manifold extensions and applications, betokening his +\PageSep{152} +originality and genius, and carried the science of algebra +\index{Algebra!among the Arabs}% +\index{Algebra!India@in India}% +to its highest pitch of perfection among the +\PgLabel{152} +Greeks. (See Cantor, \textit{Geschichte der Mathematik}, second +\index{Cantor}% +edition, Vol.~I., p.~438, et~seq.; Ball, \textit{Short Account +\index{Ball}% +of the History of Mathematics}, second edition, p.~104 +et~seq.; Fink, \textit{A Brief History of Mathematics}, pp.~63 +\index{Fink}% +et~seq., 77~et~seq. (Chicago: The Open Court +Publishing~Co.) + +The development of Hindu algebra is also to be +noted in connexion with the text of \PgRange{59}{60}. The +Arabs, who had considerable commerce with India, +\index{Arabs!Algebra among the}% +drew not a little of their early knowledge from the +works of the Hindus. Their algebra rested on both +that of the Hindus and the Greeks. (See Ball, \textit{op.~cit.}, +p.~150 et~seq.; Cantor, \textit{op.~cit.}, Vol.~I., p.~651 et~seq.).---\textit{Trans.} +\PageSep{153} +\BackMatter +\printindex +\iffalse +INDEX. + +Academies, rise of 62, 63 + +Ahmes 151 + +Algebra + definition of 2 + history of|EtSeq#history 54 % et seq., + history of 151 + essence of 55 + name@the name of 59 + among the Arabs|EtSeq 59 % et seq, + among the Arabs 152 + Europe@in Europe 60 + Italy@in Italy 64 + India@in India 152 + generality@the generality of 69 + hand-writing of 69 + application of geometry to|EtSeq 100, 127 % et seq. + +Algebraical resolution of equations + limits of the 96 + +Alligation + generally|EtSeq 44 % et seq.; + alternate 47 + +Analysis + indeterminate|EtSeq 47 % et seq., + indeterminate 55 + +Angle, trisection of an 62, 81 + +Angular sections, theory of 80 + +Annuities 16 + +Apollonius 54, 59 + +Arabs + Algebra among the|EtSeq 59 % et seq., + Algebra among the 152 + +Archimedes 54, 151 + +Archimedes|FN 58 % footnote + +Arithmetic + universal|EtSeq 2 % et seq.; + operations of|EtSeq 24 % et seq. + +Arithmetical progression revealing the roots 120 + +Arithmetical progression revealing the roots|EtSeq 112 % et seq. + +Arithmetical proportion 12 + +Astronomy, mechanics, and physics, curves of errors in 136 + +Average life|EtSeq 45 % et seq. + +Bachet de Méziriac 58 + +Ball 152 + +Binomial theorem 115 + +Binomials, extraction of the square roots of two imaginary 77 + +Biquadratic equations 63, 88, 94, 133 + +Bombelli 63, 64 + +Bret, M.|FN 93 % footnote. + +Briggs 20 + +Buteo 61 + +Cantor|FN 54, 60 % footnote, + +Cantor 152 + +Cardan 60, 61, 68, 82, 90 + +Checks on multiplication and division 39 + +Circle 144 + squaring of the 62 + and inscribed polygon, problem of the 138 + +Clairaut 69, 90 + +Coefficients + indeterminate 89 + greatest negative|EtSeq 107 % et seq., + greatest negative 117 + +Common divisor of two equations 121 + +Complements, subtraction by 26 + +Constantinople 58 + +Continued fractions, solution of alligation by|EtSeq 50 % et seq. + +Convergents 7 + +Cube, duplication of the 62 + +Cube roots of a quantity, the three 70 + +Cubic radicals 75 + +Curves + representation of equations by|EtSeq 101 % et seq; + employment of in the solution of problems 127-149 + method of, submitted to analysis|EtSeq 143 % et seq.; + advantages of the method of 135, 144 + +Decimal + fractions 9 + numbers|EtSeq 27 % et seq. + +Decimals + multiplication of 30 + division of 31 +\PageSep{154} + +DeMorgan@{\Typo{DeMorgan}{De Morgan}} v + +Descartes viii, 60, 65, 89, 93, 127 + +Differences, the equation of|EtSeq 114 % et seq., + +Differences, the equation of 123 + +Differential Calculus 131 + +Diophantine problems 55 + +Diophantus|EtSeq 54 % et seq + +Diophantus 151 + +Division + nine@by \textit{nine} 34 + eight@by \textit{eight} 34 + seven@by \textit{seven}|EtSeq 34 % et seq.; + decimals@of decimals 31 + +Divisor, greatest common|EtSeq 2 % et seq. + +Duhring@{Dühring, E.} v + +Duodecimal system 32 + +Ecole@{\Typo{Ecole}{École} Normale} v, xi, 12 + +Economy of thought vii + +Efflux, law of 42 + +Eleven, the number, test of divisibility by 37 + +Elimination + method of 121 + general formulæ for 122 + +Equations + second@of the second degree 56 + third@of the third degree 60, 66, 82 + fourth@of the fourth degree 63, 87, 133 + fifth@of the fifth degree 64 + theory of 65, 84 + biquadratic 88 + limits of the algebraical resolution of 96 + fifth@of the fifth degree 96 + mth@of the $m$th degree 96 + general remarks upon the roots of|EtSeq 102 % et seq.; + graphic resolution of 102 + odd@of an odd degree, roots of 105 + even@of an even degree, roots of 106 + real roots of, limits of the|EtSeq 107 % et seq.; + common divisor of two 121 + constructions for solving|EtSeq 100 % et seq. + constructions for solving 124 + machine@a machine for solving 126 + +Equi-different numbers 13 + +Errors, curve of|EtSeq 136 % et seq. + +Euclid 2, 57 + +Euler viii, x, 93 + +Europe, algebra in 60 + +Evolution 11, 40 + +Experiments + average of 46 + expedient@an expedient for supplying lacunæ in a series of 148 + +Falling stone, spaces traversed by a 42 + +False, rule of 137 + +Fermat 58 + +Ferrari, Louis 64 + +Ferrous, Scipio|EtSeq 60 % et seq. + +Fifth degree, equations of the 96 + +Fink 152 + +Fourth degree, equations of the 133 + +Fractional expressions in equations 134 + +Fractions|EtSeq 2 % et seq.; + +Fractions + continued|EtSeq 3 % et seq.; + converging 6 + decimal 9 + origin of continued 10 + +France 58, 61 + +Galileo ix + +Geometers, ancient|EtSeq 54 % et seq. + +Geometers, ancient 58, 59 + +Geometrical + proportion 13 + calculus 24 + +Geometry 24, 60 + application of to algebra|EtSeq 100, 127 % et seq. + +Germany 61 + +Girard, Albert 62 + +Grain, of different prices 44 + +Greeks, mathematics of the vii, 151 + +Greeks, mathematics of the|EtSeq 54 % et seq. + +Hand-writing of algebra 69 + +Harriot 65 + +Hero 59, 151 + +Horses 43 + +Hudde 65, 82 + +Huygens ix, 10 + +Hypsicles 151 + +Imaginary binomials, square roots of 77 + +Imaginary expressions|EtSeq 79 % et seq. + +Imaginary expressions 83 + +Imaginary quantities, office of the 87 + +Imaginary roots, occur in pairs 99 + +Indeterminate analysis|EtSeq 47 % et seq. + +Indeterminate analysis 55 + +Indeterminate coefficients 89 + +Indeterminates, the method of 83 + +Ingredients 48 + +Interest 15 + +Intersections, with the axis give roots|EtSeq 102 % et seq , + +Intersections, with the axis give roots 113 + +Inventors, great 22 + +Involution and evolution 11 + +Irreducible case 61, 65, 69, 73, 82 + +Italy, cradle of algebra in Europe 61, 64 + +Laborers, work of 41 + +Lagrange, J. L.#Lagrange v + +Lagrange, J. L.|EtSeq#Lagrange vii % et seq. +\PageSep{155} + +Laplace v, xi + +Lavoisier xii + +Leibnitz viii + +Life insurance|EtSeq 45 % et seq. + +Life, probability of 46 + +Light, law of the intensity of 129 + +Lights, problem of the two|EtSeq 129 % et seq. + +Limits of roots 107-120 + +Logarithms|EtSeq 16 % et seq. + +Logarithms 40 + advantages in calculating by 28 + origin of 19 + tables of 20 + +Machine for solving equations 124-126 + +Mathematics + wings of 24 + exactness of 43 + evolution of vii + +Mean values|EtSeq 45 % et seq. + +Mechanics, astronomy, and physics, curves of errors in 136 + +Metals, mingling of, by fusion 44 + +Meziriac@Méziriac, Bachet de 58 + +Minimal values 132 + +Mixtures, rule of|EtSeq 44 % et seq. + +Mixtures, rule of 49 + +Monge v, xi + +Mortality, tables of 45 + +Moving bodies, two 98 + +Multiple roots 105 + +Multiplication + abridged methods of|EtSeq 26 % et seq.; + inverted 28 + approximate 29 + decimals@of decimals 30 + +Music 22 + +Napier|EtSeq 17 % et seq. + +Napoleon xii + +Negative roots 60 + +Newton, his problem 145, viii + +Nine + property of the number|EtSeq 31 % et seq.; + property of the number generalised 33 + +Nizze|FN 58 % footnote. + +Numeration, systems of 1 + +Numerical equations |See Equations 0 + +Numerical equations + resolution of 96-126 + conditions of the resolution of 97 + position of the roots of 98 + +Observations, expedient for supplying lacunæ in series of 148 + +Observer, problem of the, and three objects 140 + +Oughtred 30 + +Paciolus, Lucas 59, 60 + +Pappus 59 + +Parabolic@\textit{Parabolic} curves|EtSeq 144 % et seq. + +Peletier 61 + +Peyrard 58 + +Physics, astronomy, and mechanics, curves of errors in 136 + +Planetarium 9 + +Point in space, position of a 139 + +Polygon, problem of the circle and inscribed 138 + +Polytechnic School v, xi + +Positive roots, superior and inferior limits of the 109 + +Powers|EtSeq 10 % et seq. + +Practice, theory and 43 + +Present value 15 + +Printing, invention of 59 + +Probabilities, calculus of|EtSeq 45 % et seq. + +Problems 110 + solution@for solution 62 + employment of curves in the solution of 127-149 + +Proclus 59 + +Progressions, theory of 12, 14 + +Proportion|EtSeq 11 % et seq. + +Ptolemy 59 + +Radical expressions in equations 134 + +Radicals, cubic 75 + +Ratios, constant 42 + +Ratios, constant|EtSeq 2, 11 % et seq. + +Reality of roots 76, 83, 85, 93 + +Regula@\textit{Regula falsi} 137, 148 + +Remainders + theory of|EtSeq 34 % et seq. + theory of 38 + negative|EtSeq 35 % et seq. + +Romans, mathematics of the 54 + +Roots + negative 60 + equations@of equations of the third degree 71 + reality@the reality of the 74, 76, 79, 83, 85, 93 + biquadratic@of a biquadratic equation 94 + multiple 105 + superior and inferior limits of the positive 109 + method for finding the limits of 110 + separation of the 112 + arithmetical@the arithmetical progression revealing the|EtSeq 112 % et seq. + arithmetical@the arithmetical progression revealing the 120 + quantity less than the difference between any two 113 + smallest|EtSeq 116 % et seq.; + limits of the positive and negative 119 + +Rule + Cardan's 68 + false@of false 137 + mixtures@of mixtures|EtSeq 44 % et seq.; + three@of three|EtSeq 11, 40 % et seq. +\PageSep{156} + +Science + history of 22 + development of|EtSeq vii % et seq. + +Seven, tests of divisibility by 35 + +Short-mind symbols|EtSeq vii % et seq. + +Signs $+$ and $-$ 57 + +Squaring of the circle 62 + +Stenophrenic symbols|EtSeq vii % et seq. + +Straight line 144 + +Substitutions|EtSeq 111 % et seq. + +Substitutions 123 + +Subtraction, new method of|EtSeq 25 % et seq. + +Sum and difference, of two numbers 56 + +Supposition, rule of 137, 148 + +Symbols|EtSeq vii % et seq. + +Tables 137 + expedient for supplying lacunæ in 148 + +Tannery, M. Paul|FN 58 % footnote + +Tannery, M. Paul 151 + +Tartaglia 60, 61 + +Temperament, theory of 23 + +Theon 59 + +Theory and practice 43 + +Theory of remainders, utility of the 38 + +Third degree, equations of the 71, 82 + +Three roots, reality of the 93 + +Trial and error, rule of 137, 148 + +Trisection of an angle 62, 81 + +Turks 58 + +Undetermined quantities 82 + +Unity, three cubic roots of 72 + +Unknown quantity 55 + +Values + mean|EtSeq 45 % et seq.; + minimal 132 + +Variations, calculus of x + +Vatican library 58 + +Vieta viii, 62, 65 + +Vlacq 20 + +Wallis viii + +Wertheim, G.|FN 58 % footnote. + +Woodhouse x + +Xylander 58 +\fi +\PageSep{157} + +\Catalog +%[** TN: Macro prints the following text] +% Catalogue of Publications +% of the +% Open Court Publishing Co. + +\begin{Author}{COPE, E. D.} +\Title{THE PRIMARY FACTORS OF ORGANIC EVOLUTION.} +{121~cuts. Pp.~xvi,~547. Cloth,~\$2.00 (10s.).} +\end{Author} + +\begin{Author}{MÜLLER, F. MAX.} +\Title{THREE INTRODUCTORY LECTURES ON THE SCIENCE OF +THOUGHT.} +{128~pages. Cloth,~75c (3s.\ 6d.).} + +\Title{THREE LECTURES ON THE SCIENCE OF LANGUAGE.} +{112~pages. 2nd~Edition. Cloth,~75c (3s.\ 6d.).} +\end{Author} + +\begin{Author}{ROMANES, GEORGE JOHN.} +\Title{DARWIN AND AFTER DARWIN.} +{Three Vols., \$4.00. Singly, as follows:}{} + +%[** TN: Next three extries get a bit less hanging indentation] +\Title[3\parindent]{}{1.~\textsc{The Darwinian Theory.} 460~pages. 125~illustrations. Cloth, \$2.00\Add{.}} + +\Title[3\parindent]{}{2.~\textsc{Post-Darwinian Questions.} Heredity and Utility. Pp.~338. \$1.50\Add{.}} + +\Title[3\parindent]{}{3.~\textsc{Post-Darwinian Questions.} Isolation and Physiological Selection +Pp.~181. \$1.00.} + +\Title{AN EXAMINATION OF WEISMANNISM.} +{236~pages. Cloth, \$1.00.} + +\Title{THOUGHTS ON RELIGION.} +{Third Edition, Pages,~184. Cloth, gilt top, \$1.25.} +\end{Author} + +\begin{Author}{SHUTE, DR. D. KERFOOT.} +\Title{FIRST BOOK IN ORGANIC EVOLUTION.} +{9~colored plates, 39~cuts. Pp.~xvi+285. Price, \$2.00 (7s.\ 6d.).} +\end{Author} + +\begin{Author}{MACH, ERNST.} +\Title{THE SCIENCE OF MECHANICS.} +{Translated by \textsc{T. J. McCormack.} 250~cuts. 534~pages. \$2.50 (12s.\ 6d.)} + +\Title{POPULAR SCIENTIFIC LECTURES.} +{Third Edition. 415~pages. 59~cuts. Cloth, gilt top. \$1.50 (7s.\ 6d.).} + +\Title{THE ANALYSIS OF THE SENSATIONS.} +{Pp.~208. 37~cuts. Cloth, \$1.25 (6s.\ 6d.).} +\end{Author} + +\begin{Author}{LAGRANGE, JOSEPH LOUIS.} +\Title{LECTURES ON ELEMENTARY MATHEMATICS.} +{With portrait of the author. Pp.~172. Price, \$1.00 (5s.).} +\end{Author} + +\begin{Author}{DE MORGAN, AUGUSTUS.} +\Title{ON THE STUDY AND DIFFICULTIES OF MATHEMATICS.} +{New Reprint edition with notes. Pp.~viii+288. Cloth, \$1.25 (5s.).} + +\Title{ELEMENTARY ILLUSTRATIONS OF THE DIFFERENTIAL AND +INTEGRAL CALCULUS.} +{New reprint edition. Price, \$1.00 (5s.).} +\end{Author} + +\begin{Author}{FINK, KARL.} +\Title{A BRIEF HISTORY OF MATHEMATICS.} +{Trans.\ by W. W. Beman and D. E. Smith. Pp.\Typo{,}{}~333. Cloth, \$1.50 (5s.\ 6d.)} +\end{Author} + +\begin{Author}{SCHUBERT, HERMANN.} +\Title{MATHEMATICAL ESSAYS AND RECREATIONS.} +{Pp.~149. Cuts,~37. Cloth, 75c (33.\ 6d.).} +\end{Author} + +\begin{Author}{HUC AND GABET, MM.} +\Title{TRAVELS IN TARTARY, THIBET AND CHINA.} +{100~engravings. Pp\Add{.}~28+660. 2~vols. \$2.00 (10s.). One vol., \$1.25 (5s.)} +\end{Author} +\PageSep{158} + +\begin{Author}{CARUS, PAUL.} +\Title{THE HISTORY OF THE DEVIL, AND THE IDEA OF EVIL.} +{311~Illustrations. Pages,~500. Price, \$6.00 (30s.).} + +\Title{EROS AND PSYCHE.} +{Retold after Apuleius. With Illustrations by Paul Thumann. Pp.~125. +Price, \$1.50 (6s.).} + +\Title{WHENCE AND WHITHER?} +{An Inquiry into the Nature of the Soul. 196~pages. Cloth, 75c (3s.\ 6d.)} + +\Title{THE ETHICAL PROBLEM.} +{Second edition, revised and enlarged. 351~pages. Cloth, \$1.25 (6s.\ 6d.)} + +\Title{FUNDAMENTAL PROBLEMS.} +{Second edition, revised and enlarged. 372~pp.\ Cl., \$1.50 (7s.\ 6d.).} + +\Title{HOMILIES OF SCIENCE.} +{317~pages. Cloth, Gilt Top, \$1.50 (7s.\ 6d.).} + +\Title{THE IDEA OF GOD.} +{Fourth edition. 32~pages. Paper, 15c (9d.).} + +\Title{THE SOUL OF MAN.} +{2nd~ed. 182~cuts. 482~pages. Cloth, \$1.50 (6s.).} + +\Title{TRUTH IN FICTION. \textsc{Twelve Tales with a Moral.}} +{White and gold binding, gilt edges. Pp.~111. \$1.00 (5s.).} + +\Title{THE RELIGION OF SCIENCE.} +{Second, extra edition. Pp.~103. Price, 50c (2s.\ 6d.).} + +\Title{PRIMER OF PHILOSOPHY.} +{240~pages. Second Edition. Cloth, \$1.00 (5s.).} + +\Title{THE GOSPEL OF BUDDHA. According to Old Records.} +{Fifth Edition. Pp.~275. Cloth, \$1.00 (5s.). In German, \$1.25 (6s.\ 6d.)\Add{.}} + +\Title{BUDDHISM AND ITS CHRISTIAN CRITICS.} +{Pages,~311. Cloth, \$1.25 (6s.\ 6d.).} + +\Title{KARMA. \textsc{A Story of Early Buddhism.}} +{Illustrated by Japanese artists. Crêpe paper, 75c (3s.\ 6d.).} + +\Title{NIRVANA: \textsc{A Story of Buddhist Psychology.}} +{Japanese edition, like \textit{Karma}. \$1.00 (4s.\ 6d.).} + +\Title{LAO-TZE'S TAO-TEH-KING.} +{Chinese-English. Pp.~360. Cloth, \$3.00 (15s.).} +\end{Author} + +\begin{Author}{CORNILL, CARL HEINRICH.} +\Title{THE PROPHETS OF ISRAEL.} +{Pp.,~200\Add{.} Cloth, \$1.00 (5s.).} + +\Title{HISTORY OF THE PEOPLE OF ISRAEL.} +{Pp.~vi+325. Cloth, \$1.50 (7s. 6d.).} +\end{Author} + +\begin{Author}{POWELL, J. W.} +\Title{TRUTH AND ERROR; or, the Science of Intellection.} +{Pp.~423. Cloth, \$1.75 (7s. 6d.).} +\end{Author} + +\begin{Author}{RIBOT, TH.} +\Title{THE PSYCHOLOGY OF ATTENTION.}{} + +\Title{THE DISEASES OF PERSONALITY.}{} + +\Title{THE DISEASES OF THE WILL.} +{Cloth, 75~cents each (3s.\ 6d.). \textit{Full set, cloth, \$1.75} (9s.).} + +\Title{EVOLUTION OF GENERAL IDEAS.} +{Pp.~231. Cloth, \$1.25 (5s.).} +\end{Author} + +\begin{Author}{WAGNER, RICHARD.} +\Title{A PILGRIMAGE TO BEETHOVEN.} +{A Story. With portrait of Beethoven. Pp.~40. Boards, 50c (2s.\ 6d.).} +\end{Author} + +\begin{Author}{HUTCHINSON, WOODS.} +\Title{THE GOSPEL ACCORDING TO DARWIN.} +{Pp.~xii+241. Price, \$1.50 (6s.).} +\end{Author} + +\begin{Author}{FREYTAG, GUSTAV.} +\Title{THE LOST MANUSCRIPT. A Novel.} +{2~vols. 953~pages. Extra cloth, \$4.00 (21s\Add{.}). One vol., cl., \$1.00 (5s.)\Add{.}} + +\Title{MARTIN LUTHER.} +{Illustrated. Pp.~130. Cloth, \$1.00 (5s.).} +\end{Author} +\PageSep{159} + +\begin{Author}{AÇVAGHOSHA.} +\Title{DISCOURSE ON THE AWAKENING OF FAITH in the Mahâyâna.} +{Translated for the first time from the Chinese version by Tietaro +Suzuki. Pages,~176. Price, cloth, \$1.25 (5s.\ 6d.).} +\end{Author} + +\begin{Author}{TRUMBULL, M. M.} +\Title{THE FREE TRADE STRUGGLE IN ENGLAND.} +{Second Edition. 296~pages. Cloth,~75c (3s.\ 6d.).} + +\Title{WHEELBARROW: \textsc{Articles and Discussions on the Labor Question.}} +{With portrait of the author. 303~pages. Cloth, \$1.00 (5s.).} +\end{Author} + +\begin{Author}{GOETHE AND SCHILLER'S XENIONS.} +\Title{Translated by Paul Carus. Album form. Pp.~162. Cl., \$1.00 (5s.).}{} +\end{Author} + +\begin{Author}{OLDENBERG, H.} +\Title{ANCIENT INDIA: ITS LANGUAGE AND RELIGIONS.} +{Pp.~100. Cloth, 50c (2s. 6d.).} +\end{Author} + +\begin{Author}{CONWAY, DR. MONCURE DANIEL.} +\Title{SOLOMON, AND SOLOMONIC LITERATURE.} +{Pp.~243. Cloth, \$1.50 (6s.).} +\end{Author} + +\begin{Author}{GARBE, RICHARD.} +\Title{THE REDEMPTION OF THE BRAHMAN. \textsc{A Tale of Hindu Life.}} +{Laid paper. Gilt top. 96~pages. Price, 75c (3s.\ 6d.).} + +\Title{THE PHILOSOPHY OF ANCIENT INDIA.} +{Pp.~89. Cloth, 50c (2s.\ 6d.).} +\end{Author} + +\begin{Author}{HUEPPE, FERDINAND.} +\Title{THE PRINCIPLES OF BACTERIOLOGY.} +{28~Woodcuts. Pp.~x+467. Price, \$1.75 (9s.).} +\end{Author} + +\begin{Author}{LÉVY-BRUHL, PROF. L.} +\Title{HISTORY OF MODERN PHILOSOPHY IN FRANCE.} +{23 Portraits. Handsomely bound. Pp. 500. Price, \$3.00 (12s.).} +\end{Author} + +\begin{Author}{TOPINARD, DR. PAUL.} +\Title{SCIENCE AND FAITH, \textsc{or Man as an Animal and Man as a Member +of Society.}} +{Pp.~374. Cloth, \$1.50 (6s.\ 6d.).} +\end{Author} + +\begin{Author}{BINET, ALFRED.} +\Title{THE PSYCHOLOGY OF REASONING.} +{Pp.~193. Cloth, 75c (3s.\ 6d.).} + +\Title{THE PSYCHIC LIFE OF MICRO-ORGANISMS.} +{Pp.~135. Cloth, 75 cents.} + +\Title{ON DOUBLE CONSCIOUSNESS.} +{See No.~8, Religion of Science Library.} +\end{Author} + +\begin{Author}{THE OPEN COURT.} +\Title{A Monthly Magazine Devoted to the Science of Religion, the Religion of +Science, and the Extension of the Religious Parliament Idea.} +{Terms: \$1.00 a year; 5s.\ 6d.\ to foreign countries in the Postal Union. +Single Copies, 10~cents (6d.).} +\end{Author} + +\begin{Author}{THE MONIST.} +\Title{A Quarterly Magazine of Philosophy and Science.} +{Per copy, 50~cents; Yearly, \$2.00. In England and all countries in +U.P.U. per copy, 2s.~6d.: Yearly, 9s.~6d.} +\end{Author} + +\tb +\vfill +\begin{center} +CHICAGO: \\ +\large THE OPEN COURT PUBLISHING CO. \\ +\footnotesize Monon Building, 324 Dearborn St. \\ +LONDON: Kegan Paul, Trench, Trübner \&~Company, Ltd. +\end{center} +\PageSep{160} +\newpage +\begin{center} +\makebox[0.9\textwidth][s]{\LARGE\itshape The Religion of Science Library.} +\tb +\end{center} + +\CatalogSmallFont +A collection of bi-monthly publications, most of which are reprints of +books published by The Open Court Publishing Company. Yearly, \$1.50. +Separate copies according to prices quoted. The books are printed upon +good paper, from large type. + +The Religion of Science Library, by its extraordinarily reasonable price +will place a large number of valuable books within the reach of all readers. + +The following have already appeared in the series: + +\Item{No.\ 1.} \textit{The Religion of Science.} By \textsc{Paul Carus.} 25c (1s.\ 6d.). + +\Item{2.} \textit{Three Introductory Lectures on the Science of Thought.} By \textsc{F. Max +Müller.} 25c (1s.\ 6d.). + +\Item{3.} \textit{Three Lectures on the Science of Language.} \textsc{F. Max Müller.} 25 (1s.\ 6d.) + +\Item{4.} \textit{The Diseases of Personality.} By \textsc{Th.\ Ribot.} 25c (1s.\ 6d.). + +\Item{5.} \textit{The Psychology of Attention.} By \textsc{Th.\ Ribot.} 25c (1s.\ 6d.). + +\Item{6.} \textit{The Psychic Life of Micro-Organisms.} By \textsc{Alfred Binet.} 25c (1s.\ 6d.) + +\Item{7.} \textit{The Nature of the State.} By \textsc{Paul Carus.} 15c (9d.). + +\Item{8.} \textit{On Double Consciousness.} By \textsc{Alfred Binet.} 15c (9d.). + +\Item{9.} \textit{Fundamental Problems.} By \textsc{Paul Carus.} 50c (2s. 6d.). + +\Item{10.} \textit{The Diseases of the Will.} By \textsc{Th.\ Ribot.} 25c (1s.\ 6d.). + +\Item{11.} \textit{The Origin of Language.} By \textsc{Ludwig Noire.} 15c (9d.). + +\Item{12.} \textit{The Free Trade Struggle in England.} By \textsc{M. M. Trumbull.} 25c (1s.\ 6d.) + +\Item{13.} \textit{Wheelbarrow on the Labor Question.} By \textsc{M. M. Trumbull.} 35c (2s.). + +\Item{14.} \textit{The Gospel of Buddha.} By \textsc{Paul Carus.} 35c (2s.). + +\Item{15.} \textit{The Primer of Philosophy.} By \textsc{Paul Carus.} 25c (1s.\ 6d.). + +\Item{16.} \textit{On Memory, and The Specific Energies of the Nervous System.} By \textsc{Prof.\ +Ewald Hering.} 15c (9d.). + +\Item{17.} \textit{The Redemption of the Brahman. Tale of Hindu Life.} By \textsc{Richard +Garbe.} 25c (1s.\ 6d.). + +\Item{18.} \textit{An Examination of Weismannism.} By \textsc{G. J. Romanes.} 35c (2s.). + +\Item{19.} \textit{On Germinal Selection.} By \textsc{August Weismann.} 25c (1s.\ 6d.). + +\Item{20.} \textit{Lovers Three Thousand Years Ago.} By \textsc{T. A. Goodwin.} (Out of print.) + +\Item{21.} \textit{Popular Scientific Lectures.} By \textsc{Ernst Mach.} 50c (2s.\ 6d.). + +\Item{22.} \textit{Ancient India: Its Language and Religions.} By \textsc{H. Oldenberg.} 25c +(1s.\ 6d.). + +\Item{23.} \textit{The Prophets of Israel.} By \textsc{Prof.\ C. H. Cornill.} 25c (1\Add{s}.\ 6d.). + +\Item{24.} \textit{Homilies of Science.} By \textsc{Paul Carus.} 35c (2s.). + +\Item{25.} \textit{Thoughts on Religion.} By \textsc{G. J. Romanes.} 50c (2s.\ 6d.). + +\Item{26.} \textit{The Philosophy of Ancient India.} By \textsc{Prof.\ Richard Garbe.} 25c (1s.\ 6d.) + +\Item{27.} \textit{Martin Luther.} By \textsc{Gustav Freytag.} 25c (1s.\ 6d.). + +\Item{28.} \textit{English Secularism.} By \textsc{George Jacob Holyoake.} 25c (1s.\ 6d.). + +\Item{29.} \textit{On Orthogenesis.} By \textsc{Th.\ Eimer.} 25c (1s.\ 6d.). + +\Item{30.} \textit{Chinese Philosophy.} By \textsc{Paul Carus.} 25c (1s.\ 6d.). + +\Item{31.} \textit{The Lost Manuscript.} By \textsc{Gustav Freytag.} 60c (35.). + +\Item{32.} \textit{A Mechanico-Physiological Theory of Organic Evolution.} By \textsc{Carl von +Naegeli.} 15c (9d.). + +\Item{33.} \textit{Chinese Fiction.} By \textsc{Dr.\ George T. Candlin.} 15c (9d.). + +\Item{34.} \textit{Mathematical Essays and Recreations.} By \textsc{H. Schubert.} 25c (1s.\ 6d.) + +\Item{35.} \textit{The Ethical Problem.} By \textsc{Paul Carus.} 50c (2s.\ 6d.). + +\Item{36.} \textit{Buddhism and Its Christian Critics.} By \textsc{Paul Carus.} 50c (2s.\ 6d.). + +\Item{37.} \textit{Psychology for Beginners.} By \textsc{Hiram M. Stanley.} 20c (1s.). + +\Item{38.} \textit{Discourse on Method.} By \textsc{Descartes.} 25c (1s.\ 6d.). + +\Item{39.} \textit{The Dawn of a New Era.} By \textsc{Paul Carus.} 15c (9d.). + +\Item{40.} \textit{Kant and Spencer.} By \textsc{Paul Carus.} 20c (1s.). + +\Item{41.} \textit{The Soul of Man.} By \textsc{Paul Carus.} 75c (3s.\ 6d.). + +\Item{42.} \textit{World' s Congress Addresses.} By \textsc{C. C. Bonney.} 15c (9d.). + +\Item{43.} \textit{The Gospel According to Darwin.} By \textsc{Woods Hutchinson.} 50c (2s.\ 6d.) + +\Item{44.} \textit{Whence and Whither.} By \textsc{Paul Carus.} 25c (1s.\ 6d.). + +\Item{45.} \textit{Enquiry Concerning Human Understanding.} By \textsc{David Hume.} 25c +(1s.\ 6d.). + +\Item{46.} \textit{Enquiry Concerning the Principles of Morals.} By \textsc{David Hume.} +25c (1s.\ 6d.) + +\normalsize +\tb +\vfill +\begin{center} +\makebox[\textwidth][s]{\Large THE OPEN COURT PUBLISHING CO.,} \\[4pt] +\normalsize CHICAGO: 324 \textsc{Dearborn Street.} \\[4pt] +\footnotesize \textsc{London}: Kegan Paul, Trench, Trübner \&~Company, Ltd. +\end{center} +%%%%%%%%%%%%%%%%%%%%%%%%% GUTENBERG LICENSE %%%%%%%%%%%%%%%%%%%%%%%%%% +\PGLicense +\begin{PGtext} +End of the Project Gutenberg EBook of Lectures on Elementary Mathematics, by +Joseph Louis Lagrange + +*** END OF THIS PROJECT GUTENBERG EBOOK LECTURES ON ELEMENTARY MATHEMATICS *** + +***** This file should be named 36640-pdf.pdf or 36640-pdf.zip ***** +This and all associated files of various formats will be found in: + http://www.gutenberg.org/3/6/6/4/36640/ + +Produced by Andrew D. Hwang. + +Updated editions will replace the previous one--the old editions +will be renamed. + +Creating the works from public domain print editions means that no +one owns a United States copyright in these works, so the Foundation +(and you!) can copy and distribute it in the United States without +permission and without paying copyright royalties. Special rules, +set forth in the General Terms of Use part of this license, apply to +copying and distributing Project Gutenberg-tm electronic works to +protect the PROJECT GUTENBERG-tm concept and trademark. Project +Gutenberg is a registered trademark, and may not be used if you +charge for the eBooks, unless you receive specific permission. If you +do not charge anything for copies of this eBook, complying with the +rules is very easy. You may use this eBook for nearly any purpose +such as creation of derivative works, reports, performances and +research. They may be modified and printed and given away--you may do +practically ANYTHING with public domain eBooks. Redistribution is +subject to the trademark license, especially commercial +redistribution. + + + +*** START: FULL LICENSE *** + +THE FULL PROJECT GUTENBERG LICENSE +PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK + +To protect the Project Gutenberg-tm mission of promoting the free +distribution of electronic works, by using or distributing this work +(or any other work associated in any way with the phrase "Project +Gutenberg"), you agree to comply with all the terms of the Full Project +Gutenberg-tm License (available with this file or online at +http://gutenberg.org/license). + + +Section 1. General Terms of Use and Redistributing Project Gutenberg-tm +electronic works + +1.A. By reading or using any part of this Project Gutenberg-tm +electronic work, you indicate that you have read, understand, agree to +and accept all the terms of this license and intellectual property +(trademark/copyright) agreement. If you do not agree to abide by all +the terms of this agreement, you must cease using and return or destroy +all copies of Project Gutenberg-tm electronic works in your possession. +If you paid a fee for obtaining a copy of or access to a Project +Gutenberg-tm electronic work and you do not agree to be bound by the +terms of this agreement, you may obtain a refund from the person or +entity to whom you paid the fee as set forth in paragraph 1.E.8. + +1.B. "Project Gutenberg" is a registered trademark. It may only be +used on or associated in any way with an electronic work by people who +agree to be bound by the terms of this agreement. There are a few +things that you can do with most Project Gutenberg-tm electronic works +even without complying with the full terms of this agreement. See +paragraph 1.C below. There are a lot of things you can do with Project +Gutenberg-tm electronic works if you follow the terms of this agreement +and help preserve free future access to Project Gutenberg-tm electronic +works. See paragraph 1.E below. + +1.C. The Project Gutenberg Literary Archive Foundation ("the Foundation" +or PGLAF), owns a compilation copyright in the collection of Project +Gutenberg-tm electronic works. Nearly all the individual works in the +collection are in the public domain in the United States. If an +individual work is in the public domain in the United States and you are +located in the United States, we do not claim a right to prevent you from +copying, distributing, performing, displaying or creating derivative +works based on the work as long as all references to Project Gutenberg +are removed. Of course, we hope that you will support the Project +Gutenberg-tm mission of promoting free access to electronic works by +freely sharing Project Gutenberg-tm works in compliance with the terms of +this agreement for keeping the Project Gutenberg-tm name associated with +the work. You can easily comply with the terms of this agreement by +keeping this work in the same format with its attached full Project +Gutenberg-tm License when you share it without charge with others. + +1.D. The copyright laws of the place where you are located also govern +what you can do with this work. Copyright laws in most countries are in +a constant state of change. If you are outside the United States, check +the laws of your country in addition to the terms of this agreement +before downloading, copying, displaying, performing, distributing or +creating derivative works based on this work or any other Project +Gutenberg-tm work. The Foundation makes no representations concerning +the copyright status of any work in any country outside the United +States. + +1.E. Unless you have removed all references to Project Gutenberg: + +1.E.1. The following sentence, with active links to, or other immediate +access to, the full Project Gutenberg-tm License must appear prominently +whenever any copy of a Project Gutenberg-tm work (any work on which the +phrase "Project Gutenberg" appears, or with which the phrase "Project +Gutenberg" is associated) is accessed, displayed, performed, viewed, +copied or distributed: + +This eBook is for the use of anyone anywhere at no cost and with +almost no restrictions whatsoever. You may copy it, give it away or +re-use it under the terms of the Project Gutenberg License included +with this eBook or online at www.gutenberg.org + +1.E.2. If an individual Project Gutenberg-tm electronic work is derived +from the public domain (does not contain a notice indicating that it is +posted with permission of the copyright holder), the work can be copied +and distributed to anyone in the United States without paying any fees +or charges. If you are redistributing or providing access to a work +with the phrase "Project Gutenberg" associated with or appearing on the +work, you must comply either with the requirements of paragraphs 1.E.1 +through 1.E.7 or obtain permission for the use of the work and the +Project Gutenberg-tm trademark as set forth in paragraphs 1.E.8 or +1.E.9. + +1.E.3. If an individual Project Gutenberg-tm electronic work is posted +with the permission of the copyright holder, your use and distribution +must comply with both paragraphs 1.E.1 through 1.E.7 and any additional +terms imposed by the copyright holder. Additional terms will be linked +to the Project Gutenberg-tm License for all works posted with the +permission of the copyright holder found at the beginning of this work. + +1.E.4. Do not unlink or detach or remove the full Project Gutenberg-tm +License terms from this work, or any files containing a part of this +work or any other work associated with Project Gutenberg-tm. + +1.E.5. Do not copy, display, perform, distribute or redistribute this +electronic work, or any part of this electronic work, without +prominently displaying the sentence set forth in paragraph 1.E.1 with +active links or immediate access to the full terms of the Project +Gutenberg-tm License. + +1.E.6. You may convert to and distribute this work in any binary, +compressed, marked up, nonproprietary or proprietary form, including any +word processing or hypertext form. However, if you provide access to or +distribute copies of a Project Gutenberg-tm work in a format other than +"Plain Vanilla ASCII" or other format used in the official version +posted on the official Project Gutenberg-tm web site (www.gutenberg.org), +you must, at no additional cost, fee or expense to the user, provide a +copy, a means of exporting a copy, or a means of obtaining a copy upon +request, of the work in its original "Plain Vanilla ASCII" or other +form. Any alternate format must include the full Project Gutenberg-tm +License as specified in paragraph 1.E.1. + +1.E.7. Do not charge a fee for access to, viewing, displaying, +performing, copying or distributing any Project Gutenberg-tm works +unless you comply with paragraph 1.E.8 or 1.E.9. + +1.E.8. You may charge a reasonable fee for copies of or providing +access to or distributing Project Gutenberg-tm electronic works provided +that + +- You pay a royalty fee of 20% of the gross profits you derive from + the use of Project Gutenberg-tm works calculated using the method + you already use to calculate your applicable taxes. The fee is + owed to the owner of the Project Gutenberg-tm trademark, but he + has agreed to donate royalties under this paragraph to the + Project Gutenberg Literary Archive Foundation. Royalty payments + must be paid within 60 days following each date on which you + prepare (or are legally required to prepare) your periodic tax + returns. Royalty payments should be clearly marked as such and + sent to the Project Gutenberg Literary Archive Foundation at the + address specified in Section 4, "Information about donations to + the Project Gutenberg Literary Archive Foundation." + +- You provide a full refund of any money paid by a user who notifies + you in writing (or by e-mail) within 30 days of receipt that s/he + does not agree to the terms of the full Project Gutenberg-tm + License. You must require such a user to return or + destroy all copies of the works possessed in a physical medium + and discontinue all use of and all access to other copies of + Project Gutenberg-tm works. + +- You provide, in accordance with paragraph 1.F.3, a full refund of any + money paid for a work or a replacement copy, if a defect in the + electronic work is discovered and reported to you within 90 days + of receipt of the work. + +- You comply with all other terms of this agreement for free + distribution of Project Gutenberg-tm works. + +1.E.9. If you wish to charge a fee or distribute a Project Gutenberg-tm +electronic work or group of works on different terms than are set +forth in this agreement, you must obtain permission in writing from +both the Project Gutenberg Literary Archive Foundation and Michael +Hart, the owner of the Project Gutenberg-tm trademark. Contact the +Foundation as set forth in Section 3 below. + +1.F. + +1.F.1. Project Gutenberg volunteers and employees expend considerable +effort to identify, do copyright research on, transcribe and proofread +public domain works in creating the Project Gutenberg-tm +collection. Despite these efforts, Project Gutenberg-tm electronic +works, and the medium on which they may be stored, may contain +"Defects," such as, but not limited to, incomplete, inaccurate or +corrupt data, transcription errors, a copyright or other intellectual +property infringement, a defective or damaged disk or other medium, a +computer virus, or computer codes that damage or cannot be read by +your equipment. + +1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the "Right +of Replacement or Refund" described in paragraph 1.F.3, the Project +Gutenberg Literary Archive Foundation, the owner of the Project +Gutenberg-tm trademark, and any other party distributing a Project +Gutenberg-tm electronic work under this agreement, disclaim all +liability to you for damages, costs and expenses, including legal +fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT +LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE +PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE +TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE +LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR +INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH +DAMAGE. + +1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a +defect in this electronic work within 90 days of receiving it, you can +receive a refund of the money (if any) you paid for it by sending a +written explanation to the person you received the work from. If you +received the work on a physical medium, you must return the medium with +your written explanation. The person or entity that provided you with +the defective work may elect to provide a replacement copy in lieu of a +refund. If you received the work electronically, the person or entity +providing it to you may choose to give you a second opportunity to +receive the work electronically in lieu of a refund. If the second copy +is also defective, you may demand a refund in writing without further +opportunities to fix the problem. + +1.F.4. Except for the limited right of replacement or refund set forth +in paragraph 1.F.3, this work is provided to you 'AS-IS' WITH NO OTHER +WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +WARRANTIES OF MERCHANTIBILITY OR FITNESS FOR ANY PURPOSE. + +1.F.5. Some states do not allow disclaimers of certain implied +warranties or the exclusion or limitation of certain types of damages. +If any disclaimer or limitation set forth in this agreement violates the +law of the state applicable to this agreement, the agreement shall be +interpreted to make the maximum disclaimer or limitation permitted by +the applicable state law. The invalidity or unenforceability of any +provision of this agreement shall not void the remaining provisions. + +1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the +trademark owner, any agent or employee of the Foundation, anyone +providing copies of Project Gutenberg-tm electronic works in accordance +with this agreement, and any volunteers associated with the production, +promotion and distribution of Project Gutenberg-tm electronic works, +harmless from all liability, costs and expenses, including legal fees, +that arise directly or indirectly from any of the following which you do +or cause to occur: (a) distribution of this or any Project Gutenberg-tm +work, (b) alteration, modification, or additions or deletions to any +Project Gutenberg-tm work, and (c) any Defect you cause. + + +Section 2. Information about the Mission of Project Gutenberg-tm + +Project Gutenberg-tm is synonymous with the free distribution of +electronic works in formats readable by the widest variety of computers +including obsolete, old, middle-aged and new computers. It exists +because of the efforts of hundreds of volunteers and donations from +people in all walks of life. + +Volunteers and financial support to provide volunteers with the +assistance they need, are critical to reaching Project Gutenberg-tm's +goals and ensuring that the Project Gutenberg-tm collection will +remain freely available for generations to come. In 2001, the Project +Gutenberg Literary Archive Foundation was created to provide a secure +and permanent future for Project Gutenberg-tm and future generations. +To learn more about the Project Gutenberg Literary Archive Foundation +and how your efforts and donations can help, see Sections 3 and 4 +and the Foundation web page at http://www.pglaf.org. + + +Section 3. Information about the Project Gutenberg Literary Archive +Foundation + +The Project Gutenberg Literary Archive Foundation is a non profit +501(c)(3) educational corporation organized under the laws of the +state of Mississippi and granted tax exempt status by the Internal +Revenue Service. The Foundation's EIN or federal tax identification +number is 64-6221541. Its 501(c)(3) letter is posted at +http://pglaf.org/fundraising. Contributions to the Project Gutenberg +Literary Archive Foundation are tax deductible to the full extent +permitted by U.S. federal laws and your state's laws. + +The Foundation's principal office is located at 4557 Melan Dr. S. +Fairbanks, AK, 99712., but its volunteers and employees are scattered +throughout numerous locations. Its business office is located at +809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887, email +business@pglaf.org. Email contact links and up to date contact +information can be found at the Foundation's web site and official +page at http://pglaf.org + +For additional contact information: + Dr. Gregory B. Newby + Chief Executive and Director + gbnewby@pglaf.org + + +Section 4. Information about Donations to the Project Gutenberg +Literary Archive Foundation + +Project Gutenberg-tm depends upon and cannot survive without wide +spread public support and donations to carry out its mission of +increasing the number of public domain and licensed works that can be +freely distributed in machine readable form accessible by the widest +array of equipment including outdated equipment. Many small donations +($1 to $5,000) are particularly important to maintaining tax exempt +status with the IRS. + +The Foundation is committed to complying with the laws regulating +charities and charitable donations in all 50 states of the United +States. Compliance requirements are not uniform and it takes a +considerable effort, much paperwork and many fees to meet and keep up +with these requirements. We do not solicit donations in locations +where we have not received written confirmation of compliance. To +SEND DONATIONS or determine the status of compliance for any +particular state visit http://pglaf.org + +While we cannot and do not solicit contributions from states where we +have not met the solicitation requirements, we know of no prohibition +against accepting unsolicited donations from donors in such states who +approach us with offers to donate. + +International donations are gratefully accepted, but we cannot make +any statements concerning tax treatment of donations received from +outside the United States. U.S. laws alone swamp our small staff. + +Please check the Project Gutenberg Web pages for current donation +methods and addresses. Donations are accepted in a number of other +ways including checks, online payments and credit card donations. +To donate, please visit: http://pglaf.org/donate + + +Section 5. General Information About Project Gutenberg-tm electronic +works. + +Professor Michael S. Hart is the originator of the Project Gutenberg-tm +concept of a library of electronic works that could be freely shared +with anyone. For thirty years, he produced and distributed Project +Gutenberg-tm eBooks with only a loose network of volunteer support. + + +Project Gutenberg-tm eBooks are often created from several printed +editions, all of which are confirmed as Public Domain in the U.S. +unless a copyright notice is included. Thus, we do not necessarily +keep eBooks in compliance with any particular paper edition. + + +Most people start at our Web site which has the main PG search facility: + + http://www.gutenberg.org + +This Web site includes information about Project Gutenberg-tm, +including how to make donations to the Project Gutenberg Literary +Archive Foundation, how to help produce our new eBooks, and how to +subscribe to our email newsletter to hear about new eBooks. +\end{PGtext} + +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % +% % +% End of the Project Gutenberg EBook of Lectures on Elementary Mathematics, by +% Joseph Louis Lagrange % +% % +% *** END OF THIS PROJECT GUTENBERG EBOOK LECTURES ON ELEMENTARY MATHEMATICS *** +% % +% ***** This file should be named 36640-t.tex or 36640-t.zip ***** % +% This and all associated files of various formats will be found in: % +% http://www.gutenberg.org/3/6/6/4/36640/ % +% % +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % + +\end{document} +### +@ControlwordReplace = ( + ['\\Preface', 'Preface'], + ['\\Frontispiece', ''], + ['\\Catalog', 'Catalogue of Publications\\nof the\\nOpen Court Publishing Co.'], + ['\\end{Author}', ''], + ['\\tb', '-----'], + ['\\stars', '* * *'], + ['\\ieme', '^{me}'], + ); + +@ControlwordArguments = ( + ['\\SetRunningHeads', 1, 0, '', ''], + ['\\BookMark', 1, 0, '', '', 1, 0, '', ''], + ['\\Lecture', 0, 0, '', '', 1, 1, 'Lecture ', '', 1, 1, ' ', ''], + ['\\SectTitle', 1, 1, '', ''], + ['\\MNote', 1, 0, '', ''], + ['\\index', 1, 0, '', ''], + ['\\Appendix', 1, 1, '', ''], + ['\\BioSketch', 1, 1, '', '', 1, 1, ' ', ''], + ['\\Signature', 1, 1, '', ' ', 1, 1, '', ''], + ['\\FrontCatalog', 1, 1, '', ''], + ['\\Book', 1, 1, '', ''], + ['\\Title', 0, 0, '', '', 1, 1, '', ' ', 1, 1, '', ''], + ['\\begin{Author}', 1, 1, '', ''], + ['\\Item', 1, 1, '', ''], + ['\\Typo', 1, 0, '', '', 1, 1, '', ''], + ['\\Add', 1, 1, '', ''], + ['\\PageSep', 1, 1, '%%-- Page [', ']'], + ['\\Figure', 1, 1, '
', 1, 0, '', ''], + ['\\First', 1, 1, '', ''] + ); +### +This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) (format=pdflatex 2010.5.6) 6 JUL 2011 08:11 +entering extended mode + %&-line parsing enabled. +**36640-t.tex +(./36640-t.tex +LaTeX2e <2005/12/01> +Babel and hyphenation patterns for english, usenglishmax, dumylang, noh +yphenation, arabic, farsi, croatian, ukrainian, russian, bulgarian, czech, slov +ak, danish, dutch, finnish, basque, french, german, ngerman, ibycus, greek, mon +ogreek, ancientgreek, hungarian, italian, latin, mongolian, norsk, icelandic, i +nterlingua, turkish, coptic, romanian, welsh, serbian, slovenian, estonian, esp +eranto, uppersorbian, indonesian, polish, portuguese, spanish, catalan, galicia +n, swedish, ukenglish, pinyin, loaded. +(/usr/share/texmf-texlive/tex/latex/base/book.cls +Document Class: book 2005/09/16 v1.4f Standard LaTeX document class +(/usr/share/texmf-texlive/tex/latex/base/bk12.clo +File: bk12.clo 2005/09/16 v1.4f Standard LaTeX file (size option) +) +\c@part=\count79 +\c@chapter=\count80 +\c@section=\count81 +\c@subsection=\count82 +\c@subsubsection=\count83 +\c@paragraph=\count84 +\c@subparagraph=\count85 +\c@figure=\count86 +\c@table=\count87 +\abovecaptionskip=\skip41 +\belowcaptionskip=\skip42 +\bibindent=\dimen102 +) (/usr/share/texmf-texlive/tex/latex/base/inputenc.sty +Package: inputenc 2006/05/05 v1.1b Input encoding file +\inpenc@prehook=\toks14 +\inpenc@posthook=\toks15 +(/usr/share/texmf-texlive/tex/latex/base/latin1.def +File: latin1.def 2006/05/05 v1.1b Input encoding file +)) (/usr/share/texmf-texlive/tex/generic/babel/babel.sty +Package: babel 2005/11/23 v3.8h The Babel package +(/usr/share/texmf-texlive/tex/generic/babel/greek.ldf +Language: greek 2005/03/30 v1.3l Greek support from the babel system +(/usr/share/texmf-texlive/tex/generic/babel/babel.def +File: babel.def 2005/11/23 v3.8h Babel common definitions +\babel@savecnt=\count88 +\U@D=\dimen103 +) Loading the definitions for the Greek font encoding (/usr/share/texmf-texlive +/tex/generic/babel/lgrenc.def +File: lgrenc.def 2001/01/30 v2.2e Greek Encoding +)) (/usr/share/texmf-texlive/tex/generic/babel/english.ldf +Language: english 2005/03/30 v3.3o English support from the babel system +\l@british = a dialect from \language\l@english +\l@UKenglish = a dialect from \language\l@english +\l@canadian = a dialect from \language\l@american +\l@australian = a dialect from \language\l@british +\l@newzealand = a dialect from \language\l@british +)) (/usr/share/texmf-texlive/tex/latex/base/ifthen.sty +Package: ifthen 2001/05/26 v1.1c Standard LaTeX ifthen package (DPC) +) (/usr/share/texmf-texlive/tex/latex/amsmath/amsmath.sty +Package: amsmath 2000/07/18 v2.13 AMS math features +\@mathmargin=\skip43 +For additional information on amsmath, use the `?' option. +(/usr/share/texmf-texlive/tex/latex/amsmath/amstext.sty +Package: amstext 2000/06/29 v2.01 +(/usr/share/texmf-texlive/tex/latex/amsmath/amsgen.sty +File: amsgen.sty 1999/11/30 v2.0 +\@emptytoks=\toks16 +\ex@=\dimen104 +)) (/usr/share/texmf-texlive/tex/latex/amsmath/amsbsy.sty +Package: amsbsy 1999/11/29 v1.2d +\pmbraise@=\dimen105 +) (/usr/share/texmf-texlive/tex/latex/amsmath/amsopn.sty +Package: amsopn 1999/12/14 v2.01 operator names +) +\inf@bad=\count89 +LaTeX Info: Redefining \frac on input line 211. +\uproot@=\count90 +\leftroot@=\count91 +LaTeX Info: Redefining \overline on input line 307. +\classnum@=\count92 +\DOTSCASE@=\count93 +LaTeX Info: Redefining \ldots on input line 379. +LaTeX Info: Redefining \dots on input line 382. +LaTeX Info: Redefining \cdots on input line 467. +\Mathstrutbox@=\box26 +\strutbox@=\box27 +\big@size=\dimen106 +LaTeX Font Info: Redeclaring font encoding OML on input line 567. +LaTeX Font Info: Redeclaring font encoding OMS on input line 568. +\macc@depth=\count94 +\c@MaxMatrixCols=\count95 +\dotsspace@=\muskip10 +\c@parentequation=\count96 +\dspbrk@lvl=\count97 +\tag@help=\toks17 +\row@=\count98 +\column@=\count99 +\maxfields@=\count100 +\andhelp@=\toks18 +\eqnshift@=\dimen107 +\alignsep@=\dimen108 +\tagshift@=\dimen109 +\tagwidth@=\dimen110 +\totwidth@=\dimen111 +\lineht@=\dimen112 +\@envbody=\toks19 +\multlinegap=\skip44 +\multlinetaggap=\skip45 +\mathdisplay@stack=\toks20 +LaTeX Info: Redefining \[ on input line 2666. +LaTeX Info: Redefining \] on input line 2667. +) (/usr/share/texmf-texlive/tex/latex/amsfonts/amssymb.sty +Package: amssymb 2002/01/22 v2.2d +(/usr/share/texmf-texlive/tex/latex/amsfonts/amsfonts.sty +Package: amsfonts 2001/10/25 v2.2f +\symAMSa=\mathgroup4 +\symAMSb=\mathgroup5 +LaTeX Font Info: Overwriting math alphabet `\mathfrak' in version `bold' +(Font) U/euf/m/n --> U/euf/b/n on input line 132. +)) (/usr/share/texmf-texlive/tex/latex/base/alltt.sty +Package: alltt 1997/06/16 v2.0g defines alltt environment +) (/usr/share/texmf-texlive/tex/latex/tools/array.sty +Package: array 2005/08/23 v2.4b Tabular extension package (FMi) +\col@sep=\dimen113 +\extrarowheight=\dimen114 +\NC@list=\toks21 +\extratabsurround=\skip46 +\backup@length=\skip47 +) (/usr/share/texmf-texlive/tex/latex/footmisc/footmisc.sty +Package: footmisc 2005/03/17 v5.3d a miscellany of footnote facilities +\FN@temptoken=\toks22 +\footnotemargin=\dimen115 +\c@pp@next@reset=\count101 +\c@@fnserial=\count102 +Package footmisc Info: Declaring symbol style bringhurst on input line 817. +Package footmisc Info: Declaring symbol style chicago on input line 818. +Package footmisc Info: Declaring symbol style wiley on input line 819. +Package footmisc Info: Declaring symbol style lamport-robust on input line 823. + +Package footmisc Info: Declaring symbol style lamport* on input line 831. +Package footmisc Info: Declaring symbol style lamport*-robust on input line 840 +. +) (/usr/share/texmf-texlive/tex/latex/tools/multicol.sty +Package: multicol 2006/05/18 v1.6g multicolumn formatting (FMi) +\c@tracingmulticols=\count103 +\mult@box=\box28 +\multicol@leftmargin=\dimen116 +\c@unbalance=\count104 +\c@collectmore=\count105 +\doublecol@number=\count106 +\multicoltolerance=\count107 +\multicolpretolerance=\count108 +\full@width=\dimen117 +\page@free=\dimen118 +\premulticols=\dimen119 +\postmulticols=\dimen120 +\multicolsep=\skip48 +\multicolbaselineskip=\skip49 +\partial@page=\box29 +\last@line=\box30 +\mult@rightbox=\box31 +\mult@grightbox=\box32 +\mult@gfirstbox=\box33 +\mult@firstbox=\box34 +\@tempa=\box35 +\@tempa=\box36 +\@tempa=\box37 +\@tempa=\box38 +\@tempa=\box39 +\@tempa=\box40 +\@tempa=\box41 +\@tempa=\box42 +\@tempa=\box43 +\@tempa=\box44 +\@tempa=\box45 +\@tempa=\box46 +\@tempa=\box47 +\@tempa=\box48 +\@tempa=\box49 +\@tempa=\box50 +\@tempa=\box51 +\c@columnbadness=\count109 +\c@finalcolumnbadness=\count110 +\last@try=\dimen121 +\multicolovershoot=\dimen122 +\multicolundershoot=\dimen123 +\mult@nat@firstbox=\box52 +\colbreak@box=\box53 +) (/usr/share/texmf-texlive/tex/latex/base/makeidx.sty +Package: makeidx 2000/03/29 v1.0m Standard LaTeX package +) (/usr/share/texmf-texlive/tex/latex/caption/caption.sty +Package: caption 2007/01/07 v3.0k Customising captions (AR) +(/usr/share/texmf-texlive/tex/latex/caption/caption3.sty +Package: caption3 2007/01/07 v3.0k caption3 kernel (AR) +(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty +Package: keyval 1999/03/16 v1.13 key=value parser (DPC) +\KV@toks@=\toks23 +) +\captionmargin=\dimen124 +\captionmarginx=\dimen125 +\captionwidth=\dimen126 +\captionindent=\dimen127 +\captionparindent=\dimen128 +\captionhangindent=\dimen129 +)) (/usr/share/texmf-texlive/tex/latex/graphics/graphicx.sty +Package: graphicx 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR) +(/usr/share/texmf-texlive/tex/latex/graphics/graphics.sty +Package: graphics 2006/02/20 v1.0o Standard LaTeX Graphics (DPC,SPQR) +(/usr/share/texmf-texlive/tex/latex/graphics/trig.sty +Package: trig 1999/03/16 v1.09 sin cos tan (DPC) +) (/etc/texmf/tex/latex/config/graphics.cfg +File: graphics.cfg 2007/01/18 v1.5 graphics configuration of teTeX/TeXLive +) +Package graphics Info: Driver file: pdftex.def on input line 90. +(/usr/share/texmf-texlive/tex/latex/pdftex-def/pdftex.def +File: pdftex.def 2007/01/08 v0.04d Graphics/color for pdfTeX +\Gread@gobject=\count111 +)) +\Gin@req@height=\dimen130 +\Gin@req@width=\dimen131 +) (/usr/share/texmf-texlive/tex/latex/tools/calc.sty +Package: calc 2005/08/06 v4.2 Infix arithmetic (KKT,FJ) +\calc@Acount=\count112 +\calc@Bcount=\count113 +\calc@Adimen=\dimen132 +\calc@Bdimen=\dimen133 +\calc@Askip=\skip50 +\calc@Bskip=\skip51 +LaTeX Info: Redefining \setlength on input line 75. +LaTeX Info: Redefining \addtolength on input line 76. +\calc@Ccount=\count114 +\calc@Cskip=\skip52 +) (/usr/share/texmf-texlive/tex/latex/fancyhdr/fancyhdr.sty +\fancy@headwidth=\skip53 +\f@ncyO@elh=\skip54 +\f@ncyO@erh=\skip55 +\f@ncyO@olh=\skip56 +\f@ncyO@orh=\skip57 +\f@ncyO@elf=\skip58 +\f@ncyO@erf=\skip59 +\f@ncyO@olf=\skip60 +\f@ncyO@orf=\skip61 +) (/usr/share/texmf-texlive/tex/latex/geometry/geometry.sty +Package: geometry 2002/07/08 v3.2 Page Geometry +\Gm@cnth=\count115 +\Gm@cntv=\count116 +\c@Gm@tempcnt=\count117 +\Gm@bindingoffset=\dimen134 +\Gm@wd@mp=\dimen135 +\Gm@odd@mp=\dimen136 +\Gm@even@mp=\dimen137 +\Gm@dimlist=\toks24 +(/usr/share/texmf-texlive/tex/xelatex/xetexconfig/geometry.cfg)) (/usr/share/te +xmf-texlive/tex/latex/hyperref/hyperref.sty +Package: hyperref 2007/02/07 v6.75r Hypertext links for LaTeX +\@linkdim=\dimen138 +\Hy@linkcounter=\count118 +\Hy@pagecounter=\count119 +(/usr/share/texmf-texlive/tex/latex/hyperref/pd1enc.def +File: pd1enc.def 2007/02/07 v6.75r Hyperref: PDFDocEncoding definition (HO) +) (/etc/texmf/tex/latex/config/hyperref.cfg +File: hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive +) (/usr/share/texmf-texlive/tex/latex/oberdiek/kvoptions.sty +Package: kvoptions 2006/08/22 v2.4 Connects package keyval with LaTeX options ( +HO) +) +Package hyperref Info: Option `hyperfootnotes' set `false' on input line 2238. +Package hyperref Info: Option `bookmarks' set `true' on input line 2238. +Package hyperref Info: Option `linktocpage' set `false' on input line 2238. +Package hyperref Info: Option `pdfdisplaydoctitle' set `true' on input line 223 +8. +Package hyperref Info: Option `pdfpagelabels' set `true' on input line 2238. +Package hyperref Info: Option `bookmarksopen' set `true' on input line 2238. +Package hyperref Info: Option `colorlinks' set `true' on input line 2238. +Package hyperref Info: Hyper figures OFF on input line 2288. +Package hyperref Info: Link nesting OFF on input line 2293. +Package hyperref Info: Hyper index ON on input line 2296. +Package hyperref Info: Plain pages OFF on input line 2303. +Package hyperref Info: Backreferencing OFF on input line 2308. +Implicit mode ON; LaTeX internals redefined +Package hyperref Info: Bookmarks ON on input line 2444. +(/usr/share/texmf-texlive/tex/latex/ltxmisc/url.sty +\Urlmuskip=\muskip11 +Package: url 2005/06/27 ver 3.2 Verb mode for urls, etc. +) +LaTeX Info: Redefining \url on input line 2599. +\Fld@menulength=\count120 +\Field@Width=\dimen139 +\Fld@charsize=\dimen140 +\Choice@toks=\toks25 +\Field@toks=\toks26 +Package hyperref Info: Hyper figures OFF on input line 3102. +Package hyperref Info: Link nesting OFF on input line 3107. +Package hyperref Info: Hyper index ON on input line 3110. +Package hyperref Info: backreferencing OFF on input line 3117. +Package hyperref Info: Link coloring ON on input line 3120. +\Hy@abspage=\count121 +\c@Item=\count122 +) +*hyperref using driver hpdftex* +(/usr/share/texmf-texlive/tex/latex/hyperref/hpdftex.def +File: hpdftex.def 2007/02/07 v6.75r Hyperref driver for pdfTeX +\Fld@listcount=\count123 +) +\TmpLen=\skip62 +\@indexfile=\write3 +\openout3 = `36640-t.idx'. + +Writing index file 36640-t.idx +\c@MNote=\count124 +(./36640-t.aux) +\openout1 = `36640-t.aux'. + +LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 597. +LaTeX Font Info: ... okay on input line 597. +LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 597. +LaTeX Font Info: ... okay on input line 597. +LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 597. +LaTeX Font Info: ... okay on input line 597. +LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 597. +LaTeX Font Info: ... okay on input line 597. +LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 597. +LaTeX Font Info: ... okay on input line 597. +LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 597. +LaTeX Font Info: ... okay on input line 597. +LaTeX Font Info: Checking defaults for LGR/cmr/m/n on input line 597. +LaTeX Font Info: Try loading font information for LGR+cmr on input line 597. + +(/usr/share/texmf-texlive/tex/generic/babel/lgrcmr.fd +File: lgrcmr.fd 2001/01/30 v2.2e Greek Computer Modern +) +LaTeX Font Info: ... okay on input line 597. +LaTeX Font Info: Checking defaults for PD1/pdf/m/n on input line 597. +LaTeX Font Info: ... okay on input line 597. +(/usr/share/texmf-texlive/tex/latex/ragged2e/ragged2e.sty +Package: ragged2e 2003/03/25 v2.04 ragged2e Package (MS) +(/usr/share/texmf-texlive/tex/latex/everysel/everysel.sty +Package: everysel 1999/06/08 v1.03 EverySelectfont Package (MS) +LaTeX Info: Redefining \selectfont on input line 125. +) +\CenteringLeftskip=\skip63 +\RaggedLeftLeftskip=\skip64 +\RaggedRightLeftskip=\skip65 +\CenteringRightskip=\skip66 +\RaggedLeftRightskip=\skip67 +\RaggedRightRightskip=\skip68 +\CenteringParfillskip=\skip69 +\RaggedLeftParfillskip=\skip70 +\RaggedRightParfillskip=\skip71 +\JustifyingParfillskip=\skip72 +\CenteringParindent=\skip73 +\RaggedLeftParindent=\skip74 +\RaggedRightParindent=\skip75 +\JustifyingParindent=\skip76 +) +Package caption Info: hyperref package v6.74m (or newer) detected on input line + 597. +(/usr/share/texmf/tex/context/base/supp-pdf.tex +[Loading MPS to PDF converter (version 2006.09.02).] +\scratchcounter=\count125 +\scratchdimen=\dimen141 +\scratchbox=\box54 +\nofMPsegments=\count126 +\nofMParguments=\count127 +\everyMPshowfont=\toks27 +\MPscratchCnt=\count128 +\MPscratchDim=\dimen142 +\MPnumerator=\count129 +\everyMPtoPDFconversion=\toks28 +) +-------------------- Geometry parameters +paper: class default +landscape: -- +twocolumn: -- +twoside: true +asymmetric: -- +h-parts: 9.03374pt, 325.215pt, 9.03375pt +v-parts: 4.15848pt, 495.49379pt, 6.23773pt +hmarginratio: 1:1 +vmarginratio: 2:3 +lines: -- +heightrounded: -- +bindingoffset: 0.0pt +truedimen: -- +includehead: true +includefoot: true +includemp: -- +driver: pdftex +-------------------- Page layout dimensions and switches +\paperwidth 343.28249pt +\paperheight 505.89pt +\textwidth 325.215pt +\textheight 433.62pt +\oddsidemargin -63.23625pt +\evensidemargin -63.23624pt +\topmargin -68.11151pt +\headheight 12.0pt +\headsep 19.8738pt +\footskip 30.0pt +\marginparwidth 98.0pt +\marginparsep 7.0pt +\columnsep 10.0pt +\skip\footins 10.8pt plus 4.0pt minus 2.0pt +\hoffset 0.0pt +\voffset 0.0pt +\mag 1000 +\@twosidetrue \@mparswitchtrue +(1in=72.27pt, 1cm=28.45pt) +----------------------- +(/usr/share/texmf-texlive/tex/latex/graphics/color.sty +Package: color 2005/11/14 v1.0j Standard LaTeX Color (DPC) +(/etc/texmf/tex/latex/config/color.cfg +File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive +) +Package color Info: Driver file: pdftex.def on input line 130. +) +Package hyperref Info: Link coloring ON on input line 597. +(/usr/share/texmf-texlive/tex/latex/hyperref/nameref.sty +Package: nameref 2006/12/27 v2.28 Cross-referencing by name of section +(/usr/share/texmf-texlive/tex/latex/oberdiek/refcount.sty +Package: refcount 2006/02/20 v3.0 Data extraction from references (HO) +) +\c@section@level=\count130 +) +LaTeX Info: Redefining \ref on input line 597. +LaTeX Info: Redefining \pageref on input line 597. +(./36640-t.out) (./36640-t.out) +\@outlinefile=\write4 +\openout4 = `36640-t.out'. + + +Overfull \hbox (14.78989pt too wide) in paragraph at lines 625--625 +[]\OT1/cmtt/m/n/8 *** START OF THIS PROJECT GUTENBERG EBOOK LECTURES ON ELEMENT +ARY MATHEMATICS ***[] + [] + +LaTeX Font Info: Try loading font information for U+msa on input line 627. +(/usr/share/texmf-texlive/tex/latex/amsfonts/umsa.fd +File: umsa.fd 2002/01/19 v2.2g AMS font definitions +) +LaTeX Font Info: Try loading font information for U+msb on input line 627. +(/usr/share/texmf-texlive/tex/latex/amsfonts/umsb.fd +File: umsb.fd 2002/01/19 v2.2g AMS font definitions +) [1 + +{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}] [2] [1 + + +] +Underfull \hbox (badness 1097) detected at line 700 +\OT1/cmr/m/n/14.4 THE OPEN COURT PUBLISHING COMPANY + [] + +<./images/lagrange.jpg, id=103, 104.3097pt x 154.176pt> +File: ./images/lagrange.jpg Graphic file (type jpg) + [2] [3 <./images/lagrange.jpg>] [4 + +] [5] [6 + + +] [7] [8 + + +] [9] +Overfull \hbox (0.8094pt too wide) in paragraph at lines 886--900 +[]\OT1/cmr/m/n/12 But it should never be for-got-ten that the mighty stenophren +ic + [] + +[10] [11] [12] [13] [14] [15] (./36640-t.toc [16 + + + +] [17] [18] [19]) +\tf@toc=\write5 +\openout5 = `36640-t.toc'. + +[20] [1 + + + + + +] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] +[19] [20 + + +] [21] [22] [23] [24] [25] [26] [27] [28] [29] [30] [31] [32] [33] [34] [35] [3 +6] [37] [38] [39] [40] [41] [42] [43] [44] [45] [46 + + +] [47] [48] [49] [50] [51] [52] [53] [54] [55] [56] [57] [58] [59] [60] [61] [6 +2] [63] [64] [65] [66] [67] [68] [69] [70] [71] [72] [73] [74] [75] [76] [77] [ +78] [79] [80] [81] [82] [83] [84] [85] [86] [87 + + +] [88] [89] <./images/fig1.png, id=1073, 334.851pt x 172.9662pt> +File: ./images/fig1.png Graphic file (type png) + [90] [91 <./images/fig1.png (PNG copy)>] +File: ./images/fig1.png Graphic file (type png) + [92] [93] [94] [95] [96] [97] [98] [99] [100] [101] [10 +2] [103] [104] [105] [106] [107] [108] [109] [110] <./images/fig2.png, id=1187, + 226.9278pt x 201.8742pt> +File: ./images/fig2.png Graphic file (type png) + [111] [112 <./images/fig2.png (PNG copy)>] [113] [114] +[115 + + +] [116] [117] [118] [119] [120] [121] [122] <./images/fig3.png, id=1254, 169.59 +36pt x 167.6664pt> +File: ./images/fig3.png Graphic file (type png) + [123] <./images/fig4.png, id=1262, 151.767pt x 179.2296 +pt> +File: ./images/fig4.png Graphic file (type png) + [124 <./images/fig3.png (PNG copy)>] [125 <./images/fig +4.png (PNG copy)>] <./images/fig5.png, id=1275, 204.765pt x 182.6022pt> +File: ./images/fig5.png Graphic file (type png) + <./images/fig6.png, id=1276, 187.902pt x 71.3064pt> +File: ./images/fig6.png Graphic file (type png) + [126] [127 <./images/fig5.png (PNG copy)>] [128 <./imag +es/fig6.png (PNG copy)>] [129] [130] [131] [132] [133] [134] [135] [136 + + +] [137] (./36640-t.ind [138 + + + +] [139] [140] [141] [142] [143] [144]) [145 + + + + +] [146] [147] [148] [149] [150] +Underfull \hbox (badness 2726) detected at line 7750 +\OT1/cmr/m/n/17.28 THE OPEN COURT PUBLISHING CO., + [] + +[151] +Overfull \hbox (6.28976pt too wide) in paragraph at lines 7760--7760 +[]\OT1/cmtt/m/n/8 *** END OF THIS PROJECT GUTENBERG EBOOK LECTURES ON ELEMENTAR +Y MATHEMATICS ***[] + [] + +[1 + + +] [2] [3] [4] [5] [6] [7] [8] (./36640-t.aux) + + *File List* + book.cls 2005/09/16 v1.4f Standard LaTeX document class + bk12.clo 2005/09/16 v1.4f Standard LaTeX file (size option) +inputenc.sty 2006/05/05 v1.1b Input encoding file + latin1.def 2006/05/05 v1.1b Input encoding file + babel.sty 2005/11/23 v3.8h The Babel package + greek.ldf 2005/03/30 v1.3l Greek support from the babel system + lgrenc.def 2001/01/30 v2.2e Greek Encoding + english.ldf 2005/03/30 v3.3o English support from the babel system + ifthen.sty 2001/05/26 v1.1c Standard LaTeX ifthen package (DPC) + amsmath.sty 2000/07/18 v2.13 AMS math features + amstext.sty 2000/06/29 v2.01 + amsgen.sty 1999/11/30 v2.0 + amsbsy.sty 1999/11/29 v1.2d + amsopn.sty 1999/12/14 v2.01 operator names + amssymb.sty 2002/01/22 v2.2d +amsfonts.sty 2001/10/25 v2.2f + alltt.sty 1997/06/16 v2.0g defines alltt environment + array.sty 2005/08/23 v2.4b Tabular extension package (FMi) +footmisc.sty 2005/03/17 v5.3d a miscellany of footnote facilities +multicol.sty 2006/05/18 v1.6g multicolumn formatting (FMi) + makeidx.sty 2000/03/29 v1.0m Standard LaTeX package + caption.sty 2007/01/07 v3.0k Customising captions (AR) +caption3.sty 2007/01/07 v3.0k caption3 kernel (AR) + keyval.sty 1999/03/16 v1.13 key=value parser (DPC) +graphicx.sty 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR) +graphics.sty 2006/02/20 v1.0o Standard LaTeX Graphics (DPC,SPQR) + trig.sty 1999/03/16 v1.09 sin cos tan (DPC) +graphics.cfg 2007/01/18 v1.5 graphics configuration of teTeX/TeXLive + pdftex.def 2007/01/08 v0.04d Graphics/color for pdfTeX + calc.sty 2005/08/06 v4.2 Infix arithmetic (KKT,FJ) +fancyhdr.sty +geometry.sty 2002/07/08 v3.2 Page Geometry +geometry.cfg +hyperref.sty 2007/02/07 v6.75r Hypertext links for LaTeX + pd1enc.def 2007/02/07 v6.75r Hyperref: PDFDocEncoding definition (HO) +hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive +kvoptions.sty 2006/08/22 v2.4 Connects package keyval with LaTeX options (HO +) + url.sty 2005/06/27 ver 3.2 Verb mode for urls, etc. + hpdftex.def 2007/02/07 v6.75r Hyperref driver for pdfTeX + lgrcmr.fd 2001/01/30 v2.2e Greek Computer Modern +ragged2e.sty 2003/03/25 v2.04 ragged2e Package (MS) +everysel.sty 1999/06/08 v1.03 EverySelectfont Package (MS) +supp-pdf.tex + color.sty 2005/11/14 v1.0j Standard LaTeX Color (DPC) + color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive + nameref.sty 2006/12/27 v2.28 Cross-referencing by name of section +refcount.sty 2006/02/20 v3.0 Data extraction from references (HO) + 36640-t.out + 36640-t.out + umsa.fd 2002/01/19 v2.2g AMS font definitions + umsb.fd 2002/01/19 v2.2g AMS font definitions +./images/lagrange.jpg +./images/fig1.png +./images/fig1.png +./images/fig2.png +./images/fig3.png +./images/fig4.png +./images/fig5.png +./images/fig6.png + 36640-t.ind + *********** + + ) +Here is how much of TeX's memory you used: + 6322 strings out of 94074 + 84976 string characters out of 1165154 + 165256 words of memory out of 1500000 + 8938 multiletter control sequences out of 10000+50000 + 17173 words of font info for 63 fonts, out of 1200000 for 2000 + 645 hyphenation exceptions out of 8191 + 34i,14n,44p,366b,766s stack positions out of 5000i,500n,6000p,200000b,5000s + +Output written on 36640-t.pdf (181 pages, 892352 bytes). +PDF statistics: + 2007 PDF objects out of 2073 (max. 8388607) + 548 named destinations out of 1000 (max. 131072) + 196 words of extra memory for PDF output out of 10000 (max. 10000000) + diff --git a/latex/math/41568_t_c5dd66.tex b/latex/math/41568_t_c5dd66.tex new file mode 100644 index 0000000..dc4294e --- /dev/null +++ b/latex/math/41568_t_c5dd66.tex @@ -0,0 +1,10694 @@ +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % +% % +% Project Gutenberg's An Introduction to Mathematics, by Alfred North Whitehead +% % +% This eBook is for the use of anyone anywhere at no cost and with % +% almost no restrictions whatsoever. You may copy it, give it away or % +% re-use it under the terms of the Project Gutenberg License included % +% with this eBook or online at www.gutenberg.org % +% % +% % +% Title: An Introduction to Mathematics % +% % +% Author: Alfred North Whitehead % +% % +% Release Date: December 6, 2012 [EBook #41568] % +% Most recently updated: June 11, 2021 % +% % +% Language: English % +% % +% Character set encoding: UTF-8 % +% % +% *** START OF THIS PROJECT GUTENBERG EBOOK AN INTRODUCTION TO MATHEMATICS *** +% % +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % + +\def\ebook{41568} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% %% +%% Packages and substitutions: %% +%% %% +%% book: Required. %% +%% inputenc: Latin-1 text encoding. Required. %% +%% %% +%% ifthen: Logical conditionals. Required. %% +%% %% +%% amsmath: AMS mathematics enhancements. Required. %% +%% amssymb: Additional mathematical symbols. Required. %% +%% %% +%% alltt: Fixed-width font environment. Required. %% +%% %% +%% indentfirst: Indent first paragraph of each section. Optional. %% +%% %% +%% footmisc: Start footnote numbering on each page. Required. %% +%% %% +%% multicol: Multicolumn environment for index. Required. %% +%% makeidx: Index. Required. %% +%% %% +%% graphicx: Standard interface for graphics inclusion. Required. %% +%% caption: Caption customization. Required. %% +%% %% +%% calc: Length calculations. Required. %% +%% %% +%% fancyhdr: Enhanced running headers and footers. Required. %% +%% %% +%% geometry: Enhanced page layout package. Required. %% +%% hyperref: Hypertext embellishments for pdf output. Required. %% +%% %% +%% %% +%% Producer's Comments: %% +%% %% +%% OCR text for this ebook was obtained on Nov. 24, 2012, from %% +%% http://archive.org/details/introductiontoma00whitiala. %% +%% %% +%% Minor changes to the original are noted in this file in three %% +%% ways: %% +%% 1. \Typo{}{} for typographical corrections, showing original %% +%% and replacement text side-by-side. %% +%% 2. \Chg{}{} and \Add{}, for inconsistent/missing punctuation,%% +%% italicization, and capitalization. %% +%% 3. [** TN: Note]s for lengthier or stylistic comments. %% +%% %% +%% %% +%% Compilation Flags: %% +%% %% +%% The following behavior may be controlled by boolean flags. %% +%% %% +%% ForPrinting (false by default): %% +%% If false, compile a screen optimized file (one-sided layout, %% +%% blue hyperlinks). If true, print-optimized PDF file: Larger %% +%% text block, two-sided layout, black hyperlinks. %% +%% %% +%% %% +%% PDF pages: 228 (if ForPrinting set to false) %% +%% PDF page size: 4.5 x 6.5" (non-standard) %% +%% %% +%% Summary of log file: %% +%% * One overfull hbox (0.86pt), one slightly underfull hbox. %% +%% %% +%% Compile History: %% +%% %% +%% December, 2012: (Andrew D. Hwang) %% +%% texlive2011, GNU/Linux %% +%% %% +%% Command block: %% +%% %% +%% pdflatex x2 %% +%% makeindex %% +%% pdflatex x2 %% +%% %% +%% %% +%% December 2012: pglatex. %% +%% Compile this project with: %% +%% pdflatex 41568-t.tex ..... TWO times %% +%% makeindex 41568-t.idx %% +%% pdflatex 41568-t.tex ..... TWO times %% +%% %% +%% pdfTeX, Version 3.1415926-1.40.10 (TeX Live 2009/Debian) %% +%% %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\listfiles +\documentclass[12pt,leqno]{book}[2005/09/16] + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PACKAGES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +\usepackage[utf8]{inputenc}[2006/05/05] + +\usepackage{ifthen}[2001/05/26] %% Logical conditionals + +\usepackage{amsmath}[2000/07/18] %% Displayed equations +\usepackage{amssymb}[2002/01/22] %% and additional symbols + +\usepackage{alltt}[1997/06/16] %% boilerplate, credits, license + +\IfFileExists{indentfirst.sty}{% + \usepackage{indentfirst}[1995/11/23] +}{} + +\usepackage[perpage,symbol]{footmisc}[2005/03/17] + +\usepackage{multicol}[2006/05/18] +\usepackage{makeidx}[2000/03/29] + +\usepackage{graphicx}[1999/02/16]%% For diagrams +\usepackage[labelformat=empty,textfont=small]{caption}[2007/01/07] + +\usepackage{calc}[2005/08/06] + +\usepackage{fancyhdr} %% For running heads + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%% Interlude: Set up PRINTING (default) or SCREEN VIEWING %%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% ForPrinting=true false (default) +% Asymmetric margins Symmetric margins +% 1 : 1.6 text block aspect ratio 3 : 4 text block aspect ratio +% Black hyperlinks Blue hyperlinks +% Start major marker pages recto No blank verso pages +% +\newboolean{ForPrinting} + +%% UNCOMMENT the next line for a PRINT-OPTIMIZED VERSION of the text %% +%\setboolean{ForPrinting}{true} + +%% Initialize values to ForPrinting=false +\newcommand{\Margins}{hmarginratio=1:1} % Symmetric margins +\newcommand{\HLinkColor}{blue} % Hyperlink color +\newcommand{\PDFPageLayout}{SinglePage} +\newcommand{\TransNote}{Transcriber's Note} +\newcommand{\TransNoteCommon}{% + The camera-quality files for this public-domain ebook may be + downloaded \textit{gratis} at + \begin{center} + \texttt{www.gutenberg.org/ebooks/\ebook}. + \end{center} + + This ebook was produced using scanned images and OCR text generously + provided by the University of California, Santa Barbara, through the + Internet Archive. + \bigskip + + Minor typographical corrections and presentational changes have been + made without comment. + \bigskip +} + +\newcommand{\TransNoteText}{% + \TransNoteCommon + + This PDF file is optimized for screen viewing, but may be recompiled + for printing. Please consult the preamble of the \LaTeX\ source file + for instructions and other particulars. +} +%% Re-set if ForPrinting=true +\ifthenelse{\boolean{ForPrinting}}{% + \renewcommand{\Margins}{hmarginratio=2:3} % Asymmetric margins + \renewcommand{\HLinkColor}{black} % Hyperlink color + \renewcommand{\PDFPageLayout}{TwoPageRight} + \renewcommand{\TransNote}{Transcriber's Note} + \renewcommand{\TransNoteText}{% + \TransNoteCommon + + This PDF file is optimized for printing, but may be recompiled for + screen viewing. Please consult the preamble of the \LaTeX\ source + file for instructions and other particulars. + } +}{% If ForPrinting=false, don't skip to recto + \renewcommand{\cleardoublepage}{\clearpage} +} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%% End of PRINTING/SCREEN VIEWING code; back to packages %%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\ifthenelse{\boolean{ForPrinting}}{% + \setlength{\paperwidth}{8.5in}% + \setlength{\paperheight}{11in}% +% 1:1.6 + \usepackage[body={5in,8in},\Margins]{geometry}[2002/07/08] +}{% + \setlength{\paperwidth}{4.5in}% + \setlength{\paperheight}{6.5in}% + \raggedbottom +% 3:4 + \usepackage[body={4.25in,5.6in},\Margins,includeheadfoot]{geometry}[2002/07/08] +} + +\providecommand{\ebook}{00000} % Overridden during white-washing +\usepackage[pdftex, + hyperfootnotes=false, + pdftitle={The Project Gutenberg eBook \#\ebook: An Introduction to Mathematics.}, + pdfauthor={Alfred North Whitehead}, + pdfkeywords={University of California, Santa Barbara, The Internet Archive, Andrew D. Hwang}, + pdfstartview=Fit, % default value + pdfstartpage=1, % default value + pdfpagemode=UseNone, % default value + bookmarks=true, % default value + linktocpage=false, % default value + pdfpagelayout=\PDFPageLayout, + pdfdisplaydoctitle, + pdfpagelabels=true, + bookmarksopen=true, + bookmarksopenlevel=0, + colorlinks=true, + linkcolor=\HLinkColor]{hyperref}[2007/02/07] + +%% Fixed-width environment to format PG boilerplate %% +\newenvironment{PGtext}{% +\begin{alltt} +\fontsize{8.1}{10}\ttfamily\selectfont}% +{\end{alltt}} + +% Errors found during digitization +\newcommand{\Typo}[2]{#2} + +% Changes made for consistency; use \newcommand{\Chg}[2]{#1} to match original +\newcommand{\Chg}[2]{#2} +\newcommand{\Add}[1]{\Chg{}{#1}} + +%% Miscellaneous global parameters %% +% No hrule in page header +\renewcommand{\headrulewidth}{0pt} + +% Loosen spacing +\setlength{\emergencystretch}{1em} +\newcommand{\Loosen}{\spaceskip 0.375em plus 0.75em minus 0.25em} + +% Scratch pad for length calculations +\newlength{\TmpLen} + +%% Running heads %% +\newcommand{\FlushRunningHeads}{\clearpage\fancyhf{}} +\newcommand{\InitRunningHeads}{% + \setlength{\headheight}{15pt} + \pagestyle{fancy} + \thispagestyle{empty} + \ifthenelse{\boolean{ForPrinting}} + {\fancyhead[RO,LE]{\thepage}} + {\fancyhead[R]{\thepage}} +} + +% Uniform style for running heads +\newcommand{\RHeads}[1]{\small\textsc{\MakeUppercase{#1}}} + +\newcommand{\SetRunningHeads}[1]{% + \fancyhead[CO]{\RHeads{Introduction to Mathematics}}% + \fancyhead[CE]{\RHeads{#1}}% +} + +\newcommand{\BookMark}[2]{\phantomsection\pdfbookmark[#1]{#2}{#2}} + +%% Major document divisions %% +\newcommand{\PGBoilerPlate}{% + \pagenumbering{Alph} + \pagestyle{empty} + \BookMark{0}{PG Boilerplate.} +} +\newcommand{\FrontMatter}{% + \cleardoublepage + \frontmatter + \BookMark{-1}{Front Matter.} +} +\newcommand{\MainMatter}{% + \FlushRunningHeads + \InitRunningHeads + \mainmatter + \BookMark{-1}{Main Matter.} +} +\newcommand{\BackMatter}{% + \FlushRunningHeads + \InitRunningHeads + \backmatter + \BookMark{-1}{Back Matter.} +} +\newcommand{\PGLicense}{% + \FlushRunningHeads + \pagenumbering{Roman} + \InitRunningHeads + \BookMark{-1}{PG License.} + \fancyhead[C]{\RHeads{License}} +} + +%% ToC formatting %% +\newcommand{\TableofContents}{% + \FlushRunningHeads + \InitRunningHeads + \SetRunningHeads{Contents} + \BookMark{0}{Contents.} + \SectTitle{Contents} +} + +% Set the section number in a fixed-width box +\newcommand{\ToCBox}[1]{\settowidth{\TmpLen}{XVII.}% + \makebox[\TmpLen][r]{#1}\hspace*{1em}% +} +% For internal use, to determine if we need the Sect./Page line +\newcommand{\ToCAnchor}{} + +% \ToCLine{Chapter}{Title}{page number} +\newcommand{\ToCLine}[3]{% + \ifthenelse{\not\equal{#1}{}}{% + \label{toc:#1}% + \ifthenelse{\not\equal{\pageref{toc:#1}}{\ToCAnchor}}{% + \renewcommand{\ToCAnchor}{\pageref{toc:#1}}% + \noindent\makebox[\textwidth][r]{\scriptsize CHAP.\hfill PAGE}\\[8pt]% + }{}% + \settowidth{\TmpLen}{999}% + \noindent\strut\parbox[b]{\textwidth-\TmpLen}{\small% + \ToCBox{#1}\hangindent4em\MakeUppercase{#2}\dotfill}% + \makebox[\TmpLen][r]{\pageref{chapter:#1}}% + }{% else #1 = {} + \label{toc:#2}% + \ifthenelse{\not\equal{\pageref{toc:#2}}{\ToCAnchor}}{% + \renewcommand{\ToCAnchor}{\pageref{toc:#2}}% + \noindent\makebox[\textwidth][r]{\scriptsize CHAP.\hfill PAGE}\\[8pt]% + }{}% + \settowidth{\TmpLen}{999}% + \noindent\strut\parbox[b]{\textwidth-\TmpLen}{\small% + \ToCBox{}\hangindent4em\MakeUppercase{#2}\dotfill}% + \makebox[\TmpLen][r]{\pageref{appendix:#2}}% + }% + \smallskip +} + +%% Sectional units %% +% Typographical abstraction +\newcommand{\ChapHead}[2]{% + \SectTitle{#1} + \SubsectTitle{#2} +} + +\newcommand{\SectTitle}[1]{% + \section*{\centering\large\normalfont\MakeUppercase{#1}} +} + +\newcommand{\SubsectTitle}[1]{% + \subsection*{\centering\normalsize\normalfont\MakeUppercase{#1}} +} + +% \Chapter[running head]{Number}{Title} +\newcommand{\Chapter}[3][]{% + \FlushRunningHeads + \InitRunningHeads + \ifthenelse{\equal{#1}{}}{% + \BookMark{0}{#2: #3.}% + \SetRunningHeads{#3}% + }{% + \ifthenelse{\equal{#2}{VIII}}{ + \BookMark{0}{#2: #1 (Continued).}% + }{% + \BookMark{0}{#2: #1.}% + } + \SetRunningHeads{#1}% + } + \Pagelabel[chapter]{#2} + \ifthenelse{\equal{#2}{I}}{% + \section*{\normalfont\centering\Large AN INTRODUCTION TO MATHEMATICS} + }{} + \ChapHead{Chapter #2}{#3} +} + +\newcommand{\Appendix}[2][]{% + \FlushRunningHeads + \InitRunningHeads + \BookMark{0}{#2.} + \fancyhead[C]{\RHeads{#2}} + \Pagelabel[appendix]{#2}% + \SectTitle{#2}% + \ifthenelse{\not\equal{#1}{}}{% + \SubsectTitle{#1}% + }{} +} + +%% Diagrams %% +\newcommand{\Graphic}[2]{% + \phantomsection\label{fig:#2}% + \includegraphics[width=#1]{./images/#2.pdf}% +} +% \Figure[width]{figure number} +\newcommand{\DefWidth}{4in}% Default figure width +\newcommand{\Figure}[2][\DefWidth]{% + \begin{figure}[hbt!] + \centering + \phantomsection\label{fig:#2} + \Graphic{#1}{fig#2} + \caption{Fig.~#2.} + \end{figure}\ignorespaces% +} + +\newcommand{\Diagram}[1]{% + \begin{figure}[hbt!] + \centering + \Graphic{\DefWidth}{#1} + \end{figure}\ignorespaces% +} + +% Figure labels +\newcommand{\FigNum}[1]{\hyperref[fig:#1]{#1}} +\newcommand{\Fig}[2][Fig.]{\hyperref[fig:#2]{#1~#2}} + +\newcommand{\ChapNum}[1]{\hyperref[chapter:#1]{#1}} +\newcommand{\ChapRef}[2][Chapter]{\hyperref[chapter:#2]{\Chg{#1}{Chapter}~#2}} + +\newcommand{\Note}[1]{#1\Pagelabel{note#1}} +\newcommand{\Pagelabel}[2][page]{\phantomsection\label{#1:#2}} +\newcommand{\Pageref}[2][p.]{\hyperref[page:#2]{#1~\pageref*{page:#2}}} + +% Page separators +\newcommand{\PageSep}[1]{\ignorespaces} + +%% Index formatting +\makeindex +\makeatletter +\renewcommand{\@idxitem}{\par\hangindent 30\p@\global\let\idxbrk\nobreak} +\renewcommand\subitem{\idxbrk\@idxitem \hspace*{12\p@}\let\idxbrk\relax} +\renewcommand{\indexspace}{\par\penalty-3000 \vskip 10pt plus5pt minus3pt\relax} + +\renewenvironment{theindex}{% + \setlength\columnseprule{0.5pt}\setlength\columnsep{18pt}% + \begin{multicols}{2}[{\FlushRunningHeads% + \InitRunningHeads% + \BookMark{0}{Index.}% + \fancyhead[C]{\RHeads{Index}}% + \Pagelabel[appendix]{Index}% + \SectTitle{Index}\small}]% + \setlength\parindent{0pt}\setlength\parskip{0pt plus 0.3pt}% + \let\item\@idxitem\raggedright% + }{% + \end{multicols}\normalsize\FlushRunningHeads +} +\makeatother + +\newcommand{\EtSeq}[1]{\hyperpage{#1}\,\textit{et~seqq.}} + +% Miscellaneous textual conveniences (N.B. \emph, not \textit) +\newcommand{\Cf}{\emph{Cf.}} +\newcommand{\cf}{\emph{cf.}} +\newcommand{\eg}{\emph{e.g.}} +\newcommand{\ie}{\emph{i.e.}} +\newcommand{\viz}{\emph{viz.}} + +\newcommand{\First}[1]{\textsc{#1}} +\newcommand{\Title}[1]{\textit{#1}} +\newcommand{\Foreign}[1]{\textit{#1}} + +% Small-caps A.D. and B.C. +\newcommand{\SCAbbrev}[3]{% + \ifthenelse{\equal{#3}{.}}% + {\textsc{\MakeLowercase{#1.#2}.}}% + {\textsc{\MakeLowercase{#1.#2}.}\@#3}% +} + +\newcommand{\AD}[1]{\SCAbbrev{A}{D}{#1}} +\newcommand{\BC}[1]{\SCAbbrev{B}{C}{#1}} + + +%% Miscellaneous mathematical formatting %% +\DeclareInputMath{176}{{}^{\circ}} +\DeclareInputMath{183}{\cdot} +\newcommand{\Strut}[1][12pt]{\rule{0pt}{#1}} + +% Cross-ref-able equation tags +\newcommand{\Tag}[1]{\tag*{\quad\ensuremath{#1}}} +\newcommand{\Eq}[1]{\ensuremath{#1}} + +%%%%%%%%%%%%%%%%%%%%%%%% START OF DOCUMENT %%%%%%%%%%%%%%%%%%%%%%%%%% +\begin{document} +%% PG BOILERPLATE %% +\PGBoilerPlate +\begin{center} +\begin{minipage}{\textwidth} +\small +\begin{PGtext} +Project Gutenberg's An Introduction to Mathematics, by Alfred North Whitehead + +This eBook is for the use of anyone anywhere at no cost and with +almost no restrictions whatsoever. You may copy it, give it away or +re-use it under the terms of the Project Gutenberg License included +with this eBook or online at www.gutenberg.org + + +Title: An Introduction to Mathematics + +Author: Alfred North Whitehead + +Release Date: December 6, 2012 [EBook #41568] +Most recently updated: June 11, 2021 + +Language: English + +Character set encoding: UTF-8 + +*** START OF THIS PROJECT GUTENBERG EBOOK AN INTRODUCTION TO MATHEMATICS *** +\end{PGtext} +\end{minipage} +\end{center} +\newpage +%% Credits and transcriber's note %% +\begin{center} +\begin{minipage}{\textwidth} +\begin{PGtext} +Produced by Andrew D. Hwang. (This ebook was produced using +OCR text generously provided by the University of +California, Santa Barbara, through the Internet Archive.) +\end{PGtext} +\end{minipage} +\vfill +\end{center} + +\begin{minipage}{0.85\textwidth} +\small +\BookMark{0}{Transcriber's Note.} +\subsection*{\centering\normalfont\scshape% +\normalsize\MakeLowercase{\TransNote}}% + +\raggedright +\TransNoteText +\end{minipage} +%%%%%%%%%%%%%%%%%%%%%%%%%%% FRONT MATTER %%%%%%%%%%%%%%%%%%%%%%%%%% +\PageSep{i} +\FrontMatter +%[** TN: Publisher's front matter] +\noindent\footnotesize HOME UNIVERSITY LIBRARY \\ +OF MODERN KNOWLEDGE +\vfill + +\begin{center} +\Large AN INTRODUCTION TO \\ +MATHEMATICS +\medskip + +\normalsize +\textsc{By A. N. WHITEHEAD, Sc.D., F.R.S.} +\vfill + +\footnotesize +\scshape London \\ +{\normalsize WILLIAMS \& NORGATE} \\[6pt] +\rule{0.5in}{0.5pt} \\[6pt] +HENRY HOLT \& Co., New York \\ +Canada: WM. BRIGGS, Toronto \\ +India: R. \& T. WASHBOURNE, Ltd. +\end{center} +\normalsize +\PageSep{ii} +\iffalse +HOME +UNIVERSITY +LIBRARY +OF +MODERN KNOWLEDGE + +Editors: + +HERBERT FISHER, M.A.. F.B.A. + +PROF. GILBERT MURRAY, D.LlTT., +LL.D., F.B.A. + +PROF. J. ARTHUR THOMSON, M.A. + +PROF. WILLIAM T. BREWSTER, M.A. + +\Add{(}COLUMBIA UNIVERSITY, U.S.A.) + +NEW YORK + +HENRY HOLT AND COMPANY +\PageSep{iii} +AN +INTRODUCTION +TO +MATHEMATICS + +BY +A. N. WHITEHEAD, +Sc.D., F.R.S., + +AUTHOR OF ``UNIVERSAL ALGEBRA,'' JOINT +AUTHOR OF ``PRINCIPIA MATHEMATICA'' + +NEW AND REVISED EDITION + +LONDON +WILLIAMS AND NORGATE +\PageSep{iv} +PRINTED BY + +HALELL, WATSON AND VINEY, LD., +LONDON AND AYLESBURY. +\fi +\PageSep{v} +\TableofContents + +%CHAP. PAGE + +\ToCLine{I}{The Abstract Nature of Mathematics}{7} + +\ToCLine{II}{Variables}{15} + +\ToCLine{III}{Methods of Application}{25} + +\ToCLine{IV}{Dynamics}{42} + +\ToCLine{V}{The Symbolism of Mathematics}{58} + +\ToCLine{VI}{Generalizations of Number}{71} + +\ToCLine{VII}{Imaginary Numbers}{87} + +\ToCLine{VIII}{Imaginary Numbers (Continued)}{101} + +\ToCLine{IX}{Coordinate Geometry}{112} + +\ToCLine{X}{Conic Sections}{128} + +\ToCLine{XI}{Functions}{145} + +\ToCLine{XII}{Periodicity in Nature}{164} +\PageSep{vi} + +%CHAP. PAGE +\ToCLine{XIII}{Trigonometry}{173} + +\ToCLine{XIV}{Series}{194} + +\ToCLine{XV}{The Differential Calculus}{217} + +\ToCLine{XVI}{Geometry}{236} + +\ToCLine{XVII}{Quantity}{245} + +\ToCLine{}{Notes}{250} + +\ToCLine{}{Bibliography}{251} + +\ToCLine{}{Index}{253} +\PageSep{7} +\MainMatter +% [** TN: Text printed by \Chapter macro] +% AN INTRODUCTION TO +% MATHEMATICS + +\Chapter[Nature of Mathematics]{I}{The Abstract Nature of Mathematics} + +\First{The} study of mathematics is apt to commence +in disappointment. The important +applications of the science, the theoretical +interest of its ideas, and the logical rigour of +its methods, all generate the expectation of +a speedy introduction to processes of interest. +We are told that by its aid the stars are +weighed and the billions of molecules in a +drop of water are counted. Yet, like the +ghost of Hamlet's father, this great science +eludes the efforts of our mental weapons +to grasp it---``\,'Tis here, 'tis there, 'tis +gone''---and what we do see does not suggest +the same excuse for illusiveness as sufficed +for the ghost, that it is too noble for +our gross methods. ``A show of violence,'' +if ever excusable, may surely be ``offered'' +to the trivial results which occupy the +\PageSep{8} +pages of some elementary mathematical +treatises. + +The reason for this failure of the science to +live up to its reputation is that its fundamental +ideas are not explained to the student +disentangled from the technical procedure +which has been invented to facilitate their +exact presentation in particular instances. +Accordingly, the unfortunate learner finds +himself struggling to acquire a knowledge of +a mass of details which are not illuminated +by any general conception. Without a doubt, +technical facility is a first requisite for valuable +mental activity: we shall fail to appreciate +the rhythm of Milton, or the passion of +Shelley, so long as we find it necessary to +spell the words and are not quite certain of +the forms of the individual letters. In this +sense there is no royal road to learning. But +it is equally an error to confine attention to +technical processes, excluding consideration +of general ideas. Here lies the road to +pedantry. + +The object of the following Chapters is not +to teach mathematics, but to enable students +from the very beginning of their course to +know what the science is about, and why it is +necessarily the foundation of exact thought +as applied to natural phenomena. All allusion +in what follows to detailed deductions +in any part of the science will be inserted +\PageSep{9} +merely for the purpose of example, and care +will be taken to make the general argument +comprehensible, even if here and there some +technical process or symbol which the reader +does not understand is cited for the purpose +of illustration. + +The first acquaintance which most people +\index{Abstractness (\emph{defined})}% +have with mathematics is through arithmetic. +That two and two make four is usually taken +as the type of a simple mathematical proposition +which everyone will have heard of. +Arithmetic, therefore, will be a good subject +to consider in order to discover, if possible, +the most obvious characteristic of the science. +Now, the first noticeable fact about arithmetic +is that it applies to everything, to tastes and +to sounds, to apples and to angels, to the +ideas of the mind and to the bones of the +body. The nature of the things is perfectly +indifferent, of all things it is true that two +and two make four. Thus we write down as +the leading characteristic of mathematics +that it deals with properties and ideas +which are applicable to things just because +they are things, and apart from any particular +feelings, or emotions, or sensations, in any +way connected with them. This is what +is meant by calling mathematics an abstract +science. + +The result which we have reached deserves +attention. It is natural to think that an +\PageSep{10} +abstract science cannot be of much importance +in the affairs of human life, because it +has omitted from its consideration everything +of real interest. It will be remembered +that Swift, in his description of Gulliver's +\index{Swift}% +voyage to Laputa, is of two minds on this +\index{Laputa}% +point. He describes the mathematicians of +that country as silly and useless dreamers, +whose attention has to be awakened by +flappers. Also, the mathematical tailor measures +his height by a quadrant, and deduces +his other dimensions by a rule and compasses, +producing a suit of very ill-fitting clothes. +On the other hand, the mathematicians of +Laputa, by their marvellous invention of the +magnetic island floating in the air, ruled the +country and maintained their ascendency +over their subjects. Swift, indeed, lived at +a time peculiarly unsuited for gibes at contemporary +mathematicians. Newton's \Title{Principia} +\index{Newton}% +had just been written, one of the great +forces which have transformed the modern +world. Swift might just as well have laughed +at an earthquake. + +But a mere list of the achievements of +mathematics is an unsatisfactory way of +arriving at an idea of its importance. It is +worth while to spend a little thought in +getting at the root reason why mathematics, +because of its very abstractness, must always +remain one of the most important topics +\PageSep{11} +for thought. Let us try to make clear to +ourselves why explanations of the order of +events necessarily tend to become mathematical. + +Consider how all events are interconnected. +When we see the lightning, we listen for the +thunder; when we hear the wind, we look +for the waves on the sea; in the chill autumn, +the leaves fall. Everywhere order reigns, so +that when some circumstances have been +noted we can foresee that others will also be +present. The progress of science consists in +observing these interconnections and in showing +with a patient ingenuity that the events +of this evershifting world are but examples of +a few general connections or relations called +laws. To see what is general in what is particular +and what is permanent in what is +transitory is the aim of scientific thought. In +the eye of science, the fall of an apple, the +motion of a planet round a sun, and the clinging +of the atmosphere to the earth are all +seen as examples of the law of gravity. This +possibility of disentangling the most complex +evanescent circumstances into various examples +of permanent laws is the controlling +idea of modern thought. + +Now let us think of the sort of laws which +we want in order completely to realize this +scientific ideal. Our knowledge of the particular +facts of the world around us is gained +\PageSep{12} +from our sensations. We see, and hear, and +taste, and smell, and feel hot and cold, and +push, and rub, and ache, and tingle. These +are just our own personal sensations: my +toothache cannot be your toothache, and my +sight cannot be your sight. But we ascribe +the origin of these sensations to relations between +the things which form the external +world. Thus the dentist extracts not the +toothache but the tooth. And not only so, +we also endeavour to imagine the world as +one connected set of things which underlies +all the perceptions of all people. There is not +one world of things for my sensations and another +for yours, but one world in which we +both exist. It is the same tooth both for +dentist and patient. Also we hear and we +touch the same world as we see. + +It is easy, therefore, to understand that we +want to describe the connections between +these external things in some way which does +not depend on any particular sensations, nor +even on all the sensations of any particular +person. The laws satisfied by the course of +events in the world of external things are to +be described, if possible, in a neutral universal +fashion, the same for blind men as for +deaf men, and the same for beings with +faculties beyond our ken as for normal human +beings. + +But when we have put aside our immediate +\PageSep{13} +\index{Abstractness (\emph{defined})}% +\index{Dynamical Explanation}% +sensations, the most serviceable part---from +its clearness, definiteness, and universality---of +what is left is composed of our general ideas +of the abstract formal properties of things; +in fact, the abstract mathematical ideas mentioned +above. Thus it comes about that, +step by step, and not realizing the full meaning +of the process, mankind has been led to +search for a mathematical description of the +properties of the universe, because in this way +only can a general idea of the course of events +be formed, freed from reference to particular +persons or to particular types of sensation. +For example, it might be asked at dinner: +``What was it which underlay my sensation +of sight, yours of touch, and his of taste +and smell?''\ the answer being ``an apple.'' +But in its final analysis, science seeks to +describe an apple in terms of the positions +and motions of molecules, a description which +ignores me and you and him, and also ignores +sight and touch and taste and smell. +Thus mathematical ideas, because they +are abstract, supply just what is wanted +for a scientific description of the course of +events. + +This point has usually been misunderstood, +%[** TN: Entry listed on p. 18 in the original] +\index{Pythagoras}% +from being thought of in too narrow a way. +Pythagoras had a glimpse of it when he proclaimed +that number was the source of all +things. In modern times the belief that the +\PageSep{14} +ultimate explanation of all things was to be +found in Newtonian mechanics was an adumbration +of the truth that all science as it +grows towards perfection becomes mathematical +\index{Dynamical Explanation}% +in its ideas. +\PageSep{15} + + +\Chapter{II}{Variables} + +\First{Mathematics} as a science commenced when +first someone, probably a Greek, proved propositions +about \emph{any} things or about \emph{some} +things, without specification of definite particular +things. These propositions were first +enunciated by the Greeks for geometry; and, +accordingly, geometry was the great Greek +mathematical science. After the rise of geometry +centuries passed away before algebra +made a really effective start, despite some +faint anticipations by the later Greek mathematicians. + +The ideas of \emph{any} and of \emph{some} are introduced +into algebra by the use of letters, instead +of the definite numbers of arithmetic. +Thus, instead of saying that $2 + 3 = 3 + 2$, in +algebra we generalize and say that, if $x$ and~$y$ +stand for \emph{any} two numbers, then $x + y = y + x$. +Again, in the place of saying that $3 > 2$, we +generalize and say that if $x$~be \emph{any} number +there exists \emph{some} number (or numbers)~$y$ such +that $y > x$. We may remark in passing that +this latter assumption---for when put in its +strict ultimate form it is an assumption---is +\PageSep{16} +of vital importance, both to philosophy and +to mathematics; for by it the notion of infinity +is introduced. Perhaps it required the +introduction of the arabic numerals, by which +the use of letters as standing for definite +numbers has been completely discarded in +mathematics, in order to suggest to mathematicians +the technical convenience of the +use of letters for the ideas of \emph{any} number +and \emph{some} number. The Romans would have +stated the number of the year in which this +is written in the form MDCCCCX., whereas +we write it~1910, thus leaving the letters for +the other usage. But this is merely a speculation. +After the rise of algebra the differential +calculus was invented by Newton and +\index{Newton}% +Leibniz, and then a pause in the progress +\index{Leibniz}% +of the philosophy of mathematical thought +occurred so far as these notions are concerned; +and it was not till within the last few years +that it has been realized how fundamental +\emph{any} and \emph{some} are to the very nature of mathematics, +with the result of opening out still +further subjects for mathematical exploration. + +Let us now make some simple algebraic +statements, with the object of understanding +exactly how these fundamental ideas occur. + +\Eq{(1)} For \emph{any} number~$x$, $x + 2 = 2 + x$; + +\Eq{(2)} For \emph{some} number~$x$, $x + 2 = 3$; + +\Eq{(3)} For \emph{some} number~$x$, $x + 2 > 3$. +\PageSep{17} + +The first point to notice is the possibilities +contained in the meaning of \emph{some}, as here +used. Since $x + 2 = 2 + x$ for any number~$x$, it +is true for \emph{some} number~$x$. Thus, as here used, +\emph{any} implies \emph{some} and \emph{some} does not exclude +\emph{any}. Again, in the second example, there is, +in fact, only one number~$x$, such that $x + 2 = 3$, +namely only the number~$1$. Thus the \emph{some} +may be one number only. But in the third\Typo{,}{} +example, any number~$x$ which is greater than~$1$ +gives $x + 2 > 3$. Hence there are an infinite +number of numbers which answer to the \emph{some} +number in this case. Thus \emph{some} may be anything +between \emph{any} and \emph{one only}, including +both these limiting cases. + +It is natural to supersede the statements +\Eq{(2)} and \Eq{(3)} by the questions: + +\Eq{(2')} For what number~$x$ is $x + 2 = 3$; + +\Eq{(3')} For what numbers~$x$ is $x + 2 > 3$. + +%[** TN: No indent in the original] +Considering~\Eq{(2')}, $x + 2 = 3$ is an equation, and +\index{Unknown, The}% +it is easy to see that its solution is $x = 3 - 2 = 1$. +When we have asked the question implied in +the statement of the equation $x + 2 = 3$, $x$~is +called the unknown. The object of the solution +of the equation is the determination of +the unknown. Equations are of great importance +in mathematics, and it seems as +%[** TN: thoroughgoing hyphenated in the original; only instance] +though \Eq{(2')}~exemplified a much more thoroughgoing +and fundamental idea than the original +statement~\Eq{(2)}. This, however, is a complete +mistake. The idea of the undetermined +\PageSep{18} +``variable'' as occurring in the use of ``some'' +or ``any'' is the really important one in +mathematics; that of the ``unknown'' in an +equation, which is to be solved as quickly as +possible, is only of subordinate use, though +of course it is very important. One of the +causes of the apparent triviality of much of +elementary algebra is the preoccupation of +the text-books with the solution of equations. +The same remark applies to the solution of +the inequality~\Eq{(3')} as compared to the original +statement~\Eq{(3)}. + +But the majority of interesting formulæ, +\index{Relations between Variables|EtSeq}% +\index{Variable, The}% +especially when the idea of \emph{some} is present, +involve more than one variable. For example, +the consideration of the pairs of numbers +$x$ and~$y$ (fractional or integral) which +satisfy $x + y = 1$ involves the idea of two correlated +variables, $x$~and~$y$. When two variables +are present the same two main types of +statement occur. For example, \Eq{(1)}~for +\emph{any} pair of numbers, $x$~and~$y$, $x + y = y + x$, +and \Eq{(2)}~for \emph{some} pairs of numbers, $x$~and~$y$, +$x + y = 1$. + +The second type of statement invites consideration +of the aggregate of pairs of numbers +which are bound together by some fixed +relation---in the case given, by the relation +$x + y = 1$. One use of formulæ of the first +type, true for \emph{any} pair of numbers, is that by +them formulæ of the second type can be +\PageSep{19} +thrown into an indefinite number of equivalent +forms. For example, the relation $x + y = 1$ +is equivalent to the relations +\[ +y + x = 1,\quad +(x - y) + 2y = 1,\quad +6x + 6y = 6, +\] +and so on. Thus a skilful mathematician +uses that equivalent form of the relation +under consideration which is most convenient +for his immediate purpose. + +It is not in general true that, when a pair +of terms satisfy some fixed relation, if one of +the terms is given the other is also definitely +determined. For example, when $x$ and~$y$ +satisfy $y^{2} = x$, if $x = 4$, $y$~can be~$±2$, thus, +for any positive value of~$x$ there are alternative +values for~$y$. Also in the relation +$x + y > 1$, when either $x$ or~$y$ is given, an +indefinite number of values remain open for +the other. + +Again there is another important point to +be noticed. If we restrict ourselves to positive +numbers, integral or fractional, in considering +the relation $x + y = 1$, then, if either +$x$ or~$y$ be greater than~$1$, there is no positive +number which the other can assume so as to +satisfy the relation. Thus the ``field'' of +the relation for~$x$ is restricted to numbers less +than~$1$, and similarly for the ``field'' open +to~$y$. Again, consider integral numbers only, +positive or negative, and take the relation +\PageSep{20} +$y^{2} = x$, satisfied by pairs of such numbers. +Then whatever integral value is given to~$y$, +$x$~can assume one corresponding integral +value. So the ``field'' for~$y$ is unrestricted +among these positive or negative integers. +But the ``field'' for~$x$ is restricted in two +ways. In the first place $x$~must be positive, +and in the second place, since $y$~is to be integral, +$x$~must be a perfect square. Accordingly, +the ``field'' of~$x$ is restricted to the set +of integers $1^{2}$, $2^{2}$, $3^{2}$, $4^{2}$, and so on, \ie, to $1$, +$4$, $9$, $16$, and so on. + +The study of the general properties of a +relation between pairs of numbers is much +facilitated by the use of a diagram constructed +as follows: +\Figure[3.5in]{1} + +Draw two lines $OX$ and $OY$ at right angles; +let any number~$x$ be represented by $x$~units +\PageSep{21} +(in any scale) of length along~$OX$, any number~$y$ +by $y$~units (in any scale) of length along~$OY$. +Thus if $OM$, along~$OX$, be $x$~units in +length, and $ON$, along~$OY$, be $y$~units in length, +by completing the parallelogram $OMPN$ we +find a point~$P$ which corresponds to the pair +of numbers $x$~and~$y$. To each point there +corresponds one pair of numbers, and to each +pair of numbers there corresponds one point. +The pair of numbers are called the coordinates +of the point. Then the points +whose coordinates satisfy some fixed relation +can be indicated in a convenient way, +by drawing a line, if they all lie on a line, +or by shading an area if they are all points +in the area. If the relation can be represented +by an equation such as $x + y = 1$, or +$y^{2} = x$, then the points lie on a line, which is +straight in the former case and curved in +the latter. For example, considering only +positive numbers, the points whose coordinates +satisfy $x + y = 1$ lie on the straight +line~$AB$ in \Fig{1}, where $0A = 1$ and $OB = 1$. +Thus this segment of the straight line~$AB$ +gives a pictorial representation of the properties +of the relation under the restriction to +positive numbers. + +Another example of a relation between two +variables is afforded by considering the variations +in the pressure and volume of a given +mass of some gaseous substance---such as air +\PageSep{22} +or coal-gas or steam---at a constant temperature. +Let $v$~be the number of cubic feet in +its volume and $p$~its pressure in lb.\ weight +per square inch. Then the law, known as +Boyle's law, expressing the relation between +$p$ and~$v$ as both vary, is that the product~$pv$ +is constant, always supposing that the +temperature does not alter. Let us suppose, +for example, that the quantity of the gas +and its other circumstances are such that +we can put $pv = 1$ (the exact number on +the right-hand side of the equation makes +no essential difference). +\Figure{2} + +Then in \Fig{2} we take two lines, $OV$ and~$OP$, +at right angles and draw~$OM$ along~$OV$ +to represent $v$~units of volume, and $ON$ along~$OP$ +\PageSep{23} +to represent $p$~units of pressure. Then +the point~$Q$, which is found by completing the +parallelogram $OMQN$, represents the state of +the gas when its volume is $v$~cubic feet and its +pressure is $p$~lb.\ weight per square inch. If +the circumstances of the portion of gas considered +are such that $pv = 1$, then all these +points~$Q$ which correspond to any possible +state of this portion of gas must lie on the +curved line $ABC$, which includes all points +for which $p$~and $v$ are positive, and $pv = 1$. +Thus this curved line gives a pictorial representation +of the relation holding between the +volume and the pressure. When the pressure +is very big the corresponding point~$Q$ must +be near~$C$, or even beyond~$C$ on the undrawn +part of the curve; then the volume will be +very small. When the volume is big $Q$~will +be near to~$A$, or beyond~$A$; and then the +pressure will be small. Notice that an engineer +or a physicist may want to know the +particular pressure corresponding to some +definitely assigned volume. Then we have +the case of determining the \emph{unknown}~$p$ when +\index{Unknown, The}% +$v$~is a known number. But this is only in +particular cases. In considering generally +the properties of the gas and how it will behave, +he has to have in his mind the general +form of the whole curve $ABC$ and its general +properties. In other words the really fundamental +idea is that of the pair of \emph{variables} +\PageSep{24} +satisfying the relation $pv = 1$. This example +illustrates how the idea of \emph{variables} is fundamental, +\index{Variable, The}% +both in the applications as well as in +the theory of mathematics. +\PageSep{25} + + +\Chapter{III}{Methods of Application} + +\First{The} way in which the idea of variables +satisfying a relation occurs in the applications +of mathematics is worth thought, and by +devoting some time to it we shall clear up +our thoughts on the whole subject. + +Let us start with the simplest of examples:---Suppose +that building costs $1$\textit{s.}\ per cubic +foot and that $20$\textit{s.}\ make~£$1$. Then in all +the complex circumstances which attend the +building of a new house, amid all the various +sensations and emotions of the owner, the +architect, the builder, the workmen, and the +onlookers as the house has grown to completion, +this fixed correlation is by the law +assumed to hold between the cubic content +and the cost to the owner, namely that if $x$~be +the number of cubic feet, and £$y$~the cost, +then $20y = x$. This correlation of $x$~and $y$ is +assumed to be true for the building of any +house by any owner. Also, the volume of +the house and the cost are not supposed to +have been perceived or apprehended by any +particular sensation or faculty, or by any +\PageSep{26} +particular man. They are stated in an abstract +general way, with complete indifference +to the owner's state of mind when he has +to pay the bill. + +Now think a bit further as to what all this +means. The building of a house is a complicated +set of circumstances. It is impossible +to begin to apply the law, or to test +it, unless amid the general course of events +it is possible to recognize a definite set of +occurrences as forming a particular instance +of the building of a house. In short, we must +know a house when we see it, and must recognize +the events which belong to its building. +Then amidst these events, thus isolated in +idea from the rest of nature, the two elements +of the cost and cubic content must be determinable; +and when they are both determined, +if the law be true, they satisfy the general +formula +\[ +20y = x. +\] +But is the law true? Anyone who has had +much to do with building will know that we +have here put the cost rather high. It is +only for an expensive type of house that it +will work out at this price. This brings out +another point which must be made clear. +While we are making mathematical calculations +connected with the formula $20y = x$, it +is indifferent to us whether the law be true or +\PageSep{27} +false. In fact, the very meanings assigned +to $x$~and~$y$, as being a number of cubic feet +and a number of pounds sterling, are indifferent. +During the mathematical investigation +we are, in fact, merely considering the +properties of this correlation between a pair +of variable numbers $x$ and~$y$. Our results +will apply equally well, if we interpret $y$ to +mean a number of fishermen and $x$~the number +of fish caught, so that the assumed law +is that on the average each fisherman catches +twenty fish. The mathematical certainty of +the investigation only attaches to the results +considered as giving properties of the correlation +$20y = x$ between the variable pair of +numbers $x$ and~$y$. There is no mathematical +certainty whatever about the cost of the +actual building of any house. The law is not +quite true and the result it gives will not be +quite accurate. In fact, it may well be hopelessly +wrong. + +Now all this no doubt seems very obvious. +But in truth with more complicated instances +there is no more common error than to assume +that, because prolonged and accurate mathematical +calculations have been made, the +application of the result to some fact of +nature is absolutely certain. The conclusion +of no argument can be more certain than the +assumptions from which it starts. All mathematical +calculations about the course of +\PageSep{28} +nature must start from some assumed law of +nature, such, for instance, as the assumed +law of the cost of building stated above. +Accordingly, however accurately we have +calculated that some event must occur, the +doubt always remains---Is the law true? If +the law states a precise result, almost certainly +it is not precisely accurate; and thus +even at the best the result, precisely as calculated, +is not likely to occur. But then we +have no faculty capable of observation with +ideal precision, so, after all, our inaccurate +laws may be good enough. + +We will now turn to an actual case, that +of Newton and the Law of Gravity. This law +states that any two bodies attract one another +with a force proportional to the product +of their masses, and inversely proportional to +the square of the distance between them. +Thus if $m$~and~$M$ are the masses of the two +bodies, reckoned in lbs.\ say, and $d$~miles is +the distance between them, the force on either +body, due to the attraction of the other and +directed towards it, is proportional to~$\dfrac{mM}{d^{2}}$; +thus this force can be written as equal to +$\dfrac{kmM}{d^{2}}$, where $k$~is a definite number depending +on the absolute magnitude of this attraction +and also on the scale by which we choose to +measure forces. It is easy to see that, if we +\PageSep{29} +wish to reckon in terms of forces such as the +weight of a mass of $1$~lb., the number which +$k$~represents must be extremely small; for +when $m$~and $M$ and~$d$ are each put equal to~$1$, +$\dfrac{kmM}{d^{2}}$~becomes the gravitational attraction +of two equal masses of $1$~lb.\ at the distance of +one mile, and this is quite inappreciable. + +However, we have now got our formula for +the force of attraction. If we call this force~$F$, +it is $F = k\dfrac{mM}{d^{2}}$, giving the correlation between +the variables $F$,~$m$,~$M$, and~$d$. We all +know the story of how it was found out. +Newton, it states, was sitting in an orchard +and watched the fall of an apple, and then +the law of universal gravitation burst upon +\index{Gravitation}% +his mind. It may be that the final formulation +of the law occurred to him in an +orchard, as well as elsewhere---and he must +have been somewhere. But for our purposes +it is more instructive to dwell upon the vast +amount of preparatory thought, the product +of many minds and many centuries, which +was necessary before this exact law could be +formulated. In the first place, the mathematical +habit of mind and the mathematical +procedure explained in the previous two +chapters had to be generated; otherwise +Newton could never have thought of a formula +representing the force between \emph{any} two masses +\PageSep{30} +at \emph{any} distance. Again, what are the meanings +\index{Distance}% +of the terms employed, Force, Mass, Distance? +\index{Force}% +\index{Mass}% +Take the easiest of these terms, +Distance. It seems very obvious to us to +conceive all material things as forming a definite +geometrical whole, such that the distances +of the various parts are measurable in +terms of some unit length, such as a mile or +a yard. This is almost the first aspect of a +material structure which occurs to us. It is +the gradual outcome of the study of geometry +and of the theory of measurement. Even +now, in certain cases, other modes of thought +are convenient. In a mountainous country +distances are often reckoned in hours. But +leaving distance, the other terms, Force and +Mass, are much more obscure. The exact +comprehension of the ideas which Newton +\index{Newton}% +meant to convey by these words was of slow +growth, and, indeed, Newton himself was the +first man who had thoroughly mastered the +true general principles of Dynamics. +\index{Dynamics}% + +Throughout the middle ages, under the influence +of Aristotle, the science was entirely +\index{Aristotle}% +misconceived. Newton had the advantage of +coming after a series of great men, notably +Galileo, in Italy, who in the previous two +\index{Galileo}% +centuries had reconstructed the science and +had invented the right way of thinking about +it. He completed their work. Then, finally, +having the ideas of force, mass, and distance, +\PageSep{31} +clear and distinct in his mind, and realising +their importance and their relevance to the +fall of an apple and the motions of the planets, +he hit upon the law of gravitation and proved +it to be the formula always satisfied in these +various motions. + +The vital point in the application of mathematical +formulæ is to have clear ideas and a +correct estimate of their relevance to the +phenomena under observation. No less than +ourselves, our remote ancestors were impressed +with the importance of natural +phenomena and with the desirability of taking +energetic measures to regulate the sequence +of events. Under the influence of irrelevant +ideas they executed elaborate religious ceremonies +to aid the birth of the new moon, and +performed sacrifices to save the sun during +the crisis of an eclipse. There is no reason to +believe that they were more stupid than we +are. But at that epoch there had not been +opportunity for the slow accumulation of +clear and relevant ideas. + +The sort of way in which physical sciences +\index{Electromagnetism|EtSeq}% +grow into a form capable of treatment by +mathematical methods is illustrated by the +history of the gradual growth of the science +of electromagnetism. Thunderstorms are +events on a grand scale, arousing terror in +men and even animals. From the earliest +times they must have been objects of wild +\PageSep{32} +\index{Electricity|EtSeq}% +and fantastic hypotheses, though it may be +doubted whether our modern scientific discoveries +in connection with electricity are not +more astonishing than any of the magical +explanations of savages. The Greeks knew +that amber (Greek, electron) when rubbed +would attract light and dry bodies. In +1600~\AD, Dr.~Gilbert, of Colchester, published +\index{Gilbert, Dr.}% +the first work on the subject in which any +scientific method is followed. He made a +list of substances possessing properties similar +to those of amber; he must also have the +credit of connecting, however vaguely, electric +and magnetic phenomena. At the end of the +seventeenth and throughout the eighteenth +century knowledge advanced. Electrical +machines were made, sparks were obtained +from them; and the Leyden Jar was invented, +by which these effects could be intensified. +Some organised knowledge was +being obtained; but still no relevant mathematical +ideas had been found out. Franklin, +\index{Franklin}% +in the year 1752, sent a kite into the clouds +and proved that thunderstorms were electrical. + +Meanwhile from the earliest epoch (2634~\BC) +the Chinese had utilized the characteristic +property of the compass needle, but do not +seem to have connected it with any theoretical +ideas. The really profound changes in human +life all have their ultimate origin in knowledge +\PageSep{33} +pursued for its own sake. The use of the compass +was not introduced into Europe till the end +of the twelfth century~\AD, more than $3000$~years +after its first use in China. The importance +which the science of electromagnetism +has since assumed in every department of +human life is not due to the superior practical +bias of Europeans, but to the fact that in the +West electrical and magnetic phenomena +were studied by men who were dominated by +abstract theoretic interests. + +The discovery of the electric current is due +\index{Electric Current}% +to two Italians, Galvani in~1780, and Volta +\index{Galvani}% +\index{Volta}% +in~1792. This great invention opened a new +series of phenomena for investigation. The +scientific world had now three separate, +though allied, groups of occurrences on hand---the +effects of ``statical'' electricity arising +from frictional electrical machines, the magnetic +phenomena, and the effects due to +electric currents. From the end of the +eighteenth century onwards, these three lines +of investigation were quickly \Chg{inter-connected}{interconnected} +and the modern science of electromagnetism +was constructed, which now threatens to +transform human life. + +Mathematical ideas now appear. During +the decade 1780 to~1789, Coulomb, a Frenchman, +\index{Coulomb}% +proved that magnetic poles attract or +repel each other, in proportion to the inverse +square of their distances, and also that the +\PageSep{34} +same law holds for electric charges---laws +curiously analogous to that of gravitation. +In~1820, Öersted, a Dane, discovered that +\index{Oersted@Öersted}% +electric currents exert a force on magnets, +and almost immediately afterwards the +mathematical law of the force was correctly +formulated by Ampère, a Frenchman, who +\index{Ampere@Ampère}% +also proved that two electric currents exerted +forces on each other. ``The experimental investigation +by which Ampère established the +law of the mechanical action between electric +currents is one of the most brilliant achievements +in science. The whole, theory and +experiment, seems as if it had leaped, full-grown +and full armed, from the brain of +the `Newton of Electricity.' It is perfect +\index{Newton}% +in form, and unassailable in accuracy, and it +is summed up in a formula from which all +the phenomena may be deduced, and which +must always remain the cardinal formula of +electro-dynamics.''\footnote + {\Title{Electricity and Magnetism}, Clerk Maxwell, Vol.~II., +\index{Clerk Maxwell}% + ch.~iii.} + +The momentous laws of induction between +currents and between currents and magnets +were discovered by Michael Faraday in 1831--82. +\index{Faraday}% +Faraday was asked: ``What is the use +of this discovery?'' He answered: ``What is +the use of a child---it grows to be a man.'' +Faraday's child has grown to be a man and +is now the basis of all the modern applications +\PageSep{35} +of electricity. Faraday also reorganized the +whole theoretical conception of the science. +His ideas, which had not been fully understood +by the scientific world, were extended +and put into a directly mathematical form by +Clerk Maxwell in~1873. As a result of his +\index{Clerk Maxwell}% +mathematical investigations, Maxwell recognized +that, under certain conditions, electrical +vibrations ought to be propagated. He at +once suggested that the vibrations which +form light are electrical. This suggestion has +\index{Light}% +since been verified, so that now the whole +theory of light is nothing but a branch of the +% [** TN: Herz [sic]] +great science of electricity. Also Herz, a +\index{Herz}% +German, in~1888, following on Maxwell's +ideas, succeeded in producing electric vibrations +by direct electrical methods\Add{.} His +experiments are the basis of our wireless +telegraphy. + +In more recent years even more fundamental +discoveries have been made, and the +science continues to grow in theoretic importance +and in practical interest. This rapid +sketch of its progress illustrates how, by the +gradual introduction of the relevant theoretic +ideas, suggested by experiment and themselves +suggesting fresh experiments, a whole +mass of isolated and even trivial phenomena +are welded together into one coherent science, +in which the results of abstract mathematical +deductions, starting from a few simple assumed +\PageSep{36} +laws, supply the explanation to the +complex tangle of the course of events. + +Finally, passing beyond the particular +sciences of electromagnetism and light, we +can generalize our point of view still further, +and direct our attention to the growth of +mathematical physics considered as one great +chapter of scientific thought. In the first +place, what in the barest outlines is the story +of its growth? + +It did not begin as one science, or as the +product of one band of men. The Chaldean +shepherds watched the skies, the agents of +Government in Mesopotamia and Egypt +measured the land, priests and philosophers +brooded on the general nature of all things. +The vast mass of the operations of nature +appeared due to mysterious unfathomable +forces. ``The wind bloweth where it listeth'' +expresses accurately the blank ignorance then +existing of any stable rules followed in detail +by the succession of phenomena. In broad outline, +then as now, a regularity of events was +patent. But no minute tracing of their interconnection +was possible, and there was no +knowledge how even to set about to construct +such a science. + +Detached speculations, a few happy or unhappy +shots at the nature of things, formed +the utmost which could be produced. + +Meanwhile land-surveys had produced geometry, +\index{Geometry}% +\PageSep{37} +and the observations of the heavens +disclosed the exact regularity of the solar +system. Some of the later Greeks, such as +Archimedes, had just views on the elementary +\index{Archimedes|EtSeq}% +phenomena of hydrostatics and optics. Indeed, +Archimedes, who combined a genius for +mathematics with a physical insight, must +rank with Newton, who lived nearly two +\index{Newton}% +thousand years later, as one of the founders +of mathematical physics. He lived at Syracuse, +the great Greek city of Sicily. When +the Romans besieged the town (in 212~to +210~\BC), he is said to have burned their ships +by concentrating on them, by means of +mirrors, the sun's rays. The story is highly +improbable, but is good evidence of the reputation +which he had gained among his contemporaries +for his knowledge of optics. At +the end of this siege he was killed. According +to one account given by Plutarch, in his life of +\index{Plutarch}% +Marcellus, he was found by a Roman soldier +\index{Marcellus}% +absorbed in the study of a geometrical diagram +which he had traced on the sandy floor of his +room. He did not immediately obey the orders +of his captor, and so was killed. For the credit +of the Roman generals it must be said that +the soldiers had orders to spare him. The +internal evidence for the other famous story +of him is very strong; for the discovery +attributed to him is one eminently worthy of +his genius for mathematical and physical research. +\PageSep{38} +Luckily, it is simple enough to be +explained here in detail. It is one of the best +easy examples of the method of application +of mathematical ideas to physics. + +Hiero, King of Syracuse, had sent a quantity +\index{Hiero}% +of gold to some goldsmith to form the +material of a crown. He suspected that the +craftsmen had abstracted some of the gold +and had supplied its place by alloying the +remainder with some baser metal. Hiero +sent the crown to Archimedes and asked him +to test it. In these days an indefinite number +of chemical tests would be available. +But then Archimedes had to think out the +matter afresh. The solution flashed upon +him as he lay in his bath. He jumped +up and ran through the streets to the +palace, shouting \Foreign{Eureka! Eureka!} (I have +found it, I have found it). This day, if we +knew which it was, ought to be celebrated as +the birthday of mathematical physics; the +science came of age when Newton sat in his +\index{Newton}% +orchard. Archimedes had in truth made a +great discovery. He saw that a body when +immersed in water is pressed upwards by the +surrounding water with a resultant force +equal to the weight of the water it displaces. +This law can be proved theoretically from the +mathematical principles of hydrostatics and +can also be verified experimentally. Hence, +if $W$~lb.\ be the weight of the crown, as weighed +\PageSep{39} +in air, and $w$~lb.\ be the weight of the water +which it displaces when completely immersed, +$W - w$ would be the extra upward force +necessary to sustain the crown as it hung in +water. + +Now, this upward force can easily be ascertained +by weighing the body as it hangs in +water, as shown in the annexed figure. If +\Figure{3} +the weights in the right-hand scale come to +$F$~lb., then the apparent weight of the crown +in water is $F$~lb.; and we thus have +\[ +F = W - w +\] +and thus +\[ +w = W - F, +\] +and +\[ +\frac{W}{w} = \frac{W}{W - F} +\Tag{(A)} +\] +where $W$ and $F$ are determined by the easy, +and fairly precise, operation of weighing. +\PageSep{40} +Hence, by equation~\Eq{(A)}, $\dfrac{W}{w}$~is known. But +$\dfrac{W}{w}$~is the ratio of the weight of the crown to +the weight of an equal volume of water. +This ratio is the same for any lump of metal of +the same material: it is now called the specific +gravity of the material, and depends only on +the intrinsic nature of the substance and not +on its shape or quantity. Thus to test if the +crown were of gold, Archimedes had only to +take a lump of indisputably pure gold and +find its specific gravity by the same process. +If the two specific gravities agreed, the crown +was pure; if they disagreed, it was debased. + +This argument has been given at length, +because not only is it the first precise example +of the application of mathematical ideas to +physics, but also because it is a perfect and +simple example of what must be the method +and spirit of the science for all time. + +The death of Archimedes by the hands of a +Roman soldier is symbolical of a world-change +of the first magnitude: the theoretical Greeks, +with their love of abstract science, were superseded +in the leadership of the European world +by the practical Romans. Lord Beaconsfield, +\index{Beaconsfield, Lord}% +in one of his novels, has defined a practical +man as a man who practises the errors of +his forefathers. The Romans were a great +race, but they were cursed with the sterility +\PageSep{41} +\index{Specific Gravity}% +which waits upon practicality. They did not +improve upon the knowledge of their forefathers, +and all their advances were confined +to the minor technical details of engineering. +They were not dreamers enough to arrive at +new points of view, which could give a more +fundamental control over the forces of nature. +No Roman lost his life because he was absorbed +in the contemplation of a mathematical +diagram. +\PageSep{42} + + +\Chapter{IV}{Dynamics} + +\First{The} world had to wait for eighteen hundred +years till the Greek mathematical physicists +found successors. In the sixteenth and seventeenth +centuries of our era great Italians, in +particular Leonardo da~Vinci, the artist +\index{Aristotle}% +\index{Galileo|EtSeq}% +\index{Leonardo da Vinci}% +(born 1452, died 1519), and Galileo (born 1564, +died 1642), rediscovered the secret, known to +Archimedes, of relating abstract mathematical +ideas with the experimental investigation of +natural phenomena. Meanwhile the slow +advance of mathematics and the accumulation +of accurate astronomical knowledge had +placed natural philosophers in a much more +advantageous position for research. Also the +very egoistic self-assertion of that age, its +greediness for personal experience, led its +thinkers to want to see for themselves what +happened; and the secret of the relation of +mathematical theory and experiment in inductive +reasoning was practically discovered. +It was an act eminently characteristic of the +age that Galileo, a philosopher, should have +\PageSep{43} +dropped the weights from the leaning tower +of Pisa. There are always men of thought +and men of action; mathematical physics is +the product of an age which combined in the +same men impulses to thought with impulses +to action. + +This matter of the dropping of weights from +\index{Dynamics|EtSeq}% +the tower marks picturesquely an essential +step in knowledge, no less a step than the +first attainment of correct ideas on the science +of dynamics, the basal science of the whole +subject. The particular point in dispute was +as to whether bodies of different weights +would fall from the same height in the same +time. According to a dictum of Aristotle, +universally followed up to that epoch, the +heavier weight would fall the quicker. Galileo +affirmed that they would fall in the same +time, and proved his point by dropping +weights from the top of the leaning tower. +The apparent exceptions to the rule all arise +when, for some reason, such as extreme lightness +or great speed, the air resistance is important. +But neglecting the air the law is +exact. + +Galileo's successful experiment was not the +\index{Motion, First Law of}% +result of a mere lucky guess. It arose from +his correct ideas in connection with inertia +and mass. The first law of motion, as following +Newton we now enunciate it, is---Every +\index{Newton}% +body continues in its state of rest or of uniform +\PageSep{44} +motion in a straight line, except so far +as it is compelled by impressed force to +change that state. This law is more than a +dry formula: it is also a pæan of triumph +over defeated heretics. The point at issue +can be understood by deleting from the law +the phrase ``or of uniform motion in a straight +line.'' We there obtain what might be taken +as the Aristotelian opposition formula: +``Every body continues in its state of rest +except so far as it is compelled by impressed +force to change that state.'' + +In this last false formula it is asserted that, +apart from force, a body continues in a state +of rest; and accordingly that, if a body is +moving, a force is required to sustain the +motion; so that when the force ceases, the +motion ceases. The true Newtonian law +takes diametrically the opposite point of view. +The state of a body unacted on by force is +that of uniform motion in a straight line, and +no external force or influence is to be looked +for as the cause, or, if you like to put it so, as +the invariable accompaniment of this uniform +rectilinear motion. Rest is merely a particular +case of such motion, merely when the +velocity is and remains zero. Thus, when a +body is moving, we do not seek for any external +influence except to explain changes in +the rate of the velocity or changes in its direction. +So long as the body is moving at the +\PageSep{45} +same rate and in the same direction there is +no need to invoke the aid of any forces. + +The difference between the two points of +view is well seen by reference to the theory of +the motion of the planets. Copernicus, a +\index{Copernicus}% +Pole, born at Thorn in West Prussia (born +1473, died 1543), showed how much simpler +it was to conceive the planets, including the +\Figure[2.25in]{4} +earth as revolving round the sun in orbits +which are nearly circular; and later, Kepler, +\index{Kepler}% +a German mathematician, in the year 1609 +proved that, in fact, the orbits are practically +ellipses, that is, a special sort of oval curves +\index{Ellipse}% +which we will consider later in more detail. +Immediately the question arose as to what +are the forces which preserve the planets in +this motion. According to the old false view, +\PageSep{46} +held by Kepler, the actual velocity itself required +\index{Kepler}% +preservation by force. Thus he looked +for tangential forces as in the accompanying +figure~(\FigNum{4}). But according to the Newtonian +law, apart from some force the planet would +move for ever with its existing velocity in a +straight line, and thus depart entirely from +the sun. Newton, therefore, had to search +\index{Newton}% +for a force which would bend the motion +\Figure[2.25in]{5} +round into its elliptical orbit. This he showed +must be a force directed towards the sun as in +the next figure~(\FigNum{5}). In fact, the force is the +gravitational attraction of the sun acting +according to the law of the inverse square of +the distance, which has been stated above. + +The science of mechanics rose among the +\index{Mechanics}% +Greeks from a consideration of the theory of +the mechanical advantage obtained by the use +\PageSep{47} +\index{Dynamical Explanation|EtSeq}% +of a lever, and also from a consideration of +various problems connected with the weights +of bodies. It was finally put on its true basis +at the end of the sixteenth and during the +seventeenth centuries, as the preceding account +shows, partly with the view of explaining +the theory of falling bodies, but chiefly +in order to give a scientific theory of planetary +motions. But since those days dynamics has +taken upon itself a more ambitious task, and +now claims to be the ultimate science of which +the others are but branches. The claim +amounts to this: namely, that the various +qualities of things perceptible to the senses +are merely our peculiar mode of appreciating +changes in position on the part of things +existing in space. For example, suppose we +look at Westminster Abbey. It has been +standing there, grey and immovable, for centuries +past. But, according to modern scientific +theory, that greyness, which so heightens +our sense of the immobility of the building, is +itself nothing but our way of appreciating the +rapid motions of the ultimate molecules, which +form the outer surface of the building and +communicate vibrations to a substance called +the ether. Again we lay our hands on its +stones and note their cool, even temperature, +so symbolic of the quiet repose of the building. +But this feeling of temperature simply marks +our sense of the transfer of heat from the +\PageSep{48} +hand to the stone, or from the stone to the +hand; and, according to modern science, +heat is nothing but the agitation of the molecules +of a body. Finally, the organ begins +playing, and again sound is nothing but the +result of motions of the air striking on the +drum of the ear. + +Thus the endeavour to give a dynamical +explanation of phenomena is the attempt to +explain them by statements of the general +form, that such and such a substance or body +was in this place and is now in that place. +Thus we arrive at the great basal idea of +modern science, that all our sensations are +the result of comparisons of the changed +configurations of things in space at various +times. It follows therefore, that the laws +of motion, that is, the laws of the changes +of configurations of things, are the ultimate +laws of physical science. + +In the application of mathematics to the +investigation of natural philosophy, science +does systematically what ordinary thought +does casually. When we talk of a chair, we +usually mean something which we have been +seeing or feeling in some way; though most +of our language will presuppose that there +is something which exists independently of +our sight or feeling. Now in mathematical +physics the opposite course is taken. The +chair is conceived without any reference to +\PageSep{49} +\index{Variable, The}% +anyone in particular, or to any special modes +of perception. The result is that the chair +becomes in thought a set of molecules in space, +or a group of electrons, a portion of the ether +in motion, or however the current scientific +ideas describe it. But the point is that +science reduces the chair to things moving in +space and influencing each other's motions. +Then the various elements or factors which +enter into a set of circumstances, as thus +conceived, are merely the things, like lengths +of lines, sizes of angles, areas, and volumes, by +which the positions of bodies in space can be +settled. Of course, in addition to these geometrical +elements the fact of motion and +change necessitates the introduction of the +rates of changes of such elements, that is to +say, velocities, angular velocities, accelerations, +and suchlike things. Accordingly, mathematical +physics deals with correlations between +variable numbers which are supposed +to represent the correlations which exist in +nature between the measures of these geometrical +elements and of their rates of change. +But always the mathematical laws deal with +variables, and it is only in the occasional +testing of the laws by reference to experiments, +or in the use of the laws for special +predictions that definite numbers are substituted. + +The interesting point about the world as +\PageSep{50} +thus conceived in this abstract way throughout +the study of mathematical physics, where +only the positions and shapes of things are +considered together with their changes, is that +the events of such an abstract world are sufficient +to ``explain'' our sensations. When we +hear a sound, the molecules of the air have +been agitated in a certain way: given the +agitation, or air-waves as they are called, all +normal people hear sound; and if there are +no air-waves, there is no sound. And, similarly, +a physical cause or origin, or parallel +event (according as different people might like +to phrase it) underlies our other sensations. +Our very thoughts appear to correspond to +conformations and motions of the brain; injure +the brain and you injure the thoughts. +Meanwhile the events of this physical universe +succeed each other according to the mathematical +laws which ignore all special sensations +and thoughts and emotions. + +Now, undoubtedly, this is the general aspect +of the relation of the world of mathematical +physics to our emotions, sensations, and +thoughts; and a great deal of controversy +has been occasioned by it and much ink +spilled. We need only make one remark. The +whole situation has arisen, as we have seen, +from the endeavour to describe an external +world ``explanatory'' of our various individual +sensations and emotions, but a world +\PageSep{51} +also, not essentially dependent upon any +particular sensations or upon any particular +individual. Is such a world merely but +one huge fairy tale? But fairy tales are +fantastic and arbitrary: if in truth there +be such a world, it ought to submit itself +to an exact description, which determines +accurately its various parts and their mutual +relations. Now, to a large degree, this +scientific world does submit itself to this +test and allow its events to be explored +and predicted by the apparatus of abstract +mathematical ideas. It certainly seems that +here we have an inductive verification of +our initial assumption. It must be admitted +that no inductive proof is conclusive; but +if the whole idea of a world which has +existence independently of our particular perceptions +of it be erroneous, it requires careful +explanation why the attempt to characterise +it, in terms of that mathematical remnant +of our ideas which would apply to it, should +issue in such a remarkable success. + +It would take us too far afield to enter into +\index{Parallelogram Law|EtSeq}% +\index{Vectors|EtSeq}% +a detailed explanation of the other laws of +motion. The remainder of this chapter must +be devoted to the explanation of remarkable +ideas which are fundamental, both to mathematical +physics and to pure mathematics: +these are the ideas of vector quantities and +the parallelogram law for vector addition. We +\PageSep{52} +have seen that the essence of motion is that +a body was at~$A$ and is now at~$C$. This transference +from $A$ to~$C$ requires two distinct +elements to be settled before it is completely +determined, namely its magnitude (\ie\ the +length~$AC$) and its direction. Now anything, +like this transference, which is completely +given by the determination of a magnitude +\Figure[2in]{6} +and a direction is called a vector. For +example, a velocity requires for its definition +the assignment of a magnitude and of a +direction. It must be of so many miles per +hour in such and such a direction. The existence +and the independence of these two +elements in the determination of a velocity +are well illustrated by the action of the captain +of a ship, who communicates with different subordinates +respecting them: he tells the chief +engineer the number of knots at which he is +to steam, and the helmsman the compass +\PageSep{53} +bearing of the course which he is to keep. +Again the rate of change of velocity, that is +velocity added per unit time, is also a vector +quantity: it is called the acceleration. Similarly +a force in the dynamical sense is another +vector quantity. Indeed, the vector nature +of forces follows at once according to dynamical +principles from that of velocities and +accelerations; but this is a point which we +need not go into. It is sufficient here to say +that a force acts on a body with a certain +magnitude in a certain direction. + +Now all vectors can be graphically represented +by straight lines. All that has to be +done is to arrange: (i)~a scale according to +which units of length correspond to units of +magnitude of the vector---for example, one +inch to a velocity of $10$~miles per~hour in the +case of velocities, and one inch to a force of +$10$~tons weight in the case of forces---and (ii)~a +direction of the line on the diagram corresponding +to the direction of the vector. Then +a line drawn with the proper number of inches +of length in the proper direction represents the +required vector on the arbitrarily assigned scale +of magnitude. This diagrammatic representation +of vectors is of the first importance. By +its aid we can enunciate the famous ``parallelogram +law'' for the addition of vectors of the +same kind but in different directions. + +Consider the vector~$AC$ in \Fig[figure]{6} as representative +\PageSep{54} +\index{Transportation, Vector of|EtSeq}% +of the changed position of a body +from $A$ to~$C$: we will call this the vector of +transportation. It will be noted that, if the +reduction of physical phenomena to mere +changes in positions, as explained above, is +correct, all other types of physical vectors are +really reducible in some way or other to this +single type. Now the final transportation +from $A$ to~$C$ is equally well effected by a +transportation from $A$ to~$B$ and a transportation +from $B$ to~$C$, or, completing the parallelogram +$ABCD$, by a transportation from $A$ to~$D$ +and a transportation from $D$ to~$C$. These +transportations as thus successively applied +are said to be added together. This is simply +a definition of what we mean by the addition +of transportations. Note further that, considering +parallel lines as being lines drawn in +the same direction, the transportations $B$~to~$C$ +and $A$~to~$D$ may be conceived as the same +transportation applied to bodies in the two +initial positions $B$ and~$A$. With this conception +we may talk of the transportation +$A$~to~$D$ as applied to a body in any position, +for example at~$B$. Thus we may say that +the transportation $A$~to~$C$ can be conceived +as the sum of the two transportations $A$~to~$B$ +and $A$~to~$D$ applied in any order. Here +we have the parallelogram law for the addition +of transportations: namely, if the +transportations are $A$~to~$B$ and $A$~to~$D$, +\PageSep{55} +complete the parallelogram $ABCD$, and then +the sum of the two is the diagonal~$AC$. + +All this at first sight may seem to be +very artificial. But it must be observed +that nature itself presents us with the idea. +For example, a steamer is moving in the +direction~$AD$ (\Chg{cf.}{\cf}\ \Fig[fig.]{6}) and a man walks +across its deck. If the steamer were still, +in one minute he would arrive at~$B$; but +during that minute his starting point~$A$ on +the deck has moved to~$D$, and his path on +the deck has moved from $AB$ to~$DC$. So +that, in fact, his transportation has been from +$A$ to~$C$ over the surface of the sea. It is, +however, presented to us analysed into the +sum of two transportations, namely, one from +$A$ to~$B$ relatively to the steamer, and one +from $A$ to~$D$ which is the transportation of +the steamer. + +By taking into account the element of time, +namely one minute, this diagram of the man's +transportation~$AC$ represents his velocity. +For if $AC$~represented so many feet of transportation, +it now represents a transportation +of so many feet per minute, that is to say, it +represents the velocity of the man. Then +$AB$ and $AD$ represent two velocities, namely, +his velocity relatively to the steamer, and the +velocity of the steamer, whose ``sum'' makes +up his complete velocity. It is evident that +diagrams and definitions concerning transportations +\PageSep{56} +are turned into diagrams and definitions +concerning velocities by conceiving +the diagrams as representing transportations +per unit time. Again, diagrams and definitions +concerning velocities are turned into +diagrams and definitions concerning accelerations +\Figure[3in]{7} +by conceiving the diagrams as representing +velocities added per unit time. + +Thus by the addition of vector velocities +and of vector accelerations, we mean the +addition according to the parallelogram law. + +Also, according to the laws of motion a +force is fully represented by the vector +acceleration it produces in a body of given +mass. Accordingly, forces will be said to be +added when their joint effect is to be reckoned +according to the parallelogram law. + +Hence for the fundamental vectors of +\PageSep{57} +science, namely transportations, velocities, +and forces, the addition of any two of the same +kind is the production of a ``resultant'' +vector according to the rule of the parallelogram +law. + +By far the simplest type of parallelogram +is a rectangle, and in pure mathematics it is +\index{Rectangle}% +the relation of the single vector~$AC$ to the +two component vectors, $AB$~and~$AD$, at right +angles (\Chg{cf.}{\cf}\ \Fig[fig.]{7}), which is continually recurring. +Let $x$,~$y$, and $r$~units represent the +lengths of $AB$,~$AD$, and~$AC$, and let $m$~units +of angle represent the magnitude of the angle +$BAC$. Then the relations between $x$,~$y$,~$r$, +and~$m$, in all their many aspects are the continually +recurring topic of pure mathematics; +and the results are of the type required for +application to the fundamental vectors of +mathematical physics. This diagram is the +chief bridge over which the results of pure +mathematics pass in order to obtain application +to the facts of nature. +\PageSep{58} + + +\Chapter{V}{The Symbolism of Mathematics} + +\First{We} now return to pure mathematics, and +consider more closely the apparatus of ideas +out of which the science is built. Our first +concern is with the symbolism of the science, +and we start with the simplest and universally +known symbols, namely those of arithmetic. + +Let us assume for the present that we have +\index{Arabic Notation|EtSeq}% +sufficiently clear ideas about the integral +numbers, represented in the Arabic notation +by $0$,~$1$, $2$,~\dots, $9$, $10$, $11$,~\dots\Add{,} $100$, $101$,~\dots\ and +so on. This notation was introduced into +Europe through the Arabs, but they apparently +obtained it from Hindoo sources. The +first known work\footnote + {For the detailed historical facts relating to pure + mathematics, I am chiefly indebted to \Title{A Short History +\index{Ball, W. W. R.}% + of Mathematics}, by W.~W.~R. Ball.} +% [** TN: http://www.gutenberg.org/ebooks/31246] +in which it is systematically +explained is a work by an Indian mathematician, +Bhaskara (born 1114~\AD). But +\index{Bhaskara}% +the actual numerals can be traced back to the +seventh century of our era, and perhaps were +originally invented in Tibet. For our present +\PageSep{59} +purposes, however, the history of the notation +is a detail. The interesting point to notice +is the admirable illustration which this +numeral system affords of the enormous importance +of a good notation. By relieving +the brain of all unnecessary work, a good +notation sets it free to concentrate on more +advanced problems, and in effect increases +the mental power of the race. Before the +introduction of the Arabic notation, multiplication +was difficult, and the division even of +integers called into play the highest mathematical +faculties. Probably nothing in the +modern world would have more astonished a +Greek mathematician than to learn that, under +the influence of compulsory education, a +large proportion of the population of Western +Europe could perform the operation of +division for the largest numbers. This fact +would have seemed to him a sheer impossibility. +The consequential extension of +the notation to decimal fractions was not +accomplished till the seventeenth century. +Our modern power of easy reckoning with +decimal fractions is the almost miraculous +result of the gradual discovery of a perfect +notation. + +Mathematics is often considered a difficult +and mysterious science, because of the +numerous symbols which it employs. Of +course, nothing is more incomprehensible than +\PageSep{60} +a symbolism which we do not understand. +Also a symbolism, which we only partially +understand and are unaccustomed to use, is +difficult to follow. In exactly the same way +the technical terms of any profession or trade +are incomprehensible to those who have never +been trained to use them. But this is not +because they are difficult in themselves. On +the contrary they have invariably been introduced +to make things easy. So in mathematics, +granted that we are giving any serious +attention to mathematical ideas, the symbolism +is invariably an immense simplification. +It is not only of practical use, but is +of great interest. For it represents an analysis +of the ideas of the subject and an almost +pictorial representation of their relations to +each other. If anyone doubts the utility of +symbols, let him write out in full, without any +symbol whatever, the whole meaning of the +following equations which represent some of +\index{Algebra, Fundamental Laws of}% +the fundamental laws of algebra\footnotemark:--- +\footnotetext{\Chg{Cf.}{\Cf}\ Note~A, \Pageref{noteA}.\Pagelabel{60}} +%[** TN: left-aligned in the original] +\begin{gather*} +x + y = y + x\Add{,} +\Tag{(1)} \\ +(x + y) + z = x + (y + z)\Add{,} +\Tag{(2)} \\ +x × y = y × x\Add{,} +\Tag{(3)} \\ +(x × y) × z = x × (y × z)\Add{,} +\Tag{(4)} \\ +x × (y + z) = (x × y) + (x × z)\Add{.} +\Tag{(5)} +\end{gather*} + +Here \Eq{(1)}~and \Eq{(2)} are called the commutative +and associative laws for addition, \Eq{(3)}~and \Eq{(4)} +\PageSep{61} +are the commutative and associative laws for +multiplication, and \Eq{(5)}~is the distributive law +relating addition and multiplication. For example, +without symbols, \Eq{(1)}~becomes: If a +second number be added to any given number +the result is the same as if the first given +number had been added to the second number. + +This example shows that, by the aid of symbolism, +we can make transitions in reasoning +almost mechanically by the eye, which otherwise +would call into play the higher faculties +of the brain. + +It is a profoundly erroneous truism, repeated +by all copy-books and by eminent people when +they are making speeches, that we should +cultivate the habit of thinking of what we are +doing. The precise opposite is the case. +Civilization advances by extending the number +of important operations which we can +perform without thinking about them. Operations +of thought are like cavalry charges in +a battle---they are strictly limited in number, +they require fresh horses, and must only +be made at decisive moments. + +One very important property for symbolism +to possess is that it should be concise, so as to +be visible at one glance of the eye and to be +rapidly written. Now we cannot place symbols +more concisely together than by placing +them in immediate juxtaposition. In a good +symbolism therefore, the juxtaposition of important +\PageSep{62} +symbols should have an important +meaning. This is one of the merits of the +Arabic notation for numbers; by means of +ten symbols, $0$,~$1$, $2$, $3$, $4$, $5$, $6$, $7$, $8$,~$9$, and by +simple juxtaposition it symbolizes any number +whatever. Again in algebra, when we have +two variable numbers $x$ and~$y$, we have to +make a choice as to what shall be denoted by +their juxtaposition~$xy$. Now the two most +important ideas on hand are those of addition +and multiplication. Mathematicians have +chosen to make their symbolism more concise +by defining $xy$ to stand for $x × y$. Thus the +laws \Eq{(3)},~\Eq{(4)}, and~\Eq{(5)} above are in general +written, +\[ +xy = yx,\quad +(xy)z = x(yz),\quad +x(y + z) = xy + xz, +\] +thus securing a great gain in conciseness. +The same rule of symbolism is applied to the +juxtaposition of a definite number and a variable: +we write~$3x$ for $3 × x$, and $30x$ for $30 × x$. + +It is evident that in substituting definite +numbers for the variables some care must be +taken to restore the~$×$, so as not to conflict +with the Arabic notation. Thus when we +substitute $2$~for~$x$ and $3$~for~$y$ in~$xy$, we must +write $2 × 3$ for~$xy$, and not~$23$ which means +$20 + 3$. + +It is interesting to note how important for +the development of science a modest-looking +symbol may be. It may stand for the emphatic +presentation of an idea, often a very +\PageSep{63} +subtle idea, and by its existence make it easy +to exhibit the relation of this idea to all the +complex trains of ideas in which it occurs. +For example, take the most modest of all +symbols, namely,~$0$, which stands for the \emph{number} +\index{Zero|EtSeq}% +zero. The Roman notation for numbers +had no symbol for zero, and probably most +mathematicians of the ancient world would +have been horribly puzzled by the idea of the +number zero. For, after all, it is a very +subtle idea, not at all obvious. A great deal +of discussion on the meaning of the zero of +quantity will be found in philosophic works. +Zero is not, in real truth, more difficult or +subtle in idea than the other cardinal numbers. +What do we mean by~$1$ or by~$2$, or by~$3$? +But we are familiar with the use of these ideas, +though we should most of us be puzzled to +give a clear analysis of the simpler ideas +which go to form them. The point about zero +is that we do not need to use it in the operations +of daily life. No one goes out to buy +zero fish. It is in a way the most civilized +of all the cardinals, and its use is only forced +on us by the needs of cultivated modes of +thought. Many important services are rendered +by the symbol~$0$, which stands for the +number zero. + +The symbol developed in connection with +the Arabic notation for numbers of which it +is an essential part. For in that notation the +\PageSep{64} +value of a digit depends on the position in +which it occurs. Consider, for example, the +digit~$5$, as occurring in the numbers $25$, $51$, +$3512$, $5213$. In the first number~$5$ stands for +five, in the second number $5$~stands for fifty, +in the third number for five hundred, and in +the fourth number for five thousand. Now, +when we write the number fifty-one in the +symbolic form~$51$, the digit~$1$ pushes the digit~$5$ +along to the second place (reckoning from +right to left) and thus gives it the value fifty. +But when we want to symbolize fifty by itself, +we can have no digit~$1$ to perform this service; +we want a digit in the units place to add +nothing to the total and yet to push the~$5$ +along to the second place. This service is +performed by~$0$, the symbol for zero. It is +extremely probable that the men who introduced +for this purpose had no definite conception +in their minds of the number zero. +They simply wanted a mark to symbolize the +fact that nothing was contributed by the +digit's place in which it occurs. The idea of +zero probably took shape gradually from a +desire to assimilate the meaning of this mark +to that of the marks, $1$, $2$,~\dots\Add{,}~$9$, which do represent +cardinal numbers. This would not +represent the only case in which a subtle idea +has been introduced into mathematics by a +symbolism which in its origin was dictated by +practical convenience. +\PageSep{65} + +Thus the first use of~$0$ was to make the +arable notation possible---no slight service. +We can imagine that when it had been introduced +for this purpose, practical men, of the +sort who dislike fanciful ideas, deprecated the +silly habit of identifying it with a number +zero. But they were wrong, as such men +always are when they desert their proper +function of masticating food which others have +prepared. For the next service performed by +the symbol~$0$ essentially depends upon assigning +to it the function of representing the +number zero. + +This second symbolic use is at first sight +so absurdly simple that it is difficult to make +a beginner realize its importance. Let us +start with a simple example. In \ChapRef{II}.\ +we mentioned the correlation between two +variable numbers $x$ and $y$ represented by the +equation $x + y = 1$. This can be represented +in an indefinite number of ways; for example, +$x = 1 - y$, $y = 1 - x$, $2x + 3y - 1 = x + 2y$, and so +on. But the important way of stating it is +\[ +x + y - 1 = 0. +\] +Similarly the important way of writing the +equation $x = 1$ is $x - 1 = 0$, and of representing +the equation $3x - 2 = 2x^{2}$ is $2x^{2} - 3x + 2 = 0$. +The point is that all the symbols which represent +variables, \eg\ $x$~and~$y$, and the symbols +\PageSep{66} +representing some definite number other than +zero, such as $1$ or $2$ in the examples above, +are written on the left-hand side, so that the +whole left-hand side is equated to the number +zero. The first man to do this is said to +have been Thomas Harriot, born at Oxford +\index{Harriot, Thomas}% +in 1560 and died in~1621. But what is the +importance of this simple symbolic procedure? +It made possible the growth of the +\index{Form, Algebraic|EtSeq}% +modern conception of \emph{algebraic form}. + +This is an idea to which we shall have continually +to recur; it is not going too far to +say that no part of modern mathematics can +be properly understood without constant recurrence +to it. The conception of form is +so general that it is difficult to characterize +it in abstract terms. At this stage we shall +do better merely to consider examples. Thus +the equations $2x - 3 = 0$, $x - 1 = 0$, $5x - 6 = 0$, +are all equations of the same form, namely, +equations involving one unknown~$x$, which is +not multiplied by itself, so that $x^{2}$, $x^{3}$,~etc., do +not appear. Again $3x^{2} - 2x + 1 = 0$, $x^{2} - 3x + 2 = 0$, +$x^{2} - 4 = 0$, are all equations of the same +form, namely, equations involving one unknown~$x$ +in which $x × x$, that is~$x^{2}$, appears. These +equations are called quadratic equations. +Similarly cubic equations, in which $x^{3}$~appears, +yield another form, and so on. Among the +three quadratic equations given above there +is a minor difference between the last equation, +\PageSep{67} +$x^{2} - 4 = 0$, and the preceding two equations, +due to the fact that~$x$ (as distinct +from~$x^{2}$) does not appear in the last and +does in the other two. This distinction is +very unimportant in comparison with the +great fact that they are all three quadratic +equations. + +Then further there are the forms of equation +stating correlations between two variables; +for example, $x + y - 1 = 0$, $2x + 3y - 8 = 0$, and +so on. These are examples of what is called +the \emph{linear} form of equation. The reason for +this name of ``linear'' is that the graphic +method of representation, which is explained +at the end of \ChapRef{II}\Add{.}, always represents +such equations by a straight line. Then there +are other forms for two variables---for example, +the quadratic form, the cubic form, and so on. +But the point which we here insist upon is +that this study of form is facilitated, and, +indeed, made possible, by the standard method +of writing equations with the symbol~$0$ on +the right-hand side. + +There is yet another function performed by~$0$ +in relation to the study of form. Whatever +number $x$ may be, $0 × x = 0$, and $x + 0 = x$. +By means of these properties minor differences +of form can be assimilated. Thus the +difference mentioned above between the quadratic +equations $x^{2} - 3x + 2 = 0$, and $x^{2} - 4 = 0$, +can be obliterated by writing the latter +\PageSep{68} +equation in the form $x^{2} + (0 × x) - 4 = 0$. For, +by the laws stated above, $x^{2} + (0 × x) - 4 = +x^{2} + 0 - 4 = x^{2} - 4$. Hence the equation $x^{2} - 4 = 0$\Typo{,}{} +is merely representative of a particular +class of quadratic equations and belongs to +the same general form as does $x^{2} - 3x + 2 = 0$. + +For these three reasons the symbol~$0$, representing +the number zero, is essential to +modern mathematics. It has rendered possible +types of investigation which would have +been impossible without it. + +The symbolism of mathematics is in truth +the outcome of the general ideas which +dominate the science. We have now two +such general ideas before us, that of the variable +and that of algebraic form. The junction +of these concepts has imposed on mathematics +another type of symbolism almost quaint in +its character, but none the less effective. We +have seen that an equation involving two +variables, $x$~and~$y$, represents a particular +correlation between the pair of variables. +Thus $x + y - 1 = 0$ represents one definite correlation, +and $3x + 2y - 5 = 0$ represents another +definite correlation between the variables $x$ +and~$y$; and both correlations have the form +of what we have called linear correlations. +But now, how can we represent \emph{any} linear +correlation between the variable numbers $x$ +and~$y$? Here we want to symbolize \emph{any} +linear correlation; just as $x$~symbolizes \emph{any} +\PageSep{69} +number. This is done by turning the numbers +which occur in the definite correlation $3x + 2y - 5 = 0$ +into letters. We obtain $ax + by - c = 0$. +Here $a$,~$b$,~$c$, stand for variable numbers just +as do $x$ and~$y$: but there is a difference in the +use of the two sets of variables. We study +the general properties of the relationship between +$x$ and $y$ while $a$,~$b$, and~$c$ have unchanged +values. We do not determine what +the values of $a$,~$b$, and~$c$ are; but whatever +they are, they remain fixed while we study +the relation between the variables $x$ and $y$ +for the whole group of possible values of $x$ +and~$y$. But when we have obtained the properties +of this correlation, we note that, because +$a$,~$b$, and~$c$ have not in fact been determined, +we have proved properties which must +belong to \emph{any} such relation. Thus, by now +varying $a$,~$b$, and~$c$, we arrive at the idea that +$ax + by - c = 0$ represents a variable linear +correlation between $x$ and~$y$. In comparison +with $x$ and~$y$, the three variables $a$,~$b$, and~$c$ +are called constants. Variables used in this +\index{Constants}% +way are sometimes also called parameters. +\index{Parameters}% + +Now, mathematicians habitually save the +trouble of explaining which of their variables +are to be treated as ``constants,'' and which +as variables, considered as correlated in their +equations, by using letters at the end of the +alphabet for the ``variable'' variables, and +letters at the beginning of the alphabet for +\PageSep{70} +the ``constant'' variables, or parameters. +The two systems meet naturally about the +middle of the alphabet. Sometimes a word +or two of explanation is necessary; but as a +matter of fact custom and common sense are +usually sufficient, and surprisingly little confusion +is caused by a procedure which seems +so lax. + +The result of this continual elimination of +definite numbers by successive layers of parameters +is that the amount of arithmetic performed +by mathematicians is extremely small. +Many mathematicians dislike all numerical +computation and are not particularly expert +at it. The territory of arithmetic ends where +the two ideas of ``variables'' and of ``algebraic +form'' commence their sway. +\PageSep{71} + + +\Chapter{VI}{Generalizations of Number} + +\First{One} great peculiarity of mathematics is the +\index{Fractions|EtSeq}% +set of allied ideas which have been invented +in connection with the integral numbers from +which we started. These ideas may be called +extensions or generalizations of number. In +the first place there is the idea of fractions. +The earliest treatise on arithmetic which we +possess was written by an Egyptian priest, +named Ahmes, between 1700~\BC\ and 1100~\BC, +\index{Ahmes}% +and it is probably a copy of a much older +work. It deals largely with the properties of +fractions. It appears, therefore, that this +concept was developed very early in the history +of mathematics. Indeed the subject is +a very obvious one. To divide a field into +three equal parts, and to take two of the +parts, must be a type of operation which had +often occurred. Accordingly, we need not be +surprised that the men of remote civilizations +were familiar with the idea of two-thirds, and +\PageSep{72} +with allied notions. Thus as the first generalization +of number we place the concept of +fractions. The Greeks thought of this subject +rather in the form of ratio, so that a +Greek would naturally say that a line of +two feet in length bears to a line of three +feet in length the ratio of $2$~to~$3$. Under +the influence of our algebraic notation we +would more often say that one line was +two-thirds of the other in length, and would +think of two-thirds as a numerical multiplier. + +In connection with the theory of ratio, or +\index{Incommensurable Ratios|EtSeq}% +\index{Ratio|EtSeq}% +fractions, the Greeks made a great discovery, +which has been the occasion of a large amount +of philosophical as well as mathematical +thought. They found out the existence of +``incommensurable'' ratios. They proved, +in fact, during the course of their geometrical +investigations that, starting with a line of any +length, other lines must exist whose lengths +do not bear to the original length the ratio +of any pair of integers---or, in other words, +that lengths exist which are not any exact +fraction of the original length. + +For example, the diagonal of a square cannot +be expressed as any fraction of the side of the +same square; in our modern notation the +length of the diagonal is $\sqrt{2}$~times the length +of the side. But there is no fraction which +exactly represents~$\sqrt{2}$. We can approximate +\PageSep{73} +to~$\sqrt{2}$ as closely as we like, but we never +exactly reach its value. For example, $\dfrac{49}{25}$~is +just less than~$2$, and $\dfrac{9}{4}$~is greater than~$2$, so +that $\sqrt{2}$~lies between $\dfrac{7}{5}$ and~$\dfrac{3}{2}$. But the best +systematic way of approximating to~$\sqrt{2}$ in +obtaining a series of decimal fractions, each +bigger than the last, is by the ordinary method +of extracting the square root; thus the series +is $1$, $\dfrac{14}{10}$, $\dfrac{141}{100}$, $\dfrac{1414}{1000}$, and so on. + +Ratios of this sort are called by the Greeks +incommensurable. They have excited from +the time of the Greeks onwards a great deal +of philosophic discussion, and the difficulties +connected with them have only recently been +cleared up. + +We will put the incommensurable ratios +\index{Real Numbers|EtSeq}% +with the fractions, and consider the whole +set of integral numbers, fractional numbers, +and incommensurable numbers as forming +one class of numbers which we will call ``real +numbers.'' We always think of the real +numbers as arranged in order of magnitude, +starting from zero and going upwards, and +becoming indefinitely larger and larger as we +proceed. The real numbers are conveniently +\PageSep{74} +represented by points on a line. Let $OX$ be +\Diagram{pg76} +any line bounded at~$O$ and stretching away indefinitely +in the direction~$OX$. Take any convenient +point,~$A$, on it, so that $OA$~represents +the unit length; and divide off lengths $AB$, +$BC$, $CD$, and so on, each equal to~$OA$. Then +the point~$O$ represents the number~$0$, $A$~the +number~$1$, $B$~the number~$2$, and so on. In +fact the number represented by any point is +the measure of its distance from~$O$, in terms +of the unit length~$OA$. The points between +$O$ and~$A$ represent the proper fractions and +the incommensurable numbers less than~$1$; +the middle point of~$OA$ represents~$\dfrac{1}{2}$, that of~$AB$ +represents~$\dfrac{3}{2}$, that of~$BC$ represents~$\dfrac{5}{2}$, and +so on. In this way every point on~$OX$ represents +some one real number, and every real +number is represented by some one point on~$OX$. + +The series (or row) of points along~$OX$, +\index{Series|EtSeq}% +starting from~$O$ and moving regularly in the +direction from $O$ to~$X$, represents the real +numbers as arranged in an ascending order +\PageSep{75} +of size, starting from zero and continually +increasing as we go on. + +All this seems simple enough, but even at +\index{Order, Type of|EtSeq}% +this stage there are some interesting ideas to +be got at by dwelling on these obvious facts. +Consider the series of points which represent +the integral numbers only, namely, the points, +$O$,~$A$, $B$, $C$, $D$,~etc. Here there is a first point~$O$, +a definite next point,~$A$, and each point, +such as $A$ or~$B$, has one definite immediate +predecessor and one definite immediate successor, +with the exception of~$O$, which has no +predecessor; also the series goes on indefinitely +without end. This sort of order is +called the type of order of the integers; its +essence is the possession of next-door neighbours +on either side with the exception of +No.~1 in the row. Again consider the integers +and fractions together, omitting the points +which correspond to the incommensurable +ratios. The sort of serial order which we now +obtain is quite different. There is a first +term~$O$; but no term has any immediate predecessor +or immediate successor. This is +easily seen to be the case, for between any +two fractions we can always find another +fraction intermediate in value. One very +simple way of doing this is to add the fractions +together and to halve the result. For example, +%[** textstyle fractions start here] +between $\frac{2}{3}$ and~$\frac{3}{4}$, the fraction $\frac{1}{2}(\frac{2}{3} + \frac{3}{4})$, +that is~$\frac{17}{24}$, lies; and between $\frac{2}{3}$ and $\frac{17}{24}$ the +\PageSep{76} +\index{Compact Series}% +fraction $\frac{1}{2}(\frac{2}{3} + \frac{17}{24})$, that is~$\frac{33}{48}$, lies; and so on +indefinitely. Because of this property the +series is said to be ``compact.'' There is no +end point to the series, which increases indefinitely +without limit as we go along the +line~$OX$. It would seem at first sight as +though the type of series got in this way from +the fractions, always including the integers, +would be the same as that got from all the +real numbers, integers, fractions, and incommensurables +taken together, that is, from all +the points on the line~$OX$. All that we have +hitherto said about the series of fractions +applies equally well to the series of all real +numbers. But there are important differences +which we now proceed to develop. The +absence of the incommensurables from the +series of fractions leaves an absence of endpoints +to certain classes. Thus, consider the +incommensurable~$\sqrt{2}$. In the series of real +numbers this stands between all the numbers +whose squares are less than~$2$, and all the +numbers whose squares are greater than~$2$. +But keeping to the series of fractions alone +and not thinking of the incommensurables, so +that we cannot bring in~$\sqrt{2}$, there is no fraction +which has the property of dividing off +the series into two parts in this way, \ie\ so +that all the members on one side have their +squares less than~$2$, and on the other side +greater than~$2$. Hence in the series of fractions +\PageSep{77} +there is a quasi-gap where $\sqrt{2}$~ought to +come. This presence of quasi-gaps in the +series of fractions may seem a small matter; +but any mathematician, who happens to read +this, knows that the possible absence of limits +\index{Limits}% +or maxima to a class of numbers, which yet +does not spread over the whole series of numbers, +is no small evil. It is to avoid this +difficulty that recourse is had to the incommensurables, +so as to obtain a complete series +with no gaps. + +There is another even more fundamental +difference between the two series. We can +rearrange the fractions in a series like that of +the integers, that is, with a first term, and +such that each term has an immediate successor +and (except the first term) an immediate +predecessor. We can show how this can be +done. Let every term in the series of fractions +and integers be written in the fractional form +by writing $\frac{1}{1}$ for~$1$, $\frac{2}{1}$ for~$2$, and so on for all the +integers, excluding~$0$. Also for the moment +we will reckon fractions which are equal in +value but not reduced to their lowest terms +as distinct; so that, for example, until further +notice $\frac{2}{3}$, $\frac{4}{6}$, $\frac{6}{9}$, $\frac{8}{12}$, etc., are all reckoned as distinct. +Now group the fractions into classes +by adding together the numerator and denominator +of each term. For the sake of +brevity call this sum of the numerator and +denominator of a fraction its index. Thus $7$~is +\PageSep{78} +the index of~$\frac{4}{3}$, and also of~$\frac{3}{4}$, and of~$\frac{2}{5}$. Let +the fractions in each class be all fractions +which have some specified index, which may +therefore also be called the class index. Now +arrange these classes in the order of magnitude +of their indices. The first class has +the index~$2$, and its only member is~$\frac{1}{1}$; the +second class has the index~$3$, and its members +are $\frac{1}{2}$ and~$\frac{2}{1}$; the third class has the index~$4$, +and its members are $\frac{1}{3}$, $\frac{2}{2}$,~$\frac{3}{1}$; the fourth +class has the index~$5$, and its members are +$\frac{1}{4}$, $\frac{2}{3}$, $\frac{3}{2}$,~$\frac{4}{1}$; and so on. It is easy to see that +the number of members (still including fractions +not in their lowest terms) belonging to +any class is one less than its index. Also the +members of any one class can be arranged +in order by taking the first member to be the +fraction with numerator~$1$, the second member +to have the numerator~$2$, and so on, up to~$(n - 1)$ +where $n$~is the index. Thus for the +class of index~$n$, the members appear in the +order\Typo{.}{} +%[** TN: Reformatted slightly from the original] +\[ +\frac{1}{n - 1},\quad +\frac{2}{n - 2},\quad +\frac{3}{n - 3},\ +\dots,\quad +\frac{n - 1}{1}. +\] +The members +of the first four classes have in fact been +mentioned in this order. Thus the whole set +of fractions have now been arranged in an +order like that of the integers. It runs thus +\begin{gather*} +\frac{1}{1},\ +\frac{1}{2},\ +\frac{2}{1},\ +\frac{1}{3},\ +\left[\frac{2}{2}\right],\ +\frac{3}{1},\ +\frac{1}{4},\ +\frac{2}{3},\ +\frac{3}{2},\ +\frac{4}{1},\ \dots, \\ +%\PageSep{79} +\frac{n - 1}{1},\ +\frac{1}{n - 1},\ +\frac{2}{n - 2},\ +\frac{3}{n - 3},\ +\dots,\ +\frac{n - 1}{1},\ +\frac{1}{n}, +\end{gather*} +and so on. + +Now we can get rid of all repetitions of +fractions of the same value by simply striking +them out whenever they appear after their +first occurrence. In the few initial terms +written down above, $\frac{2}{2}$~which is enclosed above +in square brackets is the only fraction not in +its lowest terms. It has occurred before as~$\frac{1}{1}$. +Thus this must be struck out. But the +series is still left with the same properties, +namely, (\textit{a})~there is a first term, (\textit{b})~each term +has next-door neighbours, (\textit{c})~the series goes +on without end. + +It can be proved that it is not possible to +\index{Cantor, Georg}% +arrange the whole series of real numbers in +this way. This curious fact was discovered +by Georg Cantor, a German mathematician +still living; it is of the utmost importance +in the philosophy of mathematical ideas. We +are here in fact touching on the fringe of the +great problems of the meaning of continuity +and of infinity. + +Another extension of number comes from +\index{Steps|EtSeq}% +the introduction of the idea of what has been +variously named an operation or a step, +names which are respectively appropriate +from slightly different points of view. We +will start with a particular case. Consider +\PageSep{80} +the statement $2 + 3 = 5$. We add $3$ to~$2$ and +obtain~$5$. Think of the operation of adding~$3$: +let this be denoted by~$+3$. Again $4 - 3 = 1$. +Think of the operation of subtracting~$3$: +let this be denoted by~$-3$. Thus instead +of considering the real numbers in themselves, +we consider the \emph{operations} of adding or subtracting +them: instead of~$\sqrt{2}$, we consider +$+\sqrt{2}$ and~$-\sqrt{2}$, namely the operations of +adding~$\sqrt{2}$ and of subtracting~$\sqrt{2}$. Then we +can add these operations, of course in a +different sense of addition to that in which we +add numbers. The sum of two operations is +the single operation which has the same effect +as the two operations applied successively. +In what order are the two operations to be +applied? The answer is that it is indifferent, +since for example +\[ +2 + 3 + 1 = 2 + 1 + 3; +\] +so that the addition of the steps $+3$ and $+1$ +is commutative. + +Mathematicians have a habit, which is +puzzling to those engaged in tracing out +meanings, but is very convenient in practice, +of using the same symbol in different though +allied senses. The one essential requisite for +a symbol in their eyes is that, whatever its +possible varieties of meaning, the formal laws +for its use shall always be the same. In +\PageSep{81} +accordance with this habit the addition of +operations is denoted by~$+$ as well as the +addition of numbers. Accordingly we can +write +\[ +(+3) + (+1) = +4; +\] +where the middle~$+$ on the left-hand side +denotes the addition of the operations $+3$ +and~$+1$. But, furthermore, we need not be +so very pedantic in our symbolism, except in +the rare instances when we are directly tracing +meanings; thus we always drop the first~$+$ +of a line and the brackets, and never write +two $+$~signs running. So the above equation +becomes +\[ +3 + 1 = 4, +\] +which we interpret as simple numerical addition, +or as the more elaborate addition of +operations which is fully expressed in the +previous way of writing the equation, or +lastly as expressing the result of applying +the operation~$+1$ to the number~$3$ and obtaining +the number~$4$. Any interpretation +which is possible is always correct. But the +only interpretation which is always possible, +under certain conditions, is that of operations. +The other interpretations often give nonsensical +results. + +This leads us at once to a question, which +must have been rising insistently in the +\PageSep{82} +reader's mind: What is the use of all this +elaboration? At this point our friend, the +practical man, will surely step in and insist on +sweeping away all these silly cobwebs of the +brain. The answer is that what the mathematician +is seeking is Generality. This is an +\index{Generality in Mathematics}% +idea worthy to be placed beside the notions +of the Variable and of Form so far as concerns +\index{Form, Algebraic}% +\index{Variable, The}% +its importance in governing mathematical +procedure. Any limitation whatsoever upon +the generality of theorems, or of proofs, or of +interpretation is abhorrent to the mathematical +instinct. These three notions, of the +variable, of form, and of generality, compose +a sort of mathematical trinity which preside +over the whole subject. They all really +spring from the same root, namely from the +abstract nature of the science. + +Let us see how generality is gained by the +introduction of this idea of operations. Take +the equation $x + 1 = 3$; the solution is $x = 2$. +Here we can interpret our symbols as mere +numbers, and the recourse to ``operations'' +is entirely unnecessary. But, if $x$~is a mere +number, the equation $x + 3 = 1$ is nonsense. +For $x$~should be the number of things which +remain when you have taken $3$~things away +from $1$~thing; and no such procedure is +possible. At this point our idea of algebraic +form steps in, itself only generalization under +another aspect. We consider, therefore, the +\PageSep{83} +\index{Positive and Negative Numbers|EtSeq}% +general equation of the same form as $x + 1 = 3$. +This equation is $x + a = b$, and its solution is +$x = b - a$. Here our difficulties become acute; +for this form can only be used for the numerical +interpretation so long as $b$~is greater than~$a$, +and we cannot say without qualification +that $a$ and $b$ may be any constants. In other +words we have introduced a limitation on +the variability of the ``constants'' $a$~and~$b$, +which we must drag like a chain throughout +all our reasoning. Really prolonged mathematical +investigations would be impossible +under such conditions. Every equation +would at last be buried under a pile of limitations. +But if we now interpret our symbols +as ``operations,'' all limitation vanishes like +magic. The equation $x + 1 = 3$ gives $x = +2$, +the equation $x + 3 = 1$ gives $x = -2$, the equation +$x + a = b$ gives $x = b - a$ which is an operation +of addition or subtraction as the case +may be. We need never decide whether $b - a$ +represents the operation of addition or of +subtraction, for the rules of procedure with +the symbols are the same in either case. + +It does not fall within the plan of this work +to write a detailed chapter of elementary +algebra. Our object is merely to make plain +the fundamental ideas which guide the formation +of the science. Accordingly we do not +further explain the detailed rules by which +the ``positive and negative numbers'' are +\PageSep{84} +multiplied and otherwise combined. We have +explained above that positive and negative +numbers are operations. They have also +been called ``steps.'' Thus $+3$~is the step +by which we go from $2$ to~$5$, and $-3$~is the +step backwards by which we go from $5$ to~$2$. +Consider the line~$OX$ divided in the way explained +in the earlier part of the chapter, so +that its points represent numbers. Then~$+2$ +%[** TN: In original, negative numbers placed below axis, primed letters above] +\Diagram{pg86} +is the step from $O$ to~$B$, or from $A$ to~$C$, or +(if the divisions are taken backwards along~$OX'$) +from $C'$ to~$A'$, or from $D'$ to~$B'$, and so +on. Similarly $-2$ is the step from $O$ to~$B'$, +or from $B'$ to~$D'$, or from $B$ to~$O$, or from $C$ +to~$A$. + +We may consider the point which is reached +by a step from~$O$, as representative of that +step. Thus $A$~represents~$+1$, $B$~represents~$+2$, +$A'$~represents~$-1$, $B'$~represents~$-2$, and +so on. It will be noted that, whereas previously +with the mere ``unsigned'' real numbers +the points on one side of~$O$ only, namely along~$OX$, +were representative of numbers, now +with steps every point on the whole line +stretching on both sides of~$O$ is representative +of a step. This is a pictorial representation +of the superior generality introduced by the +positive and negative numbers, namely the +\PageSep{85} +operations or steps. These ``signed'' numbers +are also particular cases of what have +been called vectors (from the Latin \Foreign{veho}, I +\index{Vectors}% +draw or carry). For we may think of a +particle as carried from $O$ to~$A$, or from $A$ +to~$B$. + +In suggesting a few pages ago that the +practical man would object to the subtlety +involved by the introduction of the positive +and negative numbers, we were libelling that +excellent individual. For in truth we are on +the scene of one of his greatest triumphs. If +the truth must be confessed, it was the practical +man himself who first employed the actual +symbols $+$ and~$-$. Their origin is not very +certain, but it seems most probable that they +arose from the marks chalked on chests of +goods in German warehouses, to denote excess +or defect from some standard weight. The +earliest notice of them occurs in a book published +at Leipzig, in \AD~1489. They seem +first to have been employed in mathematics +by a German mathematician, Stifel, in a book +\index{Stifel}% +published at Nuremburg in 1544~\AD. But +then it is only recently that the Germans +have come to be looked on as emphatically +a practical nation. There is an old epigram +which assigns the empire of the sea to the +English, of the land to the French, and of the +clouds to the Germans. Surely it was from +the clouds that the Germans fetched $+$ and~$-$; +\PageSep{86} +the ideas which these symbols have +generated are much too important for the +welfare of humanity to have come from the +sea or from the land. + +The possibilities of application of the positive +and negative numbers are very obvious. +If lengths in one direction are represented +by positive numbers, those in the opposite +direction are represented by negative numbers. +If a velocity in one direction is positive, that +in the opposite direction is negative. If a +rotation round a dial in the opposite direction +to the hands of a clock (anti-clockwise) is +positive, that in the clockwise direction is +negative. If a balance at the bank is positive, +an overdraft is negative. If vitreous +electrification is positive, resinous electrification +is negative. Indeed, in this latter case, +the terms positive electrification and negative +electrification, considered as mere names, +have practically driven out the other terms. +An endless series of examples could be given. +The idea of positive and negative numbers +has been practically the most successful of +mathematical subtleties. +\PageSep{87} + + +\Chapter{VII}{Imaginary Numbers} + +\First{If} the mathematical ideas dealt with in the +\index{Imaginary Numbers|EtSeq}% +last chapter have been a popular success, +those of the present chapter have excited +almost as much general attention. But their +success has been of a different character, it +has been what the French term a \Foreign{succès de +scandale}. Not only the practical man, but +also men of letters and philosophers have expressed +their bewilderment at the devotion +of mathematicians to mysterious entities +which by their very name are confessed to be +imaginary. At this point it may be useful +to observe that a certain type of intellect +is always worrying itself and others by +discussion as to the applicability of technical +terms. Are the incommensurable numbers +properly called numbers? Are the positive +and negative numbers really numbers? Are +the imaginary numbers imaginary, and are +they numbers?---are types of such futile +questions. Now, it cannot be too clearly +understood that, in science, technical terms +are names arbitrarily assigned, like Christian +\PageSep{88} +names to children. There can be no question +of the names being right or wrong. They +may be judicious or injudicious; for they can +sometimes be so arranged as to be easy to +remember, or so as to suggest relevant and +important ideas. But the essential principle +involved was quite clearly enunciated in +Wonderland to Alice by Humpty Dumpty, +when he told her, à~propos of his use of words, +``I pay them extra and make them mean +what I like.'' So we will not bother as to +whether imaginary numbers are imaginary, +or as to whether they are numbers, but will +take the phrase as the arbitrary name of a +certain mathematical idea, which we will now +endeavour to make plain. + +The origin of the conception is in every +way similar to that of the positive and negative +numbers. In exactly the same way it +is due to the three great mathematical ideas +of the variable, of algebraic form, and of +generalization. The positive and negative +numbers arose from the consideration of +equations like $x + 1 = 3$, $x + 3 = 1$, and the +general form $x + a = b$. Similarly the origin +of imaginary numbers is due to equations like +$x^{2} + 1 = 3$, $x^{2} + 3 = 1$, and $x^{2} + a = b$. Exactly +the same process is gone through. The equation +$x^{2} + 1 = 3$ becomes $x^{2} = 2$, and this has two +solutions, either $x = +\sqrt{2}$, or $x = -\sqrt{2}$. The +statement that there are these alternative +\PageSep{89} +solutions is usually written $x = ±\sqrt{2}$. So far +all is plain sailing, as it was in the previous +case. But now an analogous difficulty arises. +For the equation $x^{2} + 3 = 1$ gives $x^{2} = -2$ and +there is no positive or negative number which, +when multiplied by itself, will give a negative +square. Hence, if our symbols are to mean +the ordinary positive or negative numbers, +there is no solution to $x^{2} = -2$, and the equation +is in fact nonsense. Thus, finally taking +the general form $x^{2} + a = b$, we find the pair +of solutions $x = ±\sqrt{(b - a)}$, when, and only +when, $b$~is not less than~$a$. Accordingly we +cannot say unrestrictedly that the ``constants'' +$a$~and~$b$ may be any numbers, that is, +the ``constants'' $a$~and~$b$ are not, as they +ought to be, independent unrestricted ``variables''; +and so again a host of limitations +and restrictions will accumulate round our +work as we proceed. + +The same task as before therefore awaits +us: we must give a new interpretation to our +symbols, so that the solutions $±\sqrt{(b - a)}$ for +the equation $x^{2} + a = b$ always have meaning. +In other words, we require an interpretation +of the symbols so that $\sqrt{a}$~always has meaning +whether $a$~be positive or negative. Of +course, the interpretation must be such that +all the ordinary formal laws for addition, subtraction, +multiplication, and division hold +good; and also it must not interfere with the +\PageSep{90} +generality which we have attained by the use +of the positive and negative numbers. In +fact, it must in a sense include them as +special cases. When $a$~is negative we may +write $-c^{2}$ for it, so that $c^{2}$~is positive. Then +\begin{align*} +\sqrt{a} &= \sqrt{(-c^{2})} = \sqrt{\{(-1) × c^{2}\}} \\ + &= \sqrt{(-1)} \sqrt{c^{2}} = c\sqrt{(-1)}. +\end{align*} +Hence, if we can so interpret our symbols that +$\sqrt{(-1)}$~has a meaning, we have attained our +object. Thus $\sqrt{(-1)}$~has come to be looked +on as the head and forefront of all the +imaginary quantities. + +This business of finding an interpretation +for~$\sqrt{(-1)}$ is a much tougher job than the +analogous one of interpreting~$-1$. In fact, +while the easier problem was solved almost +instinctively as soon as it arose, it at first +hardly occurred, even to the greatest mathematicians, +that here a problem existed which +was perhaps capable of solution. Equations +like $x^{2} = -3$, when they arose, were simply +ruled aside as nonsense. + +However, it came to be gradually perceived +during the eighteenth century, and even +earlier, how very convenient it would be if +an interpretation could be assigned to these +nonsensical symbols. Formal reasoning with +these symbols was gone through, merely +assuming that they obeyed the ordinary +\PageSep{91} +algebraic laws of transformation; and it was +seen that a whole world of interesting results +could be attained, if only these symbols might +legitimately be used. Many mathematicians +were not then very clear as to the logic of +their procedure, and an idea gained ground +that, in some mysterious way, symbols which +mean nothing can by appropriate manipulation +yield valid proofs of propositions. Nothing +can be more mistaken. A symbol +which has not been properly defined is not a +symbol at all. It is merely a blot of ink on +paper which has an easily recognized shape. +Nothing can be proved by a succession of +blots, except the existence of a bad pen or a +careless writer. It was during this epoch +that the epithet ``imaginary'' came to be +applied to~$\sqrt{(-1)}$. What these mathematicians +had really succeeded in proving were +a series of hypothetical propositions, of which +this is the blank form: If interpretations +exist for $\sqrt{(-1)}$ and for the addition, subtraction, +multiplication, and division of~$\sqrt{(-1)}$ +which make the ordinary algebraic +rules (\eg\ $x + y = y + x$, etc.)\ to be satisfied, +then such and such results follows. It was +natural that the mathematicians should not +always appreciate the big ``If,'' which ought +to have preceded the statements of their results. + +As may be expected the interpretation, +\PageSep{92} +when found, was a much more elaborate affair +than that of the negative numbers and the +reader's attention must be asked for some +careful preliminary explanation. We have +already come across the representation of a +point by two numbers. By the aid of the +\Figure{8} +positive and negative numbers we can now +represent the position of any point in a plane +by a pair of such numbers. Thus we take +the pair of straight lines $XOX'$ and $YOY'$, at +right angles, as the ``axes'' from which we +start all our measurements. Lengths measured +along $OX$ and $OY$ are positive, and +measured backwards along $OX'$ and $OY'$ are +negative. Suppose that a pair of numbers, +written in order, \eg~$(+3, +1)$, so that there +\PageSep{93} +\index{Ordered Couples|EtSeq}% +is a first number ($+3$~in the above example), +and a second number ($+1$~in the above example), +represents measurements from~$O$ +along $XOX'$ for the first number, and along +$YOY'$ for the second number. Thus (\Chg{cf.}{\cf}\ \Fig[fig.]{9}) in +$(+3, +1)$ a length of $3$~units is to be measured +along $XOX'$ in the positive direction, that +is from~$O$ towards~$X$, and a length~$+1$ +measured along $YOY'$ in the positive direction, +that is from~$O$ towards~$Y$. Similarly in +$(-3, +1)$ the length of $3$~units is to be +measured from~$O$ towards~$X'$, and of $1$~unit +from towards~$Y$. Also in $(-3, -1)$ the +two lengths are to be measured along $OX'$ +and $OY'$ respectively, and in $(+3, -1)$ along +$OX$ and $OY'$ respectively. Let us for the +moment call such a pair of numbers an +``ordered couple.'' Then, from the two numbers +$1$~and~$3$, eight ordered couples can be +generated, namely +\begin{gather*} +(+1, +3),\ (-1, +3),\ (-1, -3),\ (+1, -3), \\ +(+3, +1),\ (-3, +1),\ (-3, -1),\ (+3, -1). +\end{gather*} +Each of these eight ``ordered couples'' directs +a process of measurement along $XOX'$ and +$YOY'$ which is different from that directed +by any of the others. + +The processes of measurement represented +by the last four ordered couples, mentioned +above, are given pictorially in the figure. +The lengths $OM$ and $ON$ together correspond +\PageSep{94} +to $(+3, +1)$, the lengths $OM'$ and $ON$ +together correspond to $(-3, +1)$, $OM'$~and +$ON'$ together to $(-3, -1)$, and $OM$~and +$ON'$ together to $(+3, -1)$. But by completing +the various rectangles, it is easy to +see that the point~$P$ completely determines +and is determined by the ordered couple +\Figure{9} +$(+3, +1)$, the point~$P'$ by $(-3, +1)$, the +point~$P''$ by $(-3, -1)$, and the point~$P'''$ by +$(+3, -1)$. More generally in the previous +figure~(\FigNum{8}), the point~$P$ corresponds to the +ordered couple~$(x, y)$, where $x$~and~$y$ in the +figure are both assumed to be positive, the +point~$P'$ corresponds to $(x', y)$, where $x'$~in +the figure is assumed to be negative, $P''$~to +$(x' y')$, and $P'''$~to $(x, y')$. Thus an ordered +\PageSep{95} +couple $(x, y)$, where $x$~and~$y$ are any positive +or negative numbers, and the corresponding +point reciprocally determine each other. It +is convenient to introduce some names at this +juncture. In the ordered couple $(x, y)$ the +first number~$x$ is called the ``abscissa'' of the +\index{Abscissa}% +corresponding point, and the second number~$y$ +is called the ``ordinate'' of the point, and +\index{Ordinate}% +the two numbers together are called the ``coordinates'' +\index{Coordinates}% +of the point. The idea of determining +the position of a point by its ``coordinates'' +was by no means new when the +theory of ``imaginaries'' was being formed. +It was due to Descartes, the great French +\index{Descartes}% +mathematician and philosopher, and appears +in his \Title{Discours} published at Leyden in 1637~\AD. +The idea of the ordered couple as a +thing on its own account is of later growth +and is the outcome of the efforts to interpret +imaginaries in the most abstract way possible. + +It may be noticed as a further illustration +of this idea of the ordered couple, that the +point~$M$ in \Fig[fig.]{9} is the couple $(+3, 0)$, the +point~$N$ is the couple $(0, +1)$, the point~$M'$ +the couple $(-3, 0)$, the point~$N'$ the couple +$(0, -1)$, the point~$O$ the couple~$(0, 0)$. + +Another way of representing the ordered +couple $(x, y)$ is to think of it as representing +the dotted line~$OP$ (\Chg{cf.}{\cf}\ \Fig[fig.]{8}), rather than the +point~$P$. Thus the ordered couple represents +a line drawn from an ``origin,''~$O$, of a certain +\index{Origin}% +\PageSep{96} +\index{Steps}% +length and in a certain direction. The line~$OP$ +may be called the vector line from $O$ to~$P$, +or the step from $O$ to~$P$. We see, therefore, +that we have in this chapter only extended +the interpretation which we gave formerly of +the positive and negative numbers. This +method of representation by vectors is very +\index{Vectors}% +useful when we consider the meaning to be +assigned to the operations of the addition and +multiplication of ordered couples. + +{\Loosen We will now go on to this question, and +ask what meaning we shall find it convenient +to assign to the addition of the two ordered +couples $(x, y)$ and $(x', y')$. The interpretation +must, (\textit{a})~make the result of addition +to be another ordered couple, (\textit{b})~make the +operation commutative so that $(x, y) + (x', y') = (x', y') + (x, y)$, +(\textit{c})~make the operation +associative so that} +\[ +\{(x, y) + (x', y')\} + (u, v) = (x, y) + \{(x', y') + (u, v)\}, +\] +(\textit{d})~make the result of subtraction unique, +so that when we seek to determine the +unknown ordered couple $(x, y)$ so as to +satisfy the equation +\[ +(x, y) + (a, b) = (c, d), +\] +there is one and only one answer which we +can represent by +\[ +(x, y) = (c, d) - (a, b). +\] +\PageSep{97} +All these requisites are satisfied by taking +$(x, y) + (x', y')$ to mean the ordered couple +$(x + x', y + y')$. Accordingly by definition we +put +\[ +(x, y) + (x', y') = (x + x', y + y'). +\] +Notice that here we have adopted the mathematical +habit of using the same symbol~$+$ in +different senses. The $+$ on the left-hand side +of the equation has the new meaning of~$+$ +which we are just defining; while the two~$+$'s +on the right-hand side have the meaning +of the addition of positive and negative numbers +(operations) which was defined in the +last chapter. No practical confusion arises +from this double use. + +As examples of addition we have +\begin{align*} +(+3, +1) + (+2, +6) &= (+5, +7), \\ +(+3, -1) + (-2, -6) &= (+1, -7), \\ +(+3, +1) + (-3, -1) &= (0, 0). +\end{align*} + +The meaning of subtraction is now settled +for us. We find that +\[ +(x, y) - (u, v) = (x - u, y - v). +\] +Thus +\[ +(+3, +2) - (+1, +1) = (+2, +1), +\] +and +\[ +(+1, -2) - (+2, -4) = (-1, +2), +\] +and +\[ +(-1, -2) - (+2, +3) = (-3, -5). +\] +\PageSep{98} + +It is easy to see that +\[ +(x, y) - (u, v) = (x, y) + (-u, -v). +\] +Also +\[ +(x, y) - (x, y) = (0, 0). +\] +Hence $(0, 0)$~is to be looked on as the zero +ordered couple. For example +\[ +(x, y) + (0, 0) = (x, y). +\] + +The pictorial representation of the addition +of ordered couples is surprisingly easy. +\Figure{10} + +{\Loosen Let $OP$ represent $(x, y)$ so that $OM = x$ +and $PM = y$; let $OQ$ represent $(x_{1}, y_{1})$ so that +$OM_{1} = x_{1}$ and $QM_{1} = y_{1}$. Complete the parallelogram +$OPRQ$ by the dotted lines $PR$ and~$QR$, +then the diagonal~$OR$ is the ordered +couple $(x + x_{1}, y + y_{1})$. For draw $PS$ parallel +\PageSep{99} +to~$OX$; then evidently the triangles $OQM_{1}$ +and $PRS$ are in all respects equal. Hence +$MM' = PS = x_{1}$, and $RS = QM_{1}$ and therefore} +\begin{gather*} +OM' = OM + MM' = x + x_{1}, \\ +RM' = SM' + RS = y + y_{1}. +\end{gather*} + +Thus $OR$~represents the ordered couple as +required. This figure can also be drawn with +$OP$ and $OQ$ in other quadrants. + +It is at once obvious that we have here +come back to the parallelogram law, which +\index{Parallelogram Law}% +was mentioned in \ChapRef{VI}., on the laws of +motion, as applying to velocities and forces. +It will be remembered that, if $OP$ and $OQ$ +represent two velocities, a particle is said to +be moving with a velocity equal to the two +velocities added together if it be moving with +the velocity~$OR$. In other words $OR$~is said +to be the resultant of the two velocities $OP$ +and~$OQ$. Again forces acting at a point of a +body can be represented by lines just as +velocities can be; and the same parallelogram +law holds, namely, that the resultant of the +two forces $OP$ and $OQ$ is the force represented +by the diagonal~$OR$. It follows that we can +look on an ordered couple as representing a +velocity or a force, and the rule which we +have just given for the addition of ordered +couples then represents the fundamental laws +of mechanics for the addition of forces and +\PageSep{100} +velocities. One of the most fascinating +characteristics of mathematics is the surprising +way in which the ideas and results of +different parts of the subject dovetail into +each other. During the discussions of this +and the previous chapter we have been guided +merely by the most abstract of pure mathematical +considerations; and yet at the end +of them we have been led back to the most +fundamental of all the laws of nature, laws +which have to be in the mind of every engineer +as he designs an engine, and of every naval +architect as he calculates the stability of a +ship. It is no paradox to say that in our +most theoretical moods we may be nearest to +our most practical applications. +\PageSep{101} + + +\Chapter[Imaginary Numbers] + {VIII}{Imaginary Numbers (\textit{C\MakeLowercase{ontinued}})} + +\First{The} definition of the multiplication of +ordered couples is guided by exactly the same +considerations as is that of their addition. +The interpretation of multiplication must be +such that + +\Eq{(\alpha)} the result is another ordered couple, + +\Eq{(\beta)} the operation is commutative, so that +\[ +(x, y) × (x', y') = (x', y') × (x, y), +\] + +\Eq{(\gamma)} the operation is associative, so that +\[ +\{(x, y) × (x', y')\} × (u, v) = (x, y) × \{(x', y') × (u, v)\}, +\] + +\Eq{(\delta)} must make the result of division unique +[with an exception for the case of the zero +couple $(0, 0)$], so that when we seek to determine +the unknown couple $(x, y)$ so as to +satisfy the equation +\[ +(x, y) × (a, b) = (c, d), +\] +there is one and only one answer, which we +can represent by +\[ +(x, y) = (c, d) ÷ (a, b),\quad\text{or by}\quad +(x, y) = \frac{(c, d)}{(a, b)}\Add{.} +\] +\PageSep{102} + +\Eq{(\epsilon)} Furthermore the law involving both +addition and multiplication, called the distributive +law, must be satisfied, namely +\begin{multline*} +(x,y) × \{(a, b) + (c, d)\} \\ += \{(x, y) × (a, b)\} + \{(x, y) × (c, d)\}. +\end{multline*} + +All these conditions \Eq{(\alpha)}, \Eq{(\beta)}, \Eq{(\gamma)}, \Eq{(\delta)}, \Eq{(\epsilon)} can +be satisfied by an interpretation which, +though it looks complicated at first, is capable +of a simple geometrical interpretation. + +By definition we put +\[ +(x, y) × (x', y') = \{(xx' - yy'), (xy' + x'y)\}\Add{.} +\Tag{(A)} +\] + +This is the definition of the meaning of the +symbol~$×$ when it is written between two +ordered couples. It follows evidently from +this definition that the result of multiplication +is another ordered couple, and that the +value of the right-hand side of equation~\Eq{(A)} +is not altered by simultaneously interchanging +$x$~with~$x'$, and $y$~with~$y'$. Hence conditions +\Eq{(\alpha)} and \Eq{(\beta)} are evidently satisfied. The proof +of the satisfaction of \Eq{(\gamma)}, \Eq{(\delta)}, \Eq{(\epsilon)} is equally +easy when we have given the geometrical +interpretation, which we will proceed to do +in a moment. But before doing this it will +be interesting to pause and see whether we +have attained the object for which all this +elaboration was initiated. + +We came across equations of the form +$x^{2} = -3$, to which no solutions could be +\PageSep{103} +assigned in terms of positive and negative real +numbers. We then found that all our difficulties +would vanish if we could interpret the +equation $x^{2} = -1$, \ie, if we could so define +$\sqrt{(-1)}$ that $\sqrt{(-1)} × \sqrt{(-1)} = -1$. + +Now let us consider the three special +\index{Zero}% +ordered couples\footnote + {For the future we follow the custom of omitting the + $+$~sign wherever possible, thus $(1, 0)$ stands for $(+1, 0)$ + and $(0, 1)$ for $(0, +1)$.} +$(0, 0)$, $(1, 0)$, and $(0, 1)$. + +We have already proved that +\[ +(x, y) + (0, 0) = (x, y). +\] + +Furthermore we now have +\[ +(x, y) × (0, 0) = (0, 0). +\] + +Hence both for addition and for multiplication +the couple $(0, 0)$ plays the part of zero in +elementary arithmetic and algebra; compare +the above equations with $x + 0 = x$, and +$x × 0 = 0$. + +Again consider $(1, 0)$: this plays the part +of~$1$ in elementary arithmetic and algebra. +In these elementary sciences the special +characteristic of~$1$ is that $x × 1 = x$, for all +values of~$x$. Now by our law of multiplication +\[ +(x, y) × (1, 0) = \{(x - 0), (y + 0)\} = (x, y). +\] + +Thus $(1, 0)$ is the unit couple. +\PageSep{104} + +Finally consider $(0, 1)$: this will interpret +for us the symbol~$\sqrt{(-1)}$. The symbol must +therefore possess the characteristic property +that $\sqrt{(-1)} × \sqrt{(-1)} = -1$. Now by the +law of multiplication for ordered couples +\[ +(0, 1) × (0, 1) = \{(0 - 1), (0 + 0)\} = (-1, 0). +\] + +But $(1, 0)$ is the unit couple, and $(-1, 0)$ +is the negative unit couple; so that $(0, 1)$ has +the desired property. There are, however, +two roots of~$-1$ to be provided for, namely +$±\sqrt{(-1)}$. Consider $(0, -1)$; here again remembering +that $(-1)^{2} = 1$, we find, $(0, -1) × (0, -1) = (-1, 0)$. + +Thus $(0, -1)$ is the other square root of~$\Typo{\sqrt{(-1)}}{-1}$. +Accordingly the ordered couples +$(0, 1)$ and $(0, -1)$ are the interpretations of +$±\sqrt{(-1)}$ in terms of ordered couples. But +which corresponds to which? Does $(0, 1)$ +correspond to $+\sqrt{(-1)}$ and $(0, -1)$ to~$-\sqrt{(-1)}$, +or $(0, 1)$ to~$-\sqrt{(-1)}$, and $(0, -1)$ +to~$+\sqrt{(-1)}$? The answer is that it is perfectly +indifferent which symbolism we adopt. + +The ordered couples can be divided into +three types, (i)~the ``complex imaginary'' +type~$(x, y)$, in which neither $x$ nor~$y$ is zero; +(ii)~the ``real'' type~$(x, 0)$; (iii)~the ``pure +imaginary'' type~$(0, y)$. Let us consider the +relations of these types to each other. First +multiply together the ``complex imaginary'' +\PageSep{105} +couple $(x, y)$ and the ``real'' couple $(a, 0)$, we +find +\[ +(a, 0) × (x, y) = (ax, ay). +\] + +Thus the effect is merely to multiply each +term of the couple $(x, y)$ by the positive or +negative real number~$a$. + +Secondly, multiply together the ``complex +imaginary'' couple $(x, y)$ and the ``pure +imaginary'' couple $(0, b)$, we find +\[ +(0, b) × (x, y) = (-by, bx). +\] + +Here the effect is more complicated, and is +best comprehended in the geometrical interpretation +to which we proceed after noting +three yet more special cases. + +Thirdly, we multiply the ``real'' couple +$(a, 0)$ by the imaginary $(0, b)$ and obtain +\[ +(a, 0) × (0, b) =(0, ab). +\] + +Fourthly, we multiply the two ``real'' +couples $(a, 0)$ and $(a', 0)$ and obtain +\[ +(a, 0) × (a', 0) =( aa', 0). +\] + +Fifthly, we multiply the two ``imaginary +couples'' $(0, b)$ and $(0, \Typo{b}{b'})$ and obtain +\[ +(0, b) × (0, b') = (-bb', 0). +\] + +We now turn to the geometrical interpretation, +beginning first with some special cases. +\PageSep{106} +Take the couples $(1, 3)$ and $(2, 0)$ and consider +the equation +\[ +(2, 0) × (1, 3) = (2, 6)\Add{.} +\] +\Figure{11} + +In the diagram (\Fig[fig.]{11}) the vector~$OP$ represents~$(1, 3)$, +and the vector~$ON$ represents~$(2, 0)$, +and the vector~$OQ$ represents~$(2, 6)$. +Thus the product $(2, 0) × (1, 3)$ is found geometrically +by taking the length of the vector~$OQ$ +to be the product of the lengths of the +vectors $OP$ and~$ON$, and (in this case) by +producing $OP$ to~$Q$ to be of the required +length. Again, consider the product $(0, 2) × (1, 3)$, +we have +\[ +(0, 2) × (1, 3) = (-6, 2)\Add{.} +\] + +The vector~$ON_{1}$, corresponds to~$(0, 2)$ and +the vector~$OR$ to~$(-6,2)$. Thus $OR$ which +\PageSep{107} +represents the new product is at right angles +to~$OQ$ and of the same length. Notice that +we have the same law regulating the length +of~$OQ$ as in the previous case, namely, that +its length is the product of the lengths of +the two vectors which are multiplied together; +but now that we have $ON_{1}$ along the +``ordinate'' axis~$OY$, instead of $ON$ along +the ``abscissa'' axis~$OX$, the direction of~$OP$ +has been turned through a right-angle. + +Hitherto in these examples of multiplication +we have looked on the vector~$OP$ as modified +by the vectors $ON$ and~$ON_{1}$. We shall get +a clue to the general law for the direction by +inverting the way of thought, and by thinking +of the vectors $ON$ and~$ON_{1}$ as modified by +the vector~$OP$. The law for the length remains +unaffected; the resultant length is the +length of the product of the two vectors. +The new direction for the enlarged~$ON$ (\ie~$OQ$) +is found by rotating it in the (anti-clockwise) +direction of rotation from $OX$ towards~$OY$ +through an angle equal to the angle~$XOP$: +it is an accident of this particular case that +this rotation makes $OQ$ lie along the line~$OP$. +Again consider the product of $ON_{1}$ and~$OP$; +the new direction for the enlarged~$ON_{1}$ (\ie~$OR$) +is found by rotating~$ON$ in the anti-clockwise +direction of rotation through an +angle equal to the angle~$XOP$, namely, the +angle~$N_{1}OR$ is equal to the angle~$XOP$. +\PageSep{108} + +The general rule for the geometrical representation +of multiplication can now be enunciated +thus: +\Figure[3in]{12} + +The product of the two vectors $OP$ and~$OQ$ +is a vector~$OR$, whose length is the product +of the lengths of $OP$ and~$OQ$ and whose +direction~$OR$ is such that the angle~$XOR$ is +equal to the sum of the angles $XOP$ and~$XOQ$. + +Hence we can conceive the vector~$OP$ as +making the vector~$OQ$ rotate through an +angle~$XOP$ (\ie\ $\text{the angle } QOR = \text{the angle } XOP$), +or the vector~$OQ$ as making the vector~$OP$ +rotate through the angle~$XOQ$ (\ie $\text{the angle } POR = \text{the angle } XOQ$). + +We do not prove this general law, as we +\PageSep{109} +should thereby be led into more technical +processes of mathematics than falls within the +design of this book. But now we can immediately +see that the associative law [numbered~\Eq{(\gamma)} +above] for multiplication is satisfied. +Consider first the length of the resultant +vector; this is got by the ordinary process +of multiplication for real numbers; and thus +the associative law holds for it. + +Again, the direction of the resultant vector +is got by the mere addition of angles, and the +associative law holds for this process also. + +So much for multiplication. We have now +rapidly indicated, by considering addition and +multiplication, how an algebra or ``calculus'' +of vectors in one plane can be constructed, +which is such that any two vectors in the +plane can be added, or subtracted, and can +be multiplied, or divided one by the other. + +We have not considered the technical details +of all these processes because it would +lead us too far into mathematical details; +but we have shown the general mode of procedure. +When we are interpreting our algebraic +symbols in this way, we are said to be +employing ``imaginary quantities'' or ``complex +\index{Complex Quantities}% +\index{Imaginary Quantities}% +quantities.'' These terms are mere +details, and we have far too much to think +about to stop to enquire whether they are or +are not very happily chosen. + +%[** TN: [sic] "nett", variant spelling] +The nett result of our investigations is that +\PageSep{110} +any equations like $x + 3 = 2$ or $(x + 3)^{2} = -2$ +can now always be interpreted into terms of +vectors, and solutions found for them. In +seeking for such interpretations it is well to +note that $3$~becomes $(3, 0)$, and $-2$~becomes +$(-2, 0)$, and $x$~becomes the ``unknown'' +couple $(u, v)$: so the two equations become +respectively $(u, v) + (3, 0) = (2, 0)$, and +$\{(u, v) + (3, 0)\}^{2} = (-2, 0)$. + +We have now completely solved the initial +difficulties which caught our eye as soon as +we considered even the elements of algebra. +The science as it emerges from the solution is +much more complex in ideas than that with +which we started. We have, in fact, created +a new and entirely different science, which +will serve all the purposes for which the old +science was invented and many more in addition. +But, before we can congratulate ourselves +on this result to our labours, we must +allay a suspicion which ought by this time to +have arisen in the mind of the student. The +question which the reader ought to be asking +himself is: Where is all this invention of new +interpretations going to end? It is true that +we have succeeded in interpreting algebra so +as always to be able to solve a quadratic +equation like $x^{2} - 2x + 4 = 0$; but there are +an endless number of other equations, for +example, $x^{3} - 2x + 4 = 0$, $x^{4} + x^{3} + 2 = 0$, and so +on without limit. Have we got to make a +\PageSep{111} +new science whenever a new equation appears? + +Now, if this were the case, the whole of our +preceding investigations, though to some +minds they might be amusing, would in truth +be of very trifling importance. But the great +fact, which has made modern analysis possible, +is that, by the aid of this calculus of vectors, +every formula which arises can receive its +proper interpretation; and the ``unknown'' +quantity in every equation can be shown to +indicate some vector. Thus the science is now +complete in itself as far as its fundamental +ideas are concerned. It was receiving its final +form about the same time as when the steam +engine was being perfected, and will remain +a great and powerful weapon for the achievement +of the victory of thought over things +when curious specimens of that machine +repose in museums in company with the +helmets and breastplates of a slightly earlier +epoch. +\PageSep{112} + + +\Chapter{IX}{Coordinate Geometry} + +\First{The} methods and ideas of coordinate geometry +\index{Coordinate Geometry|EtSeq}% +have already been employed in the +previous chapters. It is now time for us to +consider them more closely for their own +sake; and in doing so we shall strengthen our +hold on other ideas to which we have attained. +In the present and succeeding chapters we +will go back to the idea of the positive and +negative real numbers and will ignore the +imaginaries which were introduced in the last +two chapters. + +We have been perpetually using the idea +that, by taking two axes, $XOX'$ and~$YOY'$, +in a plane, any point~$P$ in that plane can be +determined in position by a pair of positive +or negative numbers $x$ and~$y$, where (\Chg{cf.}{\cf}\ +\Fig[fig.]{13}) $x$~is the length~$OM$ and $y$~is the length~$PM$. +This conception, simple as it looks, is +the main idea of the great subject of coordinate +geometry. Its discovery marks a +momentous epoch in the history of mathematical +thought. It is due (as has been +\PageSep{113} +already said) to the philosopher Descartes, +\index{Descartes}% +and occurred to him as an important mathematical +method one morning as he lay in bed. +Philosophers, when they have possessed a +thorough knowledge of mathematics, have +been among those who have enriched the +\Figure{13} +science with some of its best ideas. On the +other hand it must be said that, with hardly +an exception, all the remarks on mathematics +made by those philosophers who have possessed +but a slight or hasty and late-acquired +knowledge of it are entirely worthless, being +either trivial or wrong. The fact is a curious +one; since the ultimate ideas of mathematics +\PageSep{114} +seem, after all, to be very simple, almost +childishly so, and to lie well within the +province of philosophical thought. Probably +their very simplicity is the cause of error; we +are not used to think about such simple +abstract things, and a long training is necessary +to secure even a partial immunity from +error as soon as we diverge from the beaten +track of thought. + +The discovery of coordinate geometry, and +also that of projective geometry about the +same time, illustrate another fact which is +being continually verified in the history of +knowledge, namely, that some of the greatest +discoveries are to be made among the most +well-known topics. By the time that the +seventeenth century had arrived, geometry +had already been studied for over two thousand +years, even if we date its rise with the Greeks. +Euclid, taught in the University of Alexandria, +\index{Euclid}% +being born about 330~\BC; and he only +systematized and extended the work of a long +series of predecessors, some of them men of +genius. After him generation after generation +of mathematicians laboured at the improvement +of the subject. Nor did the +subject suffer from that fatal bar to progress, +namely, that its study was confined to a +narrow group of men of similar origin and +outlook---quite the contrary was the case; +by the seventeenth century it had passed +\PageSep{115} +through the minds of Egyptians and Greeks, +of Arabs and of Germans. And yet, after all +this labour devoted to it through so many +ages by such diverse minds its most important +secrets were yet to be discovered. + +No one can have studied even the elements +of elementary geometry without feeling the +lack of some guiding method. Every proposition +has to be proved by a fresh display of ingenuity; +and a science for which this is true +lacks the great requisite of scientific thought, +namely, method. Now the especial point of +coordinate geometry is that for the first +time it introduced method. The remote +deductions of a mathematical science are not +of primary theoretical importance. The +science has not been perfected, until it consists +in essence of the exhibition of great allied +methods by which information, on any desired +topic which falls within its scope, can easily +be obtained. The growth of a science is not +primarily in bulk, but in ideas; and the more +the ideas grow, the fewer are the deductions +which it is worth while to write down. Unfortunately, +mathematics is always encumbered +by the repetition in text-books of +numberless subsidiary propositions, whose importance +has been lost by their absorption +into the role of particular cases of more +general truths---and, as we have already insisted, +generality is the soul of mathematics. +\PageSep{116} + +Again, coordinate geometry illustrates +another feature of mathematics which has +already been pointed out, namely, that mathematical +sciences as they develop dovetail into +each other, and share the same ideas in common. +It is not too much to say that the +various branches of mathematics undergo a +perpetual process of generalization, and that +as they become generalized, they coalesce. +Here again the reason springs from the very +nature of the science, its generality, that is +to say, from the fact that the science deals +with the general truths which apply to all +things in virtue of their very existence as +things. In this connection the interest of coordinate +geometry lies in the fact that it +relates together geometry, which started as +the science of space, and algebra, which has +its origin in the science of number. + +Let us now recall the main ideas of the two +sciences, and then see how they are related +by Descartes' method of coordinates. Take +\index{Descartes}% +algebra in the first place. We will not trouble +ourselves about the imaginaries and will +think merely of the real numbers with positive +or negative signs. The fundamental idea +is that of any number, the variable number, +which is denoted by a letter and not by any +definite numeral. We then proceed to the +consideration of correlations between variables. +For example, if $x$ and~$y$ are two variables, +\PageSep{117} +we may conceive them as correlated by +the equations $x + y = 1$, or by $x - y = 1$, or in +any one of an indefinite number of other ways. +This at once leads to the application of the +\index{Form, Algebraic}% +idea of algebraic form. We think, in fact, of +any correlation of some interesting type, thus +rising from the initial conception of variable +numbers to the secondary conception of +variable correlations of numbers. Thus we +generalize the correlation $x + y = 1$, into the +correlation $ax + by = c$. Here $a$~and $b$ and~$c$, +being letters, stand for any numbers and are +in fact themselves variables. But they are +the variables which determine the variable +correlation; and the correlation, when determined, +correlates the variable numbers $x$ and~$y$. +Variables, like $a$,~$b$, and~$c$ above, which +are used to determine the correlation are +called ``constants,'' or parameters. The use +\index{Constants}% +\index{Parameters}% +of the term ``constant'' in this connection +for what is really a variable may seem at first +sight to be odd; but it is really very natural. +For the mathematical investigation is concerned +with the relation between the variables +$x$ and~$y$, after $a$,~$b$,~$c$ are supposed to have been +determined. So in a sense, relatively to $x$ +and~$y$, the ``constants'' $a$,~$b$, and~$c$ are constants. +Thus $ax + by = c$ stands for the general +example of a certain algebraic form, that is, +for a variable correlation belonging to a certain +class. +\PageSep{118} + +Again we generalize $x^{2} + y^{2} = 1$ into $ax^{2} + by^{2} = c$, +or still further into $ax^{2} + 2hxy + by^{2} = c$, +or, still further, into $ax^{2} + 2hxy + by^{2} + 2gx + 2fy = c$. + +Here again we are led to variable correlations +which are indicated by their various algebraic +forms. + +Now let us turn to geometry. The name +of the science at once recalls to our minds +the thought of figures and diagrams exhibiting +triangles and rectangles and squares and +circles, all in special relations to each other. +The study of the simple properties of these +figures is the subject matter of elementary +geometry, as it is rightly presented to the +beginner. Yet a moment's thought will show +that this is not the true conception of the +subject. It may be right for a child to commence +his geometrical reasoning on shapes, +like triangles and squares, which he has cut +out with scissors. What, however, is a triangle? +It is a figure marked out and bounded +by three bits of three straight lines. + +Now the boundary of spaces by bits of +lines is a very complicated idea, and not at +all one which gives any hope of exhibiting +the simple general conceptions which should +form the bones of the subject. We want +something more simple and more general. It +is this obsession with the wrong initial ideas---very +natural and good ideas for the creation +\PageSep{119} +of first thoughts on the subject---which was +the cause of the comparative sterility of the +study of the science during so many centuries. +Coordinate geometry, and Descartes its inventor, +must have the credit of disclosing the +true simple objects for geometrical thought. + +In the place of a bit of a straight line, let +us think of the whole of a straight line +throughout its unending length in both directions. +This is the sort of general idea from +which to start our geometrical investigations. +The Greeks never seem to have found any +use for this conception which is now fundamental +in all modern geometrical thought. +Euclid always contemplates a straight line as +drawn between two definite points, and is +very careful to mention when it is to be produced +beyond this segment. He never thinks +of the line as an entity given once for all as a +whole. This careful definition and limitation, +so as to exclude an infinity not immediately +apparent to the senses, was very characteristic +of the Greeks in all their many +activities. It is enshrined in the difference +between Greek architecture and Gothic architecture, +and between the Greek religion and +the modern religion. The spire on a Gothic +cathedral and the importance of the unbounded +straight line in modern geometry +are both emblematic of the transformation of +the modern world. +\PageSep{120} + +The straight line, considered as a whole, +is accordingly the root idea from which +modern geometry starts. But then other +sorts of lines occur to us, and we arrive at the +conception of the complete curve which at +every point of it exhibits some uniform characteristic, +just as the straight line exhibits +at all points the characteristic of straightness. +For example, there is the circle which +\index{Circle}% +at all points exhibits the characteristic of +being at a given distance from its centre, and +again there is the ellipse, which is an oval +\index{Ellipse}% +curve, such that the sum of the two distances +of any point on it from two fixed points, called +\index{Focus}% +its \emph{foci}, is constant for all points on the curve. +It is evident that a circle is merely a particular +case of an ellipse when the two foci are +superposed in the same point; for then the +sum of the two distances is merely twice the +radius of the circle. The ancients knew the +properties of the ellipse and the circle and, of +course, considered them as wholes. For example, +Euclid never starts with mere segments +(\ie,~bits) of circles, which are then prolonged. +He always considers the whole circle +as described. It is unfortunate that the +circle is not the true fundamental line in +geometry, so that his defective consideration +of the straight line might have been of less +consequence. + +This general idea of a curve which at any +\PageSep{121} +\index{Locus|EtSeq}% +point of it exhibits some uniform property is +expressed in geometry by the term ``locus.'' +A locus is the curve (or surface, if we do not +confine ourselves to a plane) formed by points, +all of which possess some given property. +To every property in relation to each other +which points can have, there corresponds +some locus, which consists of all the points +possessing the property. In investigating +the properties of a locus considered as a whole, +we consider \emph{any} point or points on the locus. +Thus in geometry we again meet with the +fundamental idea of the variable. Furthermore, +in classifying loci under such headings +as straight lines, circles, ellipses, etc., we again +find the idea of form. + +Accordingly, as in algebra we are concerned +with variable numbers, correlations between +variable numbers, and the classification of +correlations into types by the idea of algebraic +form; so in geometry we are concerned with +variable points, variable points satisfying +some condition so as form to a locus, and the +classification of \emph{loci} into types by the idea of +conditions of the same form. + +Now, the essence of coordinate geometry +is the identification of the algebraic correlation +with the geometrical locus. The point +on a plane is represented in algebra by its +two coordinates, $x$~and~$y$, and the condition +satisfied by any point on the locus is represented +\PageSep{122} +by the corresponding correlation +between $x$~and~$y$. Finally to correlations +expressible in some general algebraic form, +such as $ax + by = c$, there correspond loci of +some general type, whose geometrical conditions +are all of the same form. We +have thus arrived at a position where we +can effect a complete interchange in ideas +and results between the two sciences. Each +science throws light on the other, and itself +gains immeasurably in power. It is impossible +not to feel stirred at the thought +of the emotions of men at certain historic +moments of adventure and discovery---Columbus +\index{Columbus}% +when he first saw the Western +shore, Pizarro when he stared at the Pacific +\index{Pizarro}% +Ocean, Franklin when the electric spark came +\index{Franklin}% +from the string of his kite, Galileo when he +\index{Galileo}% +first turned his telescope to the heavens. +Such moments are also granted to students +in the abstract regions of thought, and high +among them must be placed the morning when +Descartes lay in bed and invented the method +\index{Descartes}% +of coordinate geometry. + +When one has once grasped the idea of coordinate +geometry, the immediate question +which starts to the mind is, What sort of +loci correspond to the well-known algebraic +forms? For example, the simplest among +the general types of algebraic forms is $ax + by = c$. +The sort of locus which corresponds +\PageSep{123} +to this is a straight line, and conversely to +every straight line there corresponds an equation +of this form. It is fortunate that the +simplest among the geometrical loci should +correspond to the simplest among the algebraic +forms. Indeed, it is this general correspondence +of geometrical and algebraic simplicity +which gives to the whole subject its +power. It springs from the fact that the +connection between geometry and algebra is +not casual and artificial, but deep-seated and +essential. The equation which corresponds +to a locus is called the equation ``of'' (or +``to'') the locus. Some examples of equations +of straight lines will illustrate the subject. +\Figure[3.75in]{14} +\PageSep{124} + +Consider $y - x = 0$; here the $a$,~$b$, and~$c$, of +the general form have been replaced by $-1$,~$1$, +and $0$ respectively. This line passes through +the ``origin,''~$O$, in the diagram and bisects +the angle~$XOY$. It is the line~$L'OL$ of the +diagram. The fact that it passes through the +origin,~$O$, is easily seen by observing that the +equation is satisfied by putting $x = 0$ and +$y = 0$ simultaneously, but $0$~and~$0$ are the coordinates +of~$O$. In fact it is easy to generalize +and to see by the same method that the +equation of any line through the origin is of +the form $ax + by = 0$. The locus of\Typo{}{ the} equation +$y + x = 0$ also passes through the origin and +bisects the angle~$X'OY$: it is the line~$L_{1}OL_{1}'$ +of the diagram. + +Consider $y - x = 1$: the corresponding locus +does not pass through the origin. We therefore +seek where it cuts the axes. It must cut +the axis of~$x$ at some point of coordinates +$x$~and~$0$. But putting $y = 0$ in the equation, +we get $x = -1$; so the coordinates of this +point~$(A)$ are $1$~and~$0$. Similarly the point~$(B)$ +where the line cuts the axis~$OY$ are $0$~and~$1$. +The locus is the line~$AB$ in the figure and +is parallel to~$LOL'$. Similarly $y + x = 1$ is the +equation of line~$A_{1}B$ of the figure; and the +locus is parallel to~$L_{1}OL_{1}'$. It is easy to prove +the general theorem that two lines represented +by equations of the forms $ax + by = 0$ and +$ax + by = c$ are parallel. +\PageSep{125} + +The group of loci which we next come upon +are sufficiently important to deserve a chapter +to themselves. But before going on to +them we will dwell a little longer on the main +ideas of the subject. + +The position of any point~$P$ is determined +by arbitrarily choosing an origin,~$O$, two axes, +\index{Axes}% +$OX$~and~$OY$, at right-angles, and then by +noting its coordinates $x$~and~$y$, \ie\ $OM$ and~$PM$ +(\cf\ \Fig[fig.]{13}). Also, as we have seen in the +last chapter, $P$~can be determined by the +``vector''~$OP$, where the idea of the vector +includes a determinate direction as well as a +determinate length. From an abstract +mathematical point of view the idea of an +arbitrary origin may appear artificial and +clumsy, and similarly for the arbitrarily +drawn axes, $OX$~and~$OY$. But in relation to +the application of mathematics to the event +of the Universe we are here symbolizing with +direct simplicity the most fundamental fact +respecting the outlook on the world afforded +to us by our senses. We each of us refer +our sensible perceptions of things to an origin +which we call ``here'': our location in a +particular part of space round which we +group the whole Universe is the essential fact +of our bodily existence. We can imagine +beings who observe all phenomena in all space +with an equal eye, unbiassed in favour of any +part. With us it is otherwise, a cat at our +\PageSep{126} +feet claims more attention than an earthquake +at Cape Horn, or than the destruction +of a world in the Milky Way. It is true that +in making a common stock of our knowledge +with our fellowmen, we have to waive something +of the strict egoism of our own individual +``here.'' We substitute ``nearly +here'' for ``here''; thus we measure miles +from the town hall of the nearest town, or +from the capital of the country. In measuring +the earth, men of science will put the +origin at the earth's centre; astronomers +\index{Origin}% +even rise to the extreme altruism of putting +their origin inside the sun. But, far as this +last origin may be, and even if we go further +to some convenient point amid the nearer +fixed stars, yet, compared to the immeasurable +infinities of space, it remains true that +our first procedure in exploring the Universe +is to fix upon an origin ``nearly here.'' + +Again the relation of the coordinates $OM$ +and~$MP$ (\ie\ $x$~and~$y$) to the vector~$OP$ is an +instance of the famous parallelogram law, as +\index{Parallelogram Law}% +can easily be seen (\cf\ \Fig[fig.]{8}) by completing +the parallelogram~$OMPN$. The idea of the +``vector''~$OP$, that is, of a directed magnitude, +is the root-idea of physical science. +Any moving body has a certain magnitude +of velocity in a certain direction, that is to +say, its velocity is a directed magnitude, a +vector. Again a force has a certain magnitude +\PageSep{127} +and has a definite direction. Thus, +when in analytical geometry the ideas of the +``origin,'' of ``coordinates,'' and of ``vectors'' +are introduced, we are studying the +abstract conceptions which correspond to the +fundamental facts of the physical world. +\PageSep{128} + + +\Chapter{X}{Conic Sections} + +\First{When} the Greek geometers had exhausted, +\index{Conic Sections|EtSeq}% +as they thought, the more obvious and interesting +properties of figures made up of +straight lines and circles, they turned to +the study of other curves; and, with their +almost infallible instinct for hitting upon +things worth thinking about, they chiefly +devoted themselves to conic sections, that +is, to the curves in which planes would cut +the surfaces of circular cones. The man +who must have the credit of inventing the +study is Menaechmus (born 375~\BC\ and +\index{Menaechmus}% +died 325~\BC); he was a pupil of Plato +and one of the tutors of Alexander the +Great. Alexander, by the by, is a conspicuous +\index{Alexander the Great}% +example of the advantages of good +tuition, for another of his tutors was the +philosopher Aristotle. We may suspect that +\index{Aristotle}% +Alexander found Menaechmus rather a dull +teacher, for it is related that he asked for the +\PageSep{129} +proofs to be made shorter. It was to this +request that Menaechmus replied: ``In the +\index{Menaechmus}% +country there are private and even royal +roads, but in geometry there is only one road +for all.'' This reply no doubt was true +enough in the sense in which it would have +been immediately understood by Alexander. +But if Menaechmus thought that his proofs +could not be shortened, he was grievously +mistaken; and most modern mathematicians +would be horribly bored, if they were compelled +to study the Greek proofs of the properties +of conic sections. Nothing illustrates +better the gain in power which is obtained by +the introduction of relevant ideas into a +science than to observe the progressive +shortening of proofs which accompanies the +growth of richness in idea. There is a certain +type of mathematician who is always +rather impatient at delaying over the ideas +of a subject: he is anxious at once to get on +to the proofs of ``important'' problems. The +history of the science is entirely against him. +There are royal roads in science; but those +who first tread them are men of genius and +\index{Alexander the Great}% +not kings. + +The way in which conic sections first presented +themselves to mathematicians was as +follows: think of a cone (\cf\ \Fig[fig.]{15}), whose +vertex (or point) is~$V$, standing on a circular +base~$STU$. For example, a conical shade to +\PageSep{130} +an electric light is often an example of such a +surface. Now let the ``generating'' lines +which pass through~$V$ and lie on the surface +be all produced backwards; the result is a +double cone, and $PQR$~is another circular cross +section on the opposite side of~$V$ to the cross +section~$STU$. The axis of the cone~$CVC'$ +passes through all the centres of these circles +and is perpendicular to their planes, which +are parallel to each other. In the diagram +the parts of the curves which are supposed +to lie behind the plane of the paper are dotted +lines, and the parts on the plane or in front +of it are continuous lines. Now suppose this +double cone is cut by a plane not perpendicular +to the axis~$CVC'$, or at least not +necessarily perpendicular to it. Then three +cases can arise:--- + +(1) The plane may cut the cone in a closed +\index{Ellipse|EtSeq}% +oval curve, such as~$ABA'B'$ which lies entirely +on one of the two half-cones. In this +case the plane will not meet the other half-cone +at all. Such a curve is called an ellipse; it is +an oval curve. A particular case of such a +section of the cone is when the plane is perpendicular +to the axis~$CVC'$, then the section, +such as $STU$ or $PQR$, is a circle. Hence a +\index{Circle}% +circle is a particular case of the ellipse. + +(2) The plane may be parallelled to a tangent +plane touching the cone along one of its ``generating'' +lines as for example the plane of the +\PageSep{131} +\index{Parabola|EtSeq}% +curve $D_{1}A_{1}D_{1}'$ in the diagram is parallel to +the tangent plane touching the cone along the +generating line~$VS$; the curve is still confined +to one of the half-cones, but it is now not a +closed oval curve, it goes on endlessly as long +as the generating lines of the half-cone are +produced away from the vertex. Such a +conic section is called parabola. + +(3) The plane may cut both the half-cones, +\index{Hyperbola|EtSeq}% +so that the complete curve consists of two +detached portions, or ``branches'' as they +are called, this case is illustrated by the two +branches $G_{2}A_{2}G_{2}'$ and $L_{2}A_{2}'L_{2}'$ which together +make up the curve. Neither branch is closed, +each of them spreading out endlessly as the +two half-cones are prolonged away from the +vertex. Such a conic section is called a +hyperbola. + +There are accordingly three types of conic +sections, namely, ellipses, parabolas, and +hyperbolas. It is easy to see that, in a sense, +parabolas are limiting cases lying between +ellipses and hyperbolas. They form a more +special sort and have to satisfy a more particular +condition. These three names are +apparently due to Apollonius of Perga (born +\index{Apollonius of Perga}% +about 260~\BC, and died about 200~\BC), who +wrote a systematic treatise on conic sections +which remained the standard work till the +sixteenth century. +%[** TN: Moved to top of paragraph] +\Figure{15} + +It must at once be apparent how awkward +\PageSep{132} +and difficult the investigation of the properties +of these curves must have been to the +Greek geometers. The curves are plane +curves, and yet their investigation involves +the drawing in perspective of a solid figure. +Thus in the diagram given above we have +practically drawn no subsidiary lines and yet +the figure is sufficiently complicated. The +\PageSep{133} +curves are plane curves, and it seems obvious +that we should be able to define them without +\Figure{16} +going beyond the plane into a solid figure. +At the same time, just as in the ``solid'' +\Figure[2.5in]{17} +definition there is one uniform method of +definition---namely, the section of a cone by +\PageSep{134} +a plane---which yields three cases, so in any +``plane'' definition there also should be one +uniform method of procedure which falls into +three cases. Their shapes when drawn on +their planes are those of the curved lines in +the three figures \FigNum{16},~\FigNum{17}, and~\FigNum{18}. The +points $A$~and~$A'$ in the figures are called +%[** TN: Labels A, A', M, and line PM added to match the text] +\Figure[4in]{18} +the vertices and the line~$AA'$ the major axis. +It will be noted that a parabola (\cf\ \Fig[fig.]{17}) +\index{Apollonius of Perga}% +\index{Vertex}% +has only one vertex. Apollonius proved\footnote + {\Chg{Cf.}{\Cf}\ Ball, \Foreign{loc.\ cit.}, for this account of Apollonius and + Pappus.} +that +the ratio of $PM^{2}$ to $AM·MA'$ $\left(\ie\ \dfrac{PM^{2}}{AM·\Typo{MA}{MA'}}\right)$ +remains constant both for the ellipse and the +hyperbola (figs.\ \FigNum{16} and \FigNum{18}), and that the ratio +\PageSep{135} +of $PM^{2}$ to~$AM$ is constant for the parabola +of \Fig[fig.]{17}; and he bases most of his work +on this fact. We are evidently advancing +towards the desired uniform definition which +does not go out of the plane; but have not +yet quite attained to uniformity. + +In the diagrams \FigNum{16} and~\FigNum{18}, two points, $S$ +and~$S'$, will be seen marked, and in \Fig[diagram]{17} +one point,~$S$. These are the \emph{foci} of the curves, +and are points of the greatest importance. +Apollonius knew that for an ellipse the sum +of $SP$ and~$S'P$ (\ie\ $SP + S'P$) is constant as +$P$~moves on the curve, and is equal to~$AA'$. +Similarly for a hyperbola the difference $S'P - SP$ +is constant, and equal to~$AA'$ when $P$~is +on one branch, and the difference $SP' - S'P'$ +is constant and equal to~$AA'$ when $P'$~is on +the other branch. But no corresponding +point seemed to exist for the parabola. + +Finally $500$~years later the last great Greek +geometer, Pappus of Alexandria, discovered +\index{Pappus}% +the final secret which completed this line of +thought. In the diagrams \FigNum{16} and~\FigNum{18} will be +seen two lines, $XN$~and~$X'N'$, and in \Fig[diagram]{17} +the single line,~$XN$. These are the directrices +of the curves, two each for the ellipse +and the hyperbola, and one for the parabola. +Each directrix corresponds to its nearer focus. +\index{Directrix}% +\index{Focus}% +The characteristic property of a focus,~$S$, and +its corresponding directrix,~$XN$, for any one +of the three types of curve, is that the ratio +\PageSep{136} +$SP$ to~$PN$ $\left(\ie\ \dfrac{SP}{PN}\right)$ is constant, where $PN$~is +the perpendicular on the directrix from~$P$, +and $P$~is any point on the curve. Here we +have finally found the desired property of the +curves which does not require us to leave +the plane, and is stated uniformly for all +three curves. For ellipses the ratio\footnote + {\Chg{Cf.}{\Cf}\ Note~B, \Pageref{noteB}.\Pagelabel{136}} +is less +than~$1$, for parabolas it is equal to~$1$, and for +hyperbolas it is greater than~$1$. + +When Pappus had finished his investigations, +\index{Pappus}% +he must have felt that, apart from +minor extensions, the subject was practically +exhausted; and if he could have foreseen +the history of science for more than a thousand +years, it would have confirmed his belief. +Yet in truth the really fruitful ideas in connection +with this branch of mathematics had +not yet been even touched on, and no one +had guessed their supremely important applications +in nature. No more impressive +warning can be given to those who would +confine knowledge and research to what is +apparently useful, than the reflection that +conic sections were studied for eighteen hundred +years merely as an abstract science, +without a thought of any utility other than +to satisfy the craving for knowledge on the +part of mathematicians, and that then at the +end of this long period of abstract study, they +\PageSep{137} +were found to be the necessary key with +which to attain the knowledge of one of the +most important laws of nature. + +Meanwhile the entirely distinct study of +astronomy had been going forward. The +\index{Astronomy}% +great Greek astronomer Ptolemy (died 168~\AD) +\index{Ptolemy}% +published his standard treatise on the +subject in the University of Alexandria, explaining +the apparent motions among the +fixed stars of the sun and planets by the conception +of the earth at rest and the sun and +the planets circling round it. During the +next thirteen hundred years the number and +the accuracy of the astronomical observations +increased, with the result that the description +of the motions of the planets on +Ptolemy's hypothesis had to be made more +and more complicated. Copernicus (born +\index{Copernicus}% +1473~\AD\ and died 1543~\AD) pointed out +that the motions of these heavenly bodies +could be explained in a simpler manner if the +sun were supposed to rest, and the earth and +planets were conceived as moving round it. +However, he still thought of these motions as +essentially circular, though modified by a set +of small corrections arbitrarily superimposed +on the primary circular motions. So the +matter stood when Kepler was born at Stuttgart +\index{Kepler}% +in Germany in 1571~\AD. There were +two sciences, that of the geometry of conic +sections and that of astronomy, both of which +\PageSep{138} +had been studied from a remote antiquity +without a suspicion of any connection between +the two. Kepler was an astronomer, +\index{Kepler}% +but he was also an able geometer, and on the +subject of conic sections had arrived at ideas +in advance of his time\Add{.} He is only one of +many examples of the falsity of the idea that +success in scientific research demands an exclusive +absorption in one narrow line of study. +Novel ideas are more apt to spring from +an unusual assortment of knowledge---not +necessarily from vast knowledge, but from a +thorough conception of the methods and ideas +of distinct lines of thought. It will be remembered +that Charles Darwin was helped +\index{Darwin}% +to arrive at his conception of the law of +evolution by reading Malthus' famous \Title{Essay +\index{Malthus}% +on Population}, a work dealing with a different +subject---at least, as it was then +thought. + +Kepler enunciated three laws of planetary +\index{Kepler's Laws}% +motion, the first two in~1609, and the third +ten years later. They are as follows: + +(1) The orbits of the planets are ellipses, +the sun being in the focus. + +(2) As a planet moves in its orbit, the +radius vector from the sun to the planet +sweeps out equal areas in equal times. + +(3) The squares of the periodic times of the +several planets are proportional to the cubes +of their major axes. +\PageSep{139} + +These laws proved to be only a stage towards +a more fundamental development of +ideas. Newton (born 1642~\AD\ and died +\index{Newton}% +1727~\AD) conceived the idea of universal +gravitation, namely, that any two pieces of +\index{Gravitation}% +matter attract each other with a force proportional +to the product of their masses and +inversely proportional to the square of their +distance from each other. This sweeping +general law, coupled with the three laws of +motion which he put into their final general +shape, proved adequate to explain all astronomical +phenomena, including Kepler's laws, +and has formed the basis of modern physics. +Among other things he proved that comets +might move in very elongated ellipses, or in +parabolas, or in hyperbolas, which are nearly +parabolas. The comets which return---such +as Halley's comet---must, of course, move in +\index{Halley}% +ellipses. But the essential step in the proof of +the law of gravitation, and even in the suggestion +of its initial conception, was the verification +of Kepler's laws connecting the +motions of the planets with the theory of +conic sections. + +From the seventeenth century onwards the +abstract theory of the curves has shared in +the double renaissance of geometry due to +the introduction of coordinate geometry and +of projective geometry. In projective geometry +\index{Projective Geometry}% +the fundamental ideas cluster round +\PageSep{140} +the consideration of sets (or pencils, as they +\index{Pencils}% +are called) of lines passing through a common +point (the vertex of the ``pencil''). Now +(\cf\ \Fig[fig.]{19}) if $A$,~$B$, $C$,~$D$, be any four fixed +points on a conic section and $P$~be a variable +point on the curve, the pencil of lines $PA$, +\Figure[2.5in]{19} +$PB$, $PC$, and~$PD$, has a special property, +known as the constancy of its cross ratio. It +\index{Cross Ratio}% +will suffice here to say that cross ratio is a +fundamental idea in projective geometry. +For projective geometry this is really the definition +of the curves, or some analogous property +which is really equivalent to it. It +\PageSep{141} +will be seen how far in the course of ages of +study we have drifted away from the old +original idea of the sections of a circular cone. +We know now that the Greeks had got hold +of a minor property of comparatively slight +importance; though by some divine good +fortune the curves themselves deserved all +the attention which was paid to them. This +unimportance of the ``section'' idea is now +marked in ordinary mathematical phraseology +by dropping the word from their +names. As often as not, they are now +named merely ``conics'' instead of ``conic +sections.'' + +Finally, we come back to the point at +\index{Locus}% +which we left coordinate geometry in the last +chapter. We had asked what was the type +of \emph{loci} corresponding to the general algebraic +form $ax + by = c$, and had found that it was +the class of straight lines in the plane. We +had seen that every straight line possesses an +equation of this form, and that every equation +of this form corresponds to a straight line. +We now wish to go on to the next general +type of algebraic forms. This is evidently +to be obtained by introducing terms involving +$x^{2}$~and $xy$ and~$y^{2}$. Thus the new general +form must be written\Add{:}--- +\[ +ax^{2} + 2hxy + by^{2} + 2gx + 2fy + c = 0\Add{.} +\] +What does this represent? The answer is +\PageSep{142} +that (when it represents any locus) it always represents +a conic section, and, furthermore, +that the equation of every conic section can +always be put into this shape. The discrimination +of the particular sorts of conics as given +by this form of equation is very easy. It entirely +depends upon the consideration of $ab - h^{2}$, +where $a$,~$b$, and~$h$, are the ``constants'' as +written above. If $ab - h^{2}$ is a positive number, +the curve is an ellipse; if $ab - h^{2} = 0$, the curve +is a parabola: and if $ab - h^{2}$ is a negative +number, the curve is a hyperbola. + +For example, put $a = b = 1$, $h = g = f = 0$, +$c = -4$. We then get the equation $x^{2} + y^{2} - 4 = 0$. +It is easy to prove that this is the equation +of a circle, whose centre is at the origin, +and radius is $2$~units of length. Now $ab - h^{2}$ +becomes $1 × 1 - 0^{2}$, that is,~$1$, and is therefore +positive. Hence the circle is a particular +case of an ellipse, as it ought to be. Generalising, +the equation of any circle can be +put into the form $a(x^{2} + y^{2}) + 2gx + 2fy + c = 0$. +Hence $ab - h^{2}$ becomes $a^{2} - 0$, that is,~$a^{2}$, +which is necessarily positive. Accordingly +all circles satisfy the condition for ellipses. +The general form of the equation of a parabola +is +\[ +(dx + ey)^{2} + 2gx + 2fy + c = 0, +\] +so that the terms of the second degree, as +\PageSep{143} +they are called, can be written as a perfect +square. For squaring out, we get +\[ +d^{2} x^{2} + 2dexy + e^{2} y^{2} + 2gx + 2fy + c; +\] +so that by comparison $a = d^{2}$, $h = de$, $b = e^{2}$, +and therefore $ab - h^{2} = d^{2} e^{2} - (de)^{2} = 0$. Hence +the necessary condition is automatically satisfied. +The equation $2xy - 4 = 0$, where $a = b = g = f = 0$, +$h = 1$, $c = -4$, represents a hyperbola. +For the condition $ab - h^{2}$ becomes +$0 - 1^{2}$, that is,~$-1$, which is negative. + +{\Loosen The limitation, introduced by saying that, +\index{Circular Cylinder}% +\emph{when the general equation represents any locus}, +it represents a conic section, is necessary, because +some particular cases of the general +equation represent no real locus. For example +$x^{2} + y^{2} + 1 = 0$ can be satisfied by no +real values of $x$~and~$y$. It is usual to say that +the locus is now one composed of imaginary +points. But this idea of imaginary points in +geometry is really one of great complexity, +which we will not now enter into.} + +Some exceptional cases are included in the +general form of the equation which may not +be immediately recognized as conic sections. +By properly choosing the constants the equation +can be made to represent two straight +lines. Now two intersecting straight lines +may fairly be said to come under the Greek +idea of a conic section. For, by referring to +\PageSep{144} +the picture of the double cone above, it will +be seen that some planes through the vertex,~$V$, +will cut the cone in a pair of straight lines +intersecting at~$V$. The case of two parallel +straight lines can be included by considering +a circular cylinder as a particular case of a +cone. Then a plane, which cuts it and is +parallel to its axis, will cut it in two parallel +straight lines. Anyhow, whether or no the +%[** TN: [sic] "Greek", not "Greeks"] +ancient Greek would have allowed these +special cases to be called conic sections, they +are certainly included among the curves represented +by the general algebraic form of +the second degree. This fact is worth noting; +for it is characteristic of modern mathematics +to include among general forms all sorts of +particular cases which would formerly have +received special treatment. This is due to +its pursuit of generality. +\PageSep{145} + + +\Chapter{XI}{Functions} + +\First{The} mathematical use of the term function +%[** TN: Index entry reads "p. 144" in the original] +\index{Function|EtSeq}% +has been adopted also in common life. For +example, ``His temper is a function of his +digestion,'' uses the term exactly in this +mathematical sense. It means that a rule +can be assigned which will tell you what his +temper will be when you know how his +digestion is working. Thus the idea of a +``function'' is simple enough, we only have +to see how it is applied in mathematics to +variable numbers. Let us think first of some +concrete examples: If a train has been travelling +at the rate of twenty miles per hour, the +distance ($s$~miles) gone after any number of +hours, say~$t$, is given by $s = 20 × t$; and $s$~is +called a function of~$t$. Also $20 × t$ is the function +of~$t$ with which $s$~is identical. If John +is one year older than Thomas, then, when +Thomas is at any age of $x$~years, John's age +($y$~years) is given by $y = x + 1$; and $y$~is a +function of~$x$, namely, is the function~$x + 1$. + +In these examples $t$ and~$x$ are called the +\PageSep{146} +\index{Argument of a Function}% +\index{Value of a Function}% +``arguments'' of the functions in which they +appear. Thus $t$~is the argument of the function +$20 × t$, and $x$~is the argument of the function +$x + 1$. If $s = 20 × t$, and $y = x + 1$, then $s$ +and~$y$ are called the ``values'' of the functions +$20 × t$ and $x + 1$ respectively. + +Coming now to the general case, we can +define a function in mathematics as a correlation +between two variable numbers, called +respectively the argument and the value of +the function, such that whatever value be +assigned to the ``argument of the function'' +the ``value of the function'' is definitely +(\ie~uniquely) determined. The converse +is not necessarily true, namely, that when +the value of the function is determined +the argument is also uniquely determined. +Other functions of the argument~$x$ are $y = x^{2}$, +%[** TN: log, sin italicized throughout in the original] +$y = 2x^{2} + 3x + 1$, $y = x$, $y = \log x$, $y = \sin x$. The +last two functions of this group will be +readily recognizable by those who understand +a little algebra and trigonometry. It is not +worth while to delay now for their explanation, +as they are merely quoted for the sake +of example. + +Up to this point, though we have defined +what we mean by a function in general, we +have only mentioned a series of special functions. +But mathematics, true to its general +methods of procedure, symbolizes the general +idea of any function. It does this by writing +\PageSep{147} +\index{Variable Function}% +$F(x)$, $f(x)$, $g(x)$, $\phi(x)$,~etc., for any function of~$x$, +where the argument~$x$ is placed in a bracket, +and some letter like $F$,~$f$, $g$, $\phi$,~etc., is prefixed +to the bracket to stand for the function. +This notation has its defects. Thus it obviously +clashes with the convention that the +single letters are to represent variable numbers; +since here $F$,~$f$, $g$, $\phi$,~etc., prefixed to a +bracket stand for variable functions. It +would be easy to give examples in which we +can only trust to common sense and the context +to see what is meant. One way of +evading the confusion is by using Greek +letters (\eg~$\phi$ as above) for functions; another +way is to keep to $f$~and~$F$ (the initial +letter of function) for the functional letter, +and, if other variable functions have to be +symbolized, to take an adjacent letter like~$g$. + +With these explanations and cautions, we +write $y = f(x)$, to denote that $y$~is the value of +some undetermined function of the argument~$x$; +where $f(x)$ may stand for anything such +as $x + 1$, $x^{2} - 2x + 1$, $\sin x$, $\log x$, or merely for +$x$~itself. The essential point is that when $x$~is +given, then $y$~is thereby definitely determined. +It is important to be quite clear as +to the generality of this idea. Thus in $y = f(x)$, +we may determine, if we choose, $f(x)$~to +mean that when $x$~is an integer, $f(x)$~is zero, +and when $x$~has any other value, $f(x)$~is~$1$. +Accordingly, putting $y = f(x)$, with this choice +\PageSep{148} +for the meaning of~$f$, $y$~is either $0$ or~$1$ according +as the value of~$x$ is integral or otherwise. +Thus $f(1) = 0$, $f(2) = 0$, $f(\frac{2}{3}) = 1$, $f(\sqrt{2}) = 1$, and +so on. This choice for the meaning of~$f(x)$ +gives a perfectly good function of the argument~$x$ +according to the general definition of +a function. + +A function, which after all is only a sort +\index{Graphs|EtSeq}% +of correlation between two variables, is represented +like other correlations by a graph, +that is in effect by the methods of coordinate +geometry. For example, \Fig[fig.]{2} in \ChapRef{II}.\ +is the graph of the function~$\dfrac{1}{v}$ where $v$~is the +argument and $p$~the value of the function. +In this case the graph is only drawn for +positive values of~$v$, which are the only values +possessing any meaning for the physical application +considered in that chapter. Again +in \Fig[fig.]{14} of \ChapRef{IX}.\ the whole length of +the line~$AB$, unlimited in both directions, is +the graph of the function~$x + 1$, where $x$~is the +argument and $y$~is the value of the function; +and in the same figure the unlimited line~$A_{1}B$ +is the graph of the function~$1 - x$, and +the line~$LOL'$ is the graph of the function~$x$, +$x$~being the argument and $y$~the value of the +function. + +These functions, which are expressed by +simple algebraic formulæ, are adapted for representation +by graphs. But for some functions +\PageSep{149} +this representation would be very +misleading without a detailed explanation, or +might even be impossible. Thus, consider the +function mentioned above, which has the value~$1$ +for all values of its argument~$x$, except +those which are integral, \eg\ except for $x = 0$, +$x = 1$, $x = 2$, etc., when it has the value~$0$. +Its appearance on a graph would be that of +the straight line~$ABA'$ drawn parallel to the +\Figure{20} +axis~$XOX'$ at a distance from it of $1$~unit of +length. But the points, $B$,~$C_{1}$, $C_{2}$, $C_{3}$, $C_{4}$,~etc., +corresponding to the values $0$,~$1$, $2$, $3$, $4$,~etc., of +the argument~$x$, are to be omitted, and instead +of them the points $O$,~$B_{1}$, $B_{2}$, $B_{3}$, $B_{4}$,~etc., +on the axis~$OX$, are to be taken. It is easy +to find functions for which the graphical representation +is not only inconvenient but +impossible. Functions which do not lend +themselves to graphs are important in the +\PageSep{150} +higher mathematics, but we need not concern +ourselves further about them here. + +The most important division between functions +\index{Continuous Functions|EtSeq}% +\index{Discontinuous Functions|EtSeq}% +is that between continuous and discontinuous +functions. A function is continuous +when its value only alters gradually for +gradual alterations of the argument, and is +discontinuous when it can alter its value by +sudden jumps. Thus the two functions $x + 1$ +and $1 - x$, whose graphs are depicted as +straight lines in \Fig[fig.]{14} of \ChapRef{IX}., are continuous +functions, and so is the function~$\dfrac{1}{v}$, +depicted in \ChapRef{II}., if we only think of +positive values of~$v$. But the function depicted +in \Fig[fig.]{20} of this chapter is discontinuous +since at the values $x = 1$, $x = 2$, etc., of its +argument, its value gives sudden jumps. + +Let us think of some examples of functions +presented to us in nature, so as to get into +our heads the real bearing of continuity and +discontinuity. Consider a train in its journey +along a railway line, say from Euston Station, +the terminus in London of the London and +North-Western Railway. Along the line in +order lie the stations of Bletchley and Rugby. +Let $t$~be the number of hours which the train +has been on its journey from Euston, and $s$~be +the number of miles passed over. Then $s$~is +a function of~$t$, \ie~is the variable value +corresponding to the variable argument~$t$. +\PageSep{151} +If we know the circumstances of the train's +run, we know~$s$ as soon as any special value +of~$t$ is given. Now, miracles apart, we may +confidently assume that $s$~is a continuous +function of~$t$. It is impossible to allow for +the contingency that we can trace the train +continuously from Euston to Bletchley, and +that then, without any intervening time, however +short, it should appear at Rugby. The +idea is too fantastic to enter into our calculation: +it contemplates possibilities not to be +found outside the \Title{Arabian Nights}; and even +in those tales sheer discontinuity of motion +hardly enters into the imagination, they do +not dare to tax our credulity with anything +more than very unusual speed. But unusual +speed is no contradiction to the great law of +continuity of motion which appears to hold +in nature. Thus light moves at the rate of +about $190,000$ miles per~second and comes to +us from the sun in seven or eight minutes; +but, in spite of this speed, its distance travelled +is always a continuous function of the time. + +It is not quite so obvious to us that the +velocity of a body is invariably a continuous +function of the time. Consider the train at +any time~$t$: it is moving with some definite +velocity, say $v$~miles per~hour, where $v$~is +zero when the train is at rest in a station and +is negative when the train is backing. Now +we readily allow that $v$~cannot change its +\PageSep{152} +value suddenly for a big, heavy train. The +train certainly cannot be running at forty +miles per hour from 11.45~a.m.\ up to noon, +and then suddenly, without any lapse of time, +commence running at $50$~miles per~hour. We +at once admit that the change of velocity +will be a gradual process. But how about +sudden blows of adequate magnitude? Suppose +two trains collide; or, to take smaller +objects, suppose a man kicks a football. It +certainly appears to our sense as though the +football began suddenly to move. Thus, in +the case of velocity our senses do not revolt +at the idea of its being a discontinuous function +of the time, as they did at the idea of the +train being instantaneously transported from +Bletchley to Rugby. As a matter of fact, +if the laws of motion, with their conception +of mass, are true, there is no such thing as +discontinuous velocity in nature. Anything +that appears to our senses as discontinuous +change of velocity must, according to them, +be considered to be a case of gradual change +which is too quick to be perceptible to us. +It would be rash, however, to rush into the +generalization that no discontinuous functions +are presented to us in nature. A man who, +trusting that the mean height of the land +above sea-level between London and Paris +was a continuous function of the distance +from London, walked at night on Shakespeare's +\PageSep{153} +Cliff by Dover in contemplation of +the Milky Way, would be dead before he had +had time to rearrange his ideas as to the +necessity of caution in scientific conclusions. + +It is very easy to find a discontinuous +function, even if we confine ourselves to the +\Figure{21} +simplest of the algebraic formulæ. For example, +take the function $y = \dfrac{1}{x}$, which we +have already considered in the form $p = \dfrac{1}{v}$, +where $v$~was confined to positive values. But +\PageSep{154} +now let $x$ have any value, positive or negative. +The graph of the function is exhibited in \Fig[fig.]{21}. +Suppose $x$ to change continuously from +a large negative value through a numerically +decreasing set of negative values up to~$0$, and +thence through the series of increasing positive +values. Accordingly, if a moving point,~$M$, +represents~$x$ on~$XOX'$, $M$~starts at the +extreme left of the axis~$XOX'$ and successively +moves through $M_{1}$,~$M_{2}$, $M_{3}$, $M_{4}$,~etc. +The corresponding points on the function are +$P_{1}$,~$P_{2}$, $P_{3}$, $P_{4}$,~etc. It is easy to see that +there is a point of discontinuity at $x = 0$, \ie~at +the origin~$O$. For the value of the function +on the negative (left) side of the origin becomes +endlessly great, but negative, and the +function reappears on the positive (right) +side as endlessly great but positive. Hence, +however small we take the length~$M_{2} M_{3}$, +there is a finite jump between the values of +the function at $M_{2}$ and~$M_{3}$. Indeed, this case +has the peculiarity that the smaller we take the +length between $M_{2}$ and~$M_{3}$, so long as they +enclose the origin, the bigger is the jump in +value of the function between them. This +graph brings out, what is also apparent in +\Fig[fig.]{20} of this chapter, that for many functions +the discontinuities only occur at isolated +points, so that by restricting the values of the +argument we obtain a continuous function for +these remaining values. Thus it is evident +\PageSep{155} +from \Fig[fig.]{21} that in $y = \dfrac{1}{x}$, if we keep to positive +values only and exclude the origin, we obtain +a continuous function. Similarly the same +function, if we keep to negative values only, +excluding the origin, is continuous. Again +the function which is graphed in \Fig[fig.]{20} is continuous +between $B$ and~$C_{1}$, and between $C_{1}$ +and~$C_{2}$, and between $C_{2}$ and $C_{3}$, and so on, +always in each case excluding the end points. +It is, however, easy to find functions such that +their discontinuities occur at all points. For +example, consider a function~$f(x)$, such that +when $x$~is any fractional number $f(x) = 1$, and +when $x$~is any incommensurable number +$f(x) = 2$. This function is discontinuous at all +points. + +Finally, we will look a little more closely +at the definition of continuity given above. +We have said that a function is continuous +when its value only alters gradually for +gradual alterations of the argument, and is +discontinuous when it can alter its value by +sudden jumps. This is exactly the sort of +definition which satisfied our mathematical +forefathers and no longer satisfies modern +mathematicians. It is worth while to spend +some time over it; for when we understand +the modern objections to it, we shall have +gone a long way towards the understanding +of the spirit of modern mathematics. The +\PageSep{156} +whole difference between the older and the +newer mathematics lies in the fact that vague +half-metaphorical terms like ``gradually'' +are no longer tolerated in its exact statements. +Modern mathematics will only admit statements +and definitions and arguments which +exclusively employ the few simple ideas about +number and magnitude and variables on +which the science is founded. Of two numbers +one can be greater or less than the +other; and one can be such and such a multiple +of the other; but there is no relation of +``graduality'' between two numbers, and +hence the term is inadmissible. Now this +may seem at first sight to be great pedantry. +To this charge there are two answers. In +the first place, during the first half of the +nineteenth century it was found by some +great mathematicians, especially Abel in +\index{Abel}% +Sweden, and Weierstrass in Germany, that +\index{Weierstrass}% +large parts of mathematics as enunciated in +the old happy-go-lucky manner were simply +wrong. Macaulay in his essay on Bacon +\index{Bacon}% +\index{Macaulay}% +contrasts the certainty of mathematics with +the uncertainty of philosophy; and by way +of a rhetorical example he says, ``There has +been no reaction against Taylor's theorem.'' +\index{Taylor's Theorem}% +He could not have chosen a worse example. +For, without having made an examination of +English text-books on mathematics contemporary +with the publication of this essay, the +\PageSep{157} +\index{Taylor's Theorem}% +assumption is a fairly safe one that Taylor's +theorem was enunciated and proved wrongly +in every one of them. Accordingly, the +anxious precision of modern mathematics is +necessary for accuracy. In the second place +it is necessary for research. It makes for +clearness of thought, and thence for boldness +of thought and for fertility in trying new +combinations of ideas. When the initial +statements are vague and slipshod, at every +subsequent stage of thought common sense +has to step in to limit applications and to +explain meanings. Now in creative thought +common sense is a bad master. Its sole +criterion for judgment is that the new ideas +shall look like the old ones. In other words +it can only act by suppressing originality. + +In working our way towards the precise +definition of continuity (as applied to functions) +let us consider more closely the statement +that there is no relation of ``graduality'' +between numbers. It may be asked, Cannot +one number be only slightly greater than +another number, or in other words, cannot +the difference between the two numbers be +small? The whole point is that in the abstract, +apart from some arbitrarily assumed +application, there is no such thing as a great +or a small number. A million miles is a +small number of miles for an astronomer +investigating the fixed stars, but a million +\PageSep{158} +pounds is a large yearly income. Again, one-quarter +is a large fraction of one's income to +give away in charity, but is a small fraction +of it to retain for private use. Examples can +be accumulated indefinitely to show that +great or small in any absolute sense have no +abstract application to numbers. We can +say of two numbers that one is greater or +smaller than another, but not without specification +of particular circumstances that any +one number is great or small. Our task +therefore is to define continuity without any +mention of a ``small'' or ``gradual'' change +in value of the function. + +In order to do this we will give names to +some ideas, which will also be useful when +we come to consider limits and the differential +calculus. + +An ``interval'' of values of the argument~$x$ +\index{Interval|EtSeq}% +of a function~$f(x)$ is all the values lying +between some two values of the argument. +For example, the interval between $x = 1$ and +$x = 2$ consists of all the values which~$x$ can +take lying between $1$ and~$2$, \ie\ it consists of +all the real numbers between $1$ and~$2$. But +the bounding numbers of an interval need +not be integers. An interval of values of the +argument \emph{contains} a number~$a$, when $a$~is a +member of the interval. For example, the +interval between $1$ and~$2$ contains $\frac{3}{2}$, $\frac{5}{3}$, $\frac{7}{4}$, and +so on. +\PageSep{159} + +A set of numbers approximates to a number~$a$ +\index{Standard of Approximation|EtSeq}% +within a \emph{standard}~$k$, when the numerical +difference between $a$ and every number of the +set is less than~$k$. Here $k$~is the ``standard +of approximation.'' Thus the set of numbers +$3$,~$4$, $6$,~$8$, approximates to the number~$5$ +within the standard~$4$. In this case the +standard~$4$ is not the smallest which could +have been chosen, the set also approximates +%[** TN: Original uses center dot for decimal point] +to~$5$ within any of the standards $3.1$ or $3.01$ +or~$3.001$. Again, the numbers, $3.1$, $3.141$, +$3.1415$, $3.14159$ approximate to $3.13102$ within +the standard~$.032$, and also within the +smaller standard~$.03103$. + +These two ideas of an interval and of +\index{Neighbourhood|EtSeq}% +approximation to a number within a standard +are easy enough; their only difficulty is that +they look rather trivial. But when combined +with the next idea, that of the ``neighbourhood'' +of a number, they form the foundation +of modern mathematical reasoning. What +do we mean by saying that something is true +for a function~$f(x)$ in the neighbourhood of +the value~$a$ of the argument~$x$? It is this +fundamental notion which we have now got to +make precise. + +The values of a function~$f(x)$ are said to +possess a characteristic in the ``neighbourhood +of~$a$'' when some interval can be found, +which (i)~contains the number~$a$ not as an +end-point, and (ii)~is such that every value +\PageSep{160} +of the function for arguments, other than~$a$, +lying within that interval possesses the characteristic. +The value~$f(a)$ of the function for +the argument~$a$ may or may not possess the +characteristic. Nothing is decided on this +point by statements about the \emph{neighbourhood} +of~$a$. + +For example, suppose we take the particular +function~$x^{2}$. Now \emph{in the neighbourhood of~$2$}, +the values of~$x^{2}$ are less than~$5$. For we can +find an interval, \eg\ from $1$ to~$2.1$, which +(i)~contains $2$ not as an end-point, and (ii)~is +such that, for values of~$x$ lying within it, $x^{2}$~is +less than~$5$. + +Now, combining the preceding ideas we +know what is meant by saying that \emph{in the +neighbourhood of~$a$} the function~$f(x)$ approximates +to~$c$ within the \emph{standard}~$k$. It means +that some interval can be found which (i)~includes +$a$ not as an end-point, and (ii)~is such +that all values of~$f(x)$, where $x$~lies in the interval +and is not~$a$, differ from~$c$ by less than~$k$. For +example, in the neighbourhood of~$2$, the function~$\sqrt{x}$ +approximates to~$1.41425$ within the +standard~$.0001$. This is true because the +square root of~$1.99996164$ is~$1.4142$ and the +square root of~$2.00024449$ is~$1.4143$; hence +for values of~$x$ lying in the interval +$1.99996164$ to~$2.00024449$, which contains $2$ +not as an end-point, the values of the function~$\sqrt{x}$ +all lie between $1.4142$ and $1.4143$, and +\PageSep{161} +they therefore all differ from~$1.41425$ by less +than~$.0001$. In this case we can, if we like, +fix a smaller standard of approximation, +namely $.000051$ or $.0000501$. Again, to take +another example, in the neighbourhood of~$2$ +the function~$x^{2}$ approximates to~$4$ within the +standard~$.5$. For $(1.9)^{2} = 3.61$ and $(2.1)^{2} = 4.41$, +and thus the required interval $1.9$ to~$2.1$, +containing $2$ not as an end-point, has +been found. This example brings out the +fact that statements about a function~$f(x)$ in +the neighbourhood of a number~$a$ are distinct +from statements about the value of~$f(x)$ when +$x = a$. The production of an \emph{interval}, throughout +which the statement is true, is required. +Thus the mere fact that $2^{2} = 4$ does not by +itself justify us in saying that in the \emph{neighbourhood} +of~$2$ the function~$x^{2}$ is equal to~$4$. +This statement would be untrue, because no +interval can be produced with the required +property. Also, the fact that $2^{2} = 4$ does not +by itself justify us in saying that in the +\emph{neighbourhood} of~$2$ the function~$x^{2}$ approximates +to~$4$ within the standard~$.5$; although +as a matter of fact, the statement has just +been proved to be true. + +If we understand the preceding ideas, we +understand the foundations of modern +mathematics. We shall recur to analogous +ideas in the chapter on Series, and again +in the chapter on the Differential Calculus. +\PageSep{162} +\index{Continuous Functions@Continuous Functions (\emph{defined})}% +Meanwhile, we are now prepared to define +``continuous functions.'' A function~$f(x)$ +is ``continuous'' at a value~$a$ of its argument, +when in the neighbourhood of~$a$ +its values approximate to~$f(a)$ (\ie~to its +value at~$a$) within \emph{every} standard of approximation. + +This means that, whatever standard~$k$ be +chosen, in the neighbourhood of~$a$ $f(x)$~approximates +to~$f(a)$ within the standard~$k$. +For example, $x^{2}$~is continuous at the value~$2$ +of its argument,~$x$, because however $k$~be +chosen we can always find an interval, which +(i)~contains $2$ not as an end-point, and (ii)~is +such that the values of~$x^{2}$ for arguments lying +within it approximate to~$4$ (\ie~$2^{2}$) within +the standard~$k$. Thus, suppose we choose +the standard~$.1$; now $(1.999)^{2} = 3.996001$, +and $(2.01)^{2} = 4.0401$, and both these numbers +differ from~$4$ by less than~$.1$. Hence, within +the interval $1.999$ to $2.01$ the values of~$x^{2}$ +approximate to~$4$ within the standard~$.1$. +Similarly an interval can be produced for any +other standard which we like to try. + +Take the example of the railway train. Its +velocity is continuous as it passes the signal +box, if whatever velocity you like to assign +(say one-millionth of a mile per hour) an interval +of time can be found extending before +and after the instant of passing, such that at +all instants within it the train's velocity +\PageSep{163} +differs from that with which the train passed +the box by less than one-millionth of a mile +per hour; and the same is true whatever +other velocity be mentioned in the place of +one-millionth of a mile per hour. +\PageSep{164} + + +\Chapter{XII}{Periodicity in Nature} + +\First{The} whole life of Nature is dominated by +\index{Periodicity|EtSeq}% +the existence of periodic events, that is, by +the existence of successive events so analogous +to each other that, without any straining of +language, they may be termed recurrences of +the same event. The rotation of the earth +produces the successive days. It is true that +each day is different from the preceding days, +however abstractly we define the meaning of +a day, so as to exclude casual phenomena. +But with a sufficiently abstract definition of +a day, the distinction in properties between +two days becomes faint and remote from +practical interest; and each day may then +be conceived as a recurrence of the phenomenon +of one rotation of the earth. Again the +path of the earth round the sun leads to the +yearly recurrence of the seasons, and imposes +another periodicity on all the operations of +nature. Another less fundamental periodicity +is provided by the phases of the moon. +In modern civilized life, with its artificial light, +these phases are of slight importance, but in +\PageSep{165} +ancient times, in climates where the days are +burning and the skies clear, human life was +apparently largely influenced by the existence of +moonlight. Accordingly our divisions into +weeks and months, with their religious associations, +have spread over the European races from +Syria and Mesopotamia, though independent +observances following the moon's phases are +found amongst most nations. It is, however, +through the tides, and not through its phases +of light and darkness, that the moon's periodicity +has chiefly influenced the history of +the earth. + +Our bodily life is essentially periodic. +It is dominated by the beatings of the +heart, and the recurrence of breathing. +The presupposition of periodicity is indeed +fundamental to our very conception of life. +We cannot imagine a course of nature in +which, as events progressed, we should be +unable to say: ``This has happened before.'' +The whole conception of experience as a guide +to conduct would be absent. Men would +always find themselves in new situations +possessing no substratum of identity with +anything in past history. The very means of +measuring time as a quantity would be absent. +Events might still be recognized as occurring +in a series, so that some were earlier and +others later. But we now go beyond this +bare recognition. We can not only say that +\PageSep{166} +\index{Time|EtSeq}% +three events, $A$,~$B$,~$C$, occurred in this order, +so that $A$~came before~$B$, and $B$~before~$C$; +but also we can say that the length of time +between the occurrences of $A$ and~$B$ was +twice as long as that between $B$ and~$C$. Now, +quantity of time is essentially dependent on +observing the number of natural recurrences +which have intervened. We may say +that the length of time between $A$ and~$B$ was +so many days, or so many months, or so +many years, according to the type of recurrence +to which we wish to appeal. Indeed, +at the beginning of civilization, these three +modes of measuring time were really distinct. +It has been one of the first tasks of science +among civilized or semi-civilized nations, to +fuse them into one coherent measure. The +full extent of this task must be grasped. It +is necessary to determine, not merely what +number of days (\eg~$365.25$\dots) go to some +one year, but also previously to determine that +the same number of days do go to the successive +years. We can imagine a world in +which periodicities exist, but such that no two +are coherent. In some years there might be +$200$~days and in others~$350$. The determination +of the broad general consistency of the +more important periodicities was the first step +in natural science. This consistency arises +from no abstract intuitive law of thought; +it is merely an observed fact of nature +\PageSep{167} +guaranteed by experience. Indeed, so far is +it from being a necessary law, that it is not +even exactly true There are divergencies in +every case. For some instances these divergencies +are easily observed and are therefore +immediately apparent. In other cases it requires +the most refined observations and +astronomical accuracy to make them apparent. +Broadly speaking, all recurrences depending +on living beings, such as the beatings +of the heart, are subject in comparison with +other recurrences to rapid variations. The +great stable obvious recurrences---stable in +the sense of mutually agreeing with great +accuracy---are those depending on the motion +of the earth as a whole, and on similar motions +of the heavenly bodies. + +We therefore assume that these astronomical +\index{Laws of Motion|EtSeq}% +recurrences mark out equal intervals of +time. But how are we to deal with their +discrepancies which the refined observations +of astronomy detect? Apparently we are +reduced to the arbitrary assumption that one +or other of these sets of phenomena marks out +equal times---\eg\ that either all days are of +equal length, or that all years are of equal +length. This is not so: some assumptions +must be made, but the assumption which +underlies the whole procedure of the astronomers +in determining the measure of time is +that the laws of motion are exactly verified. +\PageSep{168} +Before explaining how this is done, it is interesting +to observe that this relegation of +the determination of the measure of time to +the astronomers arises (as has been said) from +the stable consistency of the recurrences with +which they deal. If such a superior consistency +had been noted among the recurrences +characteristic of the human body, we +should naturally have looked to the doctors +of medicine for the regulation of our clocks. + +In considering how the laws of motion +come into the matter, note that two inconsistent +modes of measuring time will yield +different variations of velocity to the same +body. For example, suppose we define an +hour as one twenty-fourth of a day, and take +the case of a train running uniformly for two +hours at the rate of twenty miles per hour. +Now take a grossly inconsistent measure of +time, and suppose that it makes the first hour +to be twice as long as the second hour. Then, +according to this other measure of duration, +the time of the train's run is divided into +two parts, during each of which it has traversed +the same distance, namely, twenty +miles; but the duration of the first part is +twice as long as that of the second part. +Hence the velocity of the train has not been +uniform, and on the average the velocity +during the second period is twice that during +the first period. Thus the question as to +\PageSep{169} +whether the train has been running uniformly +or not entirely depends on the standard of +time which we adopt. + +Now, for all ordinary purposes of life on the +earth, the various astronomical recurrences +may be looked on as absolutely consistent; +and, furthermore assuming their consistency, +and thereby assuming the velocities and +changes of velocities possessed by bodies, we +find that the laws of motion, which have +been considered above, are almost exactly +verified. But only \emph{almost} exactly when we +come to some of the astronomical phenomena. +We find, however, that by assuming slightly +different velocities for the rotations and +motions of the planets and stars, the laws +would be exactly verified. This assumption +is then made; and we have, in fact thereby, +adopted a measure of time, which is indeed +defined by reference to the astronomical +phenomena, but not so as to be consistent +with the uniformity of any one of them. But +the broad fact remains that the uniform flow +of time on which so much is based, is itself +dependent on the observation of periodic +events. + +Even phenomena, which on the surface +seem casual and exceptional, or, on the other +hand, maintain themselves with a uniform +persistency, may be due to the remote influence +of periodicity. Take for example, the +\PageSep{170} +principle of resonance. Resonance arises +\index{Resonance}% +when two sets of connected circumstances +have the same periodicities. It is a dynamical +law that the small vibrations of all bodies +when left to themselves take place in definite +times characteristic of the body. Thus a +pendulum with a small swing always vibrates +in some definite time, characteristic of its shape +and distribution of weight and length. A more +complicated body may have many ways of +vibrating; but each of its modes of vibration +will have its own peculiar ``period.'' Those +\index{Period}% +periods of vibration of a body are called its +``free'' periods. Thus a pendulum has but +one period of vibration, while a suspension +bridge will have many. We get a musical +instrument, like a violin string, when the +periods of vibration are all simple submultiples +of the longest; \ie~if $t$~seconds be the longest +period, the others are $\frac{1}{2}t$, $\frac{1}{3}t$, and so on, where +any of these smaller periods may be absent. +Now, suppose we excite the vibrations of a +body by a cause which is itself periodic; +then, if the period of the cause is very nearly +that of one of the periods of the body, that +mode of vibration of the body is very violently +excited; even although the magnitude of the +exciting cause is small. This phenomenon is +called ``resonance.'' The general reason is +easy to understand. Any one wanting to +upset a rocking stone will push ``in tune'' +\PageSep{171} +with the oscillations of the stone, so as always +to secure a favourable moment for a push. +If the pushes are out of tune, some increase +the oscillations, but others check them. But +when they are in tune, after a time all the +pushes are favourable. The word ``resonance'' +\index{Resonance}% +comes from considerations of sound: +but the phenomenon extends far beyond the +region of sound. The laws of absorption and +emission of light depend on it, the ``tuning'' +of receivers for wireless telegraphy, the comparative +importance of the influences of +planets on each other's motion, the danger +to a suspension bridge as troops march over +it in step, and the excessive vibration of some +ships under the rhythmical beat of their +machinery at certain speeds. This coincidence +of periodicities may produce steady +phenomena when there is a constant association +of the two periodic events, or it may +produce violent and sudden outbursts when +the association is fortuitous and temporary. + +Again, the characteristic and constant +periods of vibration mentioned above are +the underlying causes of what appear to +us as steady excitements of our senses. We +work for hours in a steady light, or we listen +to a steady unvarying sound. But, if modern +science be correct, this steadiness has no +counterpart in nature. The steady light is +due to the impact on the eye of a countless +\PageSep{172} +number of periodic waves in a vibrating ether, +and the steady sound to similar waves in a +vibrating air. It is not our purpose here to +explain the theory of light or the theory of +sound. We have said enough to make it +evident that one of the first steps necessary +to make mathematics a fit instrument for the +investigation of Nature is that it should be +able to express the essential periodicity of +things. If we have grasped this, we can +understand the importance of the mathematical +conceptions which we have next to +consider, namely, periodic functions. +\PageSep{173} + + +\Chapter{XIII}{Trigonometry} + +\First{Trigonometry} did not take its rise from +\index{Trigonometry|EtSeq}% +the general consideration of the periodicity of +nature. In this respect its history is analogous +to that of conic sections, which also had +their origin in very particular ideas. Indeed, +a comparison of the histories of the two +sciences yields some very instructive analogies +and contrasts. Trigonometry, like conic sections, +had its origin among the Greeks. Its +inventor was Hipparchus (born about 160~\BC), +\index{Hipparchus}% +a Greek astronomer, who made his +observations at Rhodes. His services to +astronomy were very great, and it left his +\index{Astronomy}% +hands a truly scientific subject with important +results established, and the right method of +progress indicated. Perhaps the invention +of trigonometry was not the least of these +services to the main science of his study. The +next man who extended trigonometry was +Ptolemy, the great Alexandrian astronomer, +\index{Ptolemy}% +whom we have already mentioned. We now +\PageSep{174} +see at once the great contrast between conic +sections and trigonometry. The origin of +trigonometry was practical; it was invented +because it was necessary for astronomical research. +The origin of conic sections was +purely theoretical. The only reason for its +initial study was the abstract interest of the +ideas involved. Characteristically enough +conic sections were invented about $150$~years +earlier than trigonometry, during the very +best period of Greek thought. But the importance +of trigonometry, both to the theory +and the application of mathematics, is only +one of innumerable instances of the fruitful +ideas which the general science has gained +from its practical applications. + +We will try and make clear to ourselves +what trigonometry is, and why it should be +generated by the scientific study of astronomy. +\index{Astronomy}% +In the first place: What are the measurements +which can be made by an astronomer? +They are measurements of time and measurements +of angles. The astronomer may adjust +a telescope (for it is easier to discuss the +familiar instrument of modern astronomers) +so that it can only turn about a fixed axis +pointing east and west; the result is that +the telescope can only point to the south, with +a greater or less elevation of direction, or, if +turned round beyond the zenith, point to the +north. This is the transit instrument, the +\PageSep{175} +great instrument for the exact measurement +of the times at which stars are due south or +due north. But indirectly this instrument +measures angles. For when the time elapsed +between the transits of two stars has been +noted, by the assumption of the uniform +rotation of the earth, we obtain the angle +through which the earth has turned in that +period of time. Again, by other instruments, +the angle between two stars can be directly +measured. For if $E$~is the eye of the astronomer, +\Figure[2in]{22} +and $EA$~and $EB$ are the directions in +which the stars are seen, it is easy to devise +instruments which shall measure the angle~$AEB$. +Hence, when the astronomer is forming +a survey of the heavens, he is, in fact, +measuring angles so as to fix the relative +directions of the stars and planets at any instant. +Again, in the analogous problem of +\PageSep{176} +\index{Surveys|EtSeq}% +\index{Triangle|EtSeq}% +land-surveying, angles are the chief subject +of measurements. The direct measurements +of length are only rarely possible with any +accuracy; rivers, houses, forests, mountains, +and general irregularities of ground all get in +the way. The survey of a whole country will +depend only on one or two direct measurements +of length, made with the greatest +elaboration in selected places like Salisbury +Plain. The main work of a survey is the +measurement of angles. For example, $A$,~$B$, +and~$C$ will be conspicuous points in the district +\Figure[2in]{23} +surveyed, say the tops of church towers. +These points are visible each from the others. +Then it is a very simple matter at~$A$ to +measure the angle~$BAC$, and at~$B$ to measure +the angle~$ABC$, and at~$C$ to measure the angle~$BCA$. +Theoretically, it is only necessary to +measure two of these angles; for, by a well-known +proposition in geometry, the sum of +the three angles of a triangle amounts to two +\PageSep{177} +right-angles, so that when two of the angles +are known, the third can be deduced. It is +better, however, in practice to measure all +three, and then any small errors of observation +can be checked. In the process of map-making +a country is completely covered with +triangles in this way. This process is called +triangulation, and is the fundamental process +\index{Triangulation}% +in a survey. + +Now, when all the angles of a triangle are +\index{Similarity|EtSeq}% +known, the shape of the triangle is known---that +is, the shape as distinguished from the +size. We here come upon the great principle +of geometrical similarity. The idea is very +familiar to us in its practical applications. +We are all familiar with the idea of a plan +drawn to scale. Thus if the scale of a plan +be an inch to a yard, a length of three inches +in the plan means a length of three yards in +the original. Also the shapes depicted in the +plan are the shapes in the original, so that a +right-angle in the original appears as a right-angle +in the plan. Similarly in a map, which +is only a plan of a country, the proportions +of the lengths in the map are the proportions +of the distances between the places indicated, +and the directions in the map are the directions +in the country. For example, if in the +map one place is north-north-west of the +other, so it is in reality; that is to say, in a +map the angles are the same as in reality. +\PageSep{178} +\index{Scale of a Map}% +Geometrical similarity may be defined thus: +Two figures are similar (i)~if to any point +in one figure a point in the other figure +corresponds, so that to every line there is a +corresponding line, and to every angle a +corresponding angle, and (ii)~if the lengths +of corresponding lines are in a fixed proportion, +and the magnitudes of corresponding +angles are the same. The fixed proportion +of the lengths of corresponding lines in a map +(or plan) and in the original is called the scale +of the map. The scale should always be +indicated on the margin of every map and +plan. It has already been pointed out that +two triangles whose angles are respectively +equal are similar. Thus, if the two triangles +\Figure{24} +$ABC$ and~$DEF$ have the angles at $A$ and $D$ +equal, and those at $B$ and~$E$, and those at $C$ +and~$F$, then $DE$~is to~$AB$ in the same proportion +\PageSep{179} +as $EF$~is to~$BC$, and as $FD$~is to~$CA$. +But it is not true of other figures that similarity +is guaranteed by the mere equality of +angles. Take for example, the familiar cases +of a rectangle and a square. Let $ABCD$~be +a square, and $ABEF$~be a rectangle. Then +all the corresponding angles are equal. But +\Figure[2.75in]{25} +whereas the side~$AB$ of the square is equal to +the side~$AB$ of the rectangle, the side~$BC$ of +the square is about half the size of the side~$BE$ +of the rectangle. Hence it is not true +that the square $ABCD$ is similar to the rectangle +$ABEF$. This peculiar property of the +triangle, which is not shared by other rectilinear +figures, makes it the fundamental +figure in the theory of similarity. Hence in +surveys, triangulation is the fundamental +process; and hence also arises the word ``trigonometry,'' +\PageSep{180} +\index{Circle|EtSeq}% +derived from the two Greek +words \Foreign{trigonon} a triangle and \Foreign{metria} measurement. +The fundamental question from which +trigonometry arose is this: Given the magnitudes +of the angles of a triangle, what can be +stated as to the relative magnitudes of the +sides. Note that we say ``\emph{relative} magnitudes +of the sides,'' since by the theory of similarity +it is only the proportions of the sides which +are known. In order to answer this question, +certain functions of the magnitudes of +an angle, considered as the argument, are introduced. +In their origin these functions +were got at by considering a right-angled triangle, +and the magnitude of the angle was +defined by the length of the arc of a circle. +In modern elementary books, the fundamental +position of the arc of the circle as defining +the magnitude of the angle has been +pushed somewhat to the background, not to +the advantage either of theory or clearness +of explanation. It must first be noticed +that, in relation to similarity, the circle holds +the same fundamental position among curvilinear +figures, as does the triangle among +rectilinear figures. Any two circles are similar +figures; they only differ in scale. The +lengths of the circumferences of two circles, +such as $APA'$ and $A_{1} P_{1} A_{1}'$ in the \Fig[fig.]{26} are +in proportion to the lengths of their radii. +Furthermore, if the two circles have the same +\PageSep{181} +centre~$O$, as do the two circles in \Fig[fig.]{26}, then +the arcs $AP$ and $A_{1} P_{1}$ intercepted by the +arms of any angle~$AOP$, are also in proportion +to their radii. Hence the ratio of the +\Figure{26} +length of the arc~$AP$ to the length of the +radius~$OP$, that is $\dfrac{\text{arc } AP}{\text{radius } OP}$ is a number which +is quite independent of the length~$OP$, and is +the same as the fraction $\dfrac{\text{arc } A_{1} P_{1}}{\text{radius } OP_{1}}$. This fraction +of ``arc divided by radius'' is the proper +theoretical way to measure the magnitude of +\PageSep{182} +\index{Cosine|EtSeq}% +\index{Sine|EtSeq}% +an angle; for it is dependent on no arbitrary +unit of length, and on no arbitrary way of +dividing up any arbitrarily assumed angle, +such as a right-angle. Thus the fraction~$\dfrac{AP}{OA}$ +represents the magnitude of the angle~$AOP$. +Now draw $PM$ perpendicularly to~$OA$. Then +the Greek mathematicians called the line~$PM$ +the sine of the arc~$AP$, and the line~$OM$ the +cosine of the arc~$AP$. They were well aware +that the importance of the relations of these +various lines to each other was dependent on +the theory of similarity which we have just +expounded. But they did not make their +definitions express the properties which arise +from this theory. Also they had not in their +heads the modern general ideas respecting +functions as correlating pairs of variable numbers, +nor in fact were they aware of any +modern conception of algebra and algebraic +analysis. Accordingly, it was natural to +them to think merely of the relations between +certain lines in a diagram. For us the case +is different: we wish to embody our more +powerful ideas. + +Hence, in modern mathematics, instead +of considering the arc~$AP$, we consider +the fraction~$\dfrac{AP}{OP}$, which is a number the +same for all lengths of~$OP$; and, instead of +considering the lines $PM$ and~$OM$, we consider +\PageSep{183} +the fractions $\dfrac{PM}{OP}$ and~$\dfrac{OM}{OP}$, which again +are numbers not dependent on the length of~$OP$, +\ie~not dependent on the scale of our +diagrams. Then we define the number $\dfrac{PM}{OP}$ +to be the \emph{sine} of the number $\dfrac{PA}{OP}$, and the +number $\dfrac{OM}{OP}$ to be the \emph{cosine} of the number +$\dfrac{PA}{OP}$. These fractional forms are clumsy to +print; so let us put $u$ for the fraction~$\dfrac{AP}{OP}$, +which represents the magnitude of the angle~$AOP$, +and put $v$ for the fraction~$\dfrac{PM}{OM}$, and $w$~for +the fraction~$\dfrac{OM}{OP}$. Then $u$,~$v$,~$w$, are numbers, +and, since we are talking of \emph{any} angle~$AOP$, +they are variable numbers. But a +correlation exists between their magnitudes, +so that when $u$ (\ie\ the angle~$AOP$) is given +the magnitudes of $v$~and~$w$ are definitely determined. +Hence $v$~and~$w$ are functions of the +argument~$u$. We have called $v$ the \emph{sine} of~$u$, +and $w$ the \emph{cosine} of~$u$. We wish to adapt +the general functional notation $y = f(x)$ to +these special cases: so in modern mathematics +%[** TN: Function names italicized in the original] +we write \Chg{$\sin$}{``$\sin$''} for~``$f$'' when we want to +\PageSep{184} +indicate the special function of ``sine,'' and +``$\cos$'' for~``$f$'' when we want to indicate +the special function of ``cosine.'' Thus, with +the above meanings for $u$,~$v$,~$w$, we get +\[ +v = \sin u,\quad\text{and}\quad +w = \cos u, +\] +where the brackets surrounding the~$x$ in~$f(x)$ +are omitted for the special functions. The +meaning of these functions $\sin$ and $\cos$ as +correlating the pairs of numbers $u$~and~$v$, and +$u$~and~$w$ is, that the functional relations are to +be found by constructing (\cf\ \Fig[fig.]{26}) an angle~$AOP$, +whose measure ``$AP$~divided by~$OP$'' +is equal to~$u$, and that then $v$~is the number +given by ``$PM$~divided by~$OP$'' and $w$~is the +number given by ``$OM$~divided by~$OP$.'' + +It is evident that without some further definitions +we shall get into difficulties when the +number~$u$ is taken too large. For then the arc~$AP$ +may be greater than one-quarter of the +circumference of the circle, and the point~$M$ +(\cf\ figs.\ \FigNum{26} and~\FigNum{27}) may fall between $O$ and~$A'$ +and not between $O$ and~$A$. Also $P$~may be +below the line~$AOA'$ and not above it as in +\Fig[fig.]{26}. In order to get over this difficulty +we have recourse to the ideas and conventions +of coordinate geometry in making our +complete definitions of the sine and cosine. +Let one arm~$OA$ of the angle be the axis~$OX$, +and produce the axis backwards to +obtain its negative part~$OX'$. Draw the +\PageSep{185} +other axis~$YOY'$ perpendicular to it. Let +any point~$P$ at a distance~$r$ from~$O$ have +coordinates $x$ and~$y$. These coordinates are +both positive in the first ``quadrant'' of +the plan, \eg\ the coordinates $x$ and~$y$ of~$P$ +\Figure{27} +in \Fig[fig.]{27}. In the other quadrants, either +one or both of the coordinates are negative, +for example, $x'$~and~$y$ for~$P'$, and $x'$ and~$y'$ +for~$P''$, and $x$ and~$y'$ for~$P'''$ in \Fig[fig.]{27}, where +$x'$ and~$y'$ are both negative numbers. The +positive angle~$POA$ is the arc~$AP$ divided +by~$r$, its sine is~$\dfrac{y}{r}$ and its cosine is~$\dfrac{x}{r}$; the positive +\PageSep{186} +angle~$AOP'$ is the arc~$ABP'$ divided by~$r$, +its sine is~$\dfrac{y}{r}$ and cosine~$\dfrac{x'}{r}$; the positive angle~$AOP''$ +is the arc $ABA'P''$ divided by~$r$, its +sine is~$\dfrac{y'}{r}$ and its cosine is~$\dfrac{x'}{r}$; the positive +angle~$AOP'''$ is the arc $ABA'B'P'''$ divided +by~$r$, its sine is~$\dfrac{y'}{r}$ and its cosine is~$\dfrac{x}{r}$. + +But even now we have not gone far enough. +For suppose we choose~$u$ to be a number +greater than the ratio of the whole circumference +of the circle to its radius. Owing to +the similarity of all circles this ratio is the +same for all circles. It is always denoted in +mathematics by the symbol~$2\pi$, where $\pi$~is +the Greek form of the letter~\Foreign{p} and its +name in the Greek alphabet is ``pi.'' It can +be proved that $\pi$~is an incommensurable +number, and that therefore its value cannot +be expressed by any fraction, or by any +terminating or recurring decimal. Its value +to a few decimal places is~$3.14159$; for many +purposes a sufficiently accurate approximate +value is~$\dfrac{22}{7}$. Mathematicians can easily calculate~$\pi$ +to any degree of accuracy required, +just as~$\sqrt{2}$ can be so calculated. Its value +has been actually given to $707$~places of +\PageSep{187} +decimals. Such elaboration of calculation is +merely a curiosity, and of no practical or +theoretical interest. The accurate determination +of~$\pi$ is one of the two parts of +the famous problem of squaring the circle. +\index{Squaring the Circle}% +The other part of the problem is, by the +theoretical methods of pure geometry to +describe a straight line equal in length to the +circumference. Both parts of the problem +are now known to be impossible; and the +insoluble problem has now lost all special +practical or theoretical interest, having become +absorbed in wider ideas. + +After this digression on the value of~$\pi$, we +now return to the question of the general +definition of the magnitude of an angle, so as +to be able to produce an angle corresponding +to any value~$u$. Suppose a moving point,~$Q$, +to start from~$A$ on~$OX$ (\Chg{cf.}{\cf}\ \Fig[fig.]{27}), and to rotate +in the positive direction (anti-clockwise, in +the figure considered) round the circumference +of the circle for any number of times, finally +resting at any point, \eg~at $P$ or~$P'$ or~$P''$ or~$P'''$. +Then the total length of the curvilinear +circular path traversed, divided by the radius +of the circle,~$r$, is the generalized definition of +a positive angle of \emph{any} size. Let $x$,~$y$ be the +coordinates of the point in which the point~$Q$ +rests, \ie~in one of the four alternative positions +mentioned in \Fig[fig.]{27}; $x$~and~$y$ (as here used) will +either \Typo{}{be} $x$~and~$y$, or $x'$~and~$y$, or $x'$~and~$y'$, or $x$~and~$y'$. +\PageSep{188} +Then the sign of this generalized +angle is~$\dfrac{y}{r}$ and its cosine is~$\dfrac{x}{r}$. With these +definitions the functional relations $v = \sin u$ +and $w = \cos u$, are at last defined for all positive +real values of~$u$. For negative values of~$u$ +we simply take rotation of~$Q$ in the opposite +(clockwise) direction; but it is not worth our +while to elaborate further on this point, now +that the general method of procedure has +been explained. + +These functions of sine and cosine, as thus +defined, enable us to deal with the problems +concerning the triangle from which Trigonometry +took its rise. But we are now in a +position to relate Trigonometry to the wider +idea of Periodicity of which the importance +\index{Periodicity}% +was explained in the last chapter. It is easy +to see that the functions $\sin u$ and $\cos u$ are +periodic functions of~$u$. For consider the +position,~$P$ (in \Fig[fig.]{27}), of a moving point,~$Q$, +which has started from~$A$ and revolved round +the circle. This position,~$P$, marks the angles +$\dfrac{\text{arc } AP}{r}$, and $2\pi + \dfrac{\text{arc } AP}{r}$, and $4\pi + \dfrac{\text{arc } AP}{r}$, +and $6\pi + \dfrac{\text{arc } AP}{r}$, and so on indefinitely. Now, +all these angles have the same sine and cosine, +namely, $\dfrac{y}{r}$~and~$\dfrac{x}{r}$. Hence it is easy to see that, +\PageSep{189} +\index{Period|EtSeq}% +if $u$ be chosen to have any value, the arguments +$u$~and~$2\pi + u$, and $4\pi + u$, and $6\pi + u$, +and $8\pi + u$ and so on indefinitely, have all the +same values for the corresponding sines and +cosines. In other words, +\begin{alignat*}{4} +\sin u &= \sin(2\pi + u) &&= \sin(4\pi + u) &&= \sin(6\pi + u) &&= \text{etc.}; \\ +\cos u &= \cos(2\pi + u) &&= \cos(4\pi + u) &&= \cos(6\pi + u) &&= \text{etc.} +\end{alignat*} +This fact is expressed by saying that $\sin u$ and +$\cos u$ are periodic functions with their period +equal to~$2\pi$. + +The graph of the function $y = \sin x$ (notice +that we now abandon $v$~and~$u$ for the more +familiar $y$~and~$x$) is shown in \Fig[fig.]{28}. We take +on the axis of~$x$ any arbitrary length at pleasure +to represent the number~$\pi$, and on the axis +of~$y$ any arbitrary length at pleasure to represent +the number~$1$. The numerical values of +the sine and cosine can never exceed unity. +The recurrence of the figure after periods of~$2\pi$ +will be noticed. This graph represents the +simplest style of periodic function, out of +which all others are constructed. The cosine +gives nothing fundamentally different from the +sine. For it is easy to prove that $\cos x = \sin(x + \dfrac{\pi}{2})$; +hence it can be seen that the +graph of $\cos x$ is simply \Fig[fig.]{28} modified by +\PageSep{190} +drawing the axis of~$OY$ through the point +on~$OX$ marked~$\dfrac{\pi}{2}$, instead of drawing it in +its actual position on the figure. + +It is easy to construct a `sine' function in +\Figure{28} +which the period has any assigned value~$a$. +For we have only to write +\[ +y = \sin \frac{2\pi x}{a}, +\] +and then +\[ +\sin \frac{2\pi (x + a)}{a} +%[** TN: Changed curly braces to parentheses] + = \sin \left(\frac{2\pi x}{a} + 2\pi\right) + = \sin \frac{2\pi x}{a}. +\] +Thus the period of this new function is now~$a$. +Let us now give a general definition of what +\PageSep{191} +we mean by a periodic function. The function~$f(x)$ +is periodic, with the period~$a$, if (i)~for \emph{any} +value of~$x$ we have $f(x) = f(x + a)$, and (ii)~there +is no number~$b$ smaller than~$a$ such that for +\emph{any} value of~$x$, $f(x) = f(x + b)$. + +The second clause is put into the definition +because when we have $\sin \dfrac{2\pi x}{a}$, it is not only +periodic in the period~$a$, but also in the periods +$2a$ and~$3a$, and so on; this arises since +\[ +\sin \frac{2\pi (x + 3a)}{a} + = \sin \left(\frac{2\pi x}{a} + 6\pi\right) + = \sin \frac{2\pi x}{a}. +\] +So it is the smallest period which we want to +get hold of and call \emph{the} period of the function. +The greater part of the abstract theory of +periodic functions and the whole of the applications +of the theory to Physical Science are +dominated by an important theorem called +Fourier's Theorem; namely that, if $f(x)$ be a +\index{Fourier's Theorem}% +periodic function with the period~$a$ and if $f(x)$ +also satisfies certain conditions, which practically +are always presupposed in functions suggested +by natural phenomena, then $f(x)$ can +be written as the sum of a set of terms in the +form\Pagelabel{191} +\begin{multline*} +c_{0} + c_{1} \sin \left(\frac{2\pi x}{a} + e_{1}\right) + + c_{2} \sin \left(\frac{4\pi x}{a} + e_{2}\right) \\ + + c_{3} \sin \left(\frac{6\pi x}{a} + e_{3}\right) + \text{etc.} +\end{multline*} +\PageSep{192} +In this formula $c_{0}$,~$c_{1}$, $c_{2}$, $c_{3}$,~etc., and also +$e_{1}$,~$e_{2}$, $e_{3}$,~etc., are constants, chosen so as to +suit the particular function. Again we have +to ask, How many terms have to be chosen? +And here a new difficulty arises: for we can +prove that, though in some particular cases a +definite number will do, yet in general all we +can do is to approximate as closely as we like +to the value of the function by taking more +and more terms. This process of gradual +approximation brings us to the consideration +of the theory of infinite series, an essential +part of mathematical theory which we will +consider in the next chapter. + +The above method of expressing a periodic +\index{Harmonic Analysis}% +function as a sum of sines is called the ``harmonic +analysis'' of the function. For example, +at any point on the sea coast the tides +rise and fall periodically. Thus at a point +near the Straits of Dover there will be two +daily tides due to the rotation of the earth. +The daily rise and fall of the tides are complicated +by the fact that there are two tidal +waves, one coming up the English Channel, +and the other which has swept round the +North of Scotland, and has then come southward +down the North Sea. Again some high +tides are higher than others: this is due to +the fact that the Sun has also a tide-generating +influence as well as the Moon. In this way +monthly and other periods are introduced. +\PageSep{193} +We leave out of account the exceptional influence +of winds which cannot be foreseen. +The general problem of the harmonic analysis +of the tides is to find sets of terms like those +in the expression on \Pageref[page]{191} above, such that +each set will give with approximate accuracy +the contribution of the tide-generating influences +of one ``period'' to the height of the +tide at any instant. The argument~$x$ will +therefore be the \emph{time} reckoned from any convenient +commencement. + +Again, the motion of vibration of a violin +string is submitted to a similar harmonic +analysis, and so are the vibrations of the +ether and the air, corresponding respectively +to waves of light and waves of sound. We +are here in the presence of one of the fundamental +processes of mathematical physics---namely, +nothing less than its general method +of dealing with the great natural fact of +Periodicity. +\PageSep{194} + + +\Chapter{XIV}{Series} + +\First{No} part of Mathematics suffers more from +\index{Order|EtSeq}% +\index{Series|EtSeq}% +the triviality of its initial presentation to +beginners than the great subject of series. +Two minor examples of series, namely arithmetic +and geometric series, are considered; +these examples are important because they +are the simplest examples of an important +general theory. But the general ideas are +never disclosed; and thus the examples, which +exemplify nothing, are reduced to silly trivialities. + +The general mathematical idea of a series +is that of a set of things ranged in order, that +is, in sequence; This meaning is accurately +represented in the common use of the term. +Consider for example, the series of English +Prime Ministers during the nineteenth century, +arranged in the order of their first tenure of +that office within the century. The series +commences with William Pitt, and ends with +\index{Pitt, William}% +\index{Rosebery, Lord}% +Lord Rosebery, who, appropriately enough, +is the biographer of the first member. We +\PageSep{195} +might have considered other serial orders for +the arrangement of these men; for example, +according to their height or their weight. +These other suggested orders strike us as +trivial in connection with Prime Ministers, +and would not naturally occur to the mind; +but abstractly they are just as good orders +as any other. When one order among terms +is very much more important or more obvious +than other orders, it is often spoken of as \emph{the} +order of those terms. Thus \emph{the} order of the +integers would always be taken to mean their +order as arranged in order of magnitude. But +of course there is an indefinite number of +other ways of arranging them. When the +number of things considered is finite, the +number of ways of arranging them in order is +called the number of their permutations. The +number of permutations of a set of $n$~things, +where $n$~is some finite integer, is +\[ +n × (n - 1) × (n - 2) × (n - 3) × \dots × 4 × 3 × 2 × 1\Add{,} +\] +that is to say, it is the product of the first $n$ +integers; this product is so important in +mathematics that a special symbolism, is used +for it, and it is always written~`$n!$\Add{.}' Thus, +$2! = 2 × 1 = 2$, and $3! = 3 × 2 × 1 = 6$, and $4! = 4 × 3 × 2 × 1 = 24$, +and $5! = 5 × 4 × 3 × 2 × 1 = 120$. +As $n$~increases, the value of~$n!$ increases very +quickly; thus $100!$~is a hundred times as +large as~$99!$\Add{.} +\PageSep{196} + +It is easy to verify in the case of small +values of~$n$ that $n!$ is the number of ways +of arranging $n$~things in order. Thus consider +two things $a$ and~$b$; these are capable +of the two orders $ab$ and~$ba$, and $2! = 2$. + +Again, take three things $a$,~$b$, and~$c$; these +are capable of the six orders, $abc$, $acb$, $bac$, +$bca$, $cab$, $cba$, and $3! = 6$. Similarly for the +twenty-four orders in which four things $a$,~$b$,~$c$, +and~$d$, can be arranged. + +When we come to the infinite sets of things---like +\index{Order, Type of}% +the sets of all the integers, or all the +fractions, or all the real numbers for instance---we +come at once upon the complications of +the theory of order-types. This subject was +touched upon in \ChapRef{VI}. in considering +the possible orders of the integers, and of the +fractions, and of the real numbers. The +whole question of order-types forms a comparatively +new branch of mathematics of +great importance. We shall not consider it +any further. All the infinite series which we +consider now are of the same order-type as +the integers arranged in ascending order of +magnitude, namely, with a first term, and +such that each term has a couple of next-door +neighbours, one on either side, with the +exception of the first term which has, of +course, only one next-door neighbour. Thus, +if $m$~be any integer (not zero), there will be +always an $m$th~term. A series with a finite +\PageSep{197} +number of terms (say $n$~terms) has the same +characteristics as far as next-door neighbours +are concerned as an infinite series; it only +differs from infinite series in having a last +term, namely, the~$n$th. + +The important thing to do with a series of +numbers---using for the future ``series'' in +the restricted sense which has just been mentioned---is +to add its successive terms together. + +Thus if $u_{1}$,~$u_{2}$, $u_{3}$,~\dots\Add{,} $u_{n}$,~\dots\ are respectively +the $1$st,~$2$nd, $3$rd, $4$th,~\dots\Add{,} $n$th,~\dots\ +terms of a series of numbers, we form successively +the series $u_{1}$, $u_{1} + u_{2}$, $u_{1} + u_{2} + u_{3}$, $u_{1} + u_{2} + u_{3} + u_{4}$, +and so on; thus the sum of the +$1$st $n$~terms may be written\Typo{.}{} +\[ +u_{1} + u_{2} + u_{3} + \dots + u_{n}. +\] + +If the series has only a finite number of +\index{Approximation|EtSeq}% +terms, we come at last in this way to the +sum of the whole series of terms. But, if +the series has an infinite number of terms, +this process of successively forming the sums +of the terms never terminates; and in this +sense there is no such thing as the sum of an +infinite series. + +But why is it important successively to add +the terms of a series in this way? The answer +is that we are here symbolizing the fundamental +mental process of approximation. +This is a process which has significance far +\PageSep{198} +beyond the regions of mathematics. Our +limited intellects cannot deal with complicated +material all at once, and our method of +arrangement is that of approximation. The +statesman in framing his speech puts the +dominating issues first and lets the details +fall naturally into their subordinate places. +There is, of course, the converse artistic +method of preparing the imagination by the +presentation of subordinate or special details, +and then gradually rising to a crisis. In +either way the process is one of gradual summation +of effects; and this is exactly what +is done by the successive summation of the +terms of a series. Our ordinary method of +stating numbers is such a process of gradual +summation, at least, in the case of large +numbers. Thus $568,213$ presents itself to +the mind as\Add{:}--- +\[ +500,000 + 60,000 + 8,000 + 200 + 10 + 3\Add{.} +\] + +In the case of decimal fractions this is so +more avowedly. Thus $3.14159$ is\Add{:}--- +\[ +3 + \tfrac{1}{10} + \tfrac{4}{100} + \tfrac{1}{1000} + \tfrac{5}{10000} + \tfrac{9}{100000}\Add{.} +\] +Also, $3$ and~$3 + \frac{1}{10}$, and $3 + \tfrac{1}{10} + \tfrac{4}{100}$, and +$3 + \tfrac{1}{10} + \tfrac{4}{100} + \tfrac{1}{1000}$, +and $3 + \tfrac{1}{10} + \tfrac{4}{100} + \tfrac{1}{1000} + \tfrac{5}{10000}$ are +successive approximations to the complete result +$3.14159$. If we read $568,213$ backwards +from right to left, starting with the $3$~units, +\PageSep{199} +we read it in the artistic way, gradually preparing +the mind for the crisis of~$500,000$. + +The ordinary process of numerical multiplication +proceeds by means of the summation +of a series, Consider the computation +\[ +\begin{array}{*{6}{@{}c@{}}} + & & &3&4&2 \\ + & & &6&5&8 \\ +\cline{4-6} +\Strut + & &2&7&3&6 \\ + &1&7&1&0& \\ +2&0&5&2& & \\ +\cline{1-6} +\Strut +2&2&5&0&3&6 +\end{array} +\] + +Hence the three lines to be added form a +series of which the first term is the upper +line. This series follows the artistic method +of presenting the most important term last, +not from any feeling for art, but because of +the convenience gained by keeping a firm +hold on the units' place, thus enabling us to +omit some~$0$'s, formally necessary. + +But when we approximate by gradually +\index{Limit of a Series|EtSeq}% +adding the successive terms of an infinite +series, what are we approximating to? The +difficulty is that the series has no ``sum'' in +the straightforward sense of the word, because +the operation of adding together its terms +can never be completed. The answer is that +we are approximating to the \emph{limit} of the +summation of the series, and we must now +\PageSep{200} +proceed to explain what the ``limit'' of a +series is. + +The summation of a series approximates to +a limit when the sum of any number of its +terms, provided the number be large enough, +is as nearly equal to the limit as you care to +approach. But this description of the meaning +of approximating to a limit evidently will +not stand the vigorous scrutiny of modern +mathematics. What is meant by \emph{large +enough}, and by \emph{nearly equal}, and by \emph{care to +approach}? All these vague phrases must be +explained in terms of the simple abstract +ideas which alone are admitted into pure +mathematics. + +Let the successive terms of the series be +$u_{1}$,~$u_{2}$, $u_{3}$, $u_{4}$,~\dots, $u_{n}$, etc., so that $u_{n}$~is the +$n$th~term of the series. Also let $s_{n}$ be the +sum of the $1$st $n$~terms, whatever $n$~may be. +So that\Add{:}--- +\begin{gather*} +s_{1} = u_{1},\quad +s_{2} = u_{1} + u_{2},\quad +s_{3} = u_{1} + u_{2} + u_{3},\quad\text{and} \\ +s_{n} = u_{1} + u_{2} + u_{3} + \dots + u_{n}. +\end{gather*} + +Then the terms $s_{1}$,~$s_{2}$, $s_{3}$,~\dots\Add{,} $s_{n}$,~\dots\ form +a new series, and the formation of this series +is the process of summation of the original +series. Then the ``approximation'' of the +\emph{summation} of the original series to a ``limit'' +means the ``approximation of the \emph{terms} of +this new series to a limit.'' And we have +\PageSep{201} +now to explain what we mean by the approximation +to a limit of the terms of a series. + +Now, remembering the definition (given in +\ChapRef[chapter]{XII}.)\ of a \emph{standard of approximation}, +\index{Standard of Approximation|EtSeq}% +\index{Sum to Infinity|EtSeq}% +the idea of a limit means this: $l$~is +the limit of the terms of the series $s_{1}$,~$s_{2}$, +$s_{3}$,~\dots\Add{,} $s_{n}$,~\dots, if, corresponding to each +real number~$k$, taken as a standard of +approximation, a term~$s_{n}$ of the series can +be found so that all succeeding terms (\ie\ +$s_{n+1}$, $s_{n+2}$, etc.)\ approximate to~$l$ within +that standard of approximation. If another +smaller standard~$k^{1}$ be chosen, the term~$s_{n}$ +may be too early in the series, and a +later term~$s_{m}$ with the above property will +then be found. + +If this property holds, it is evident that as +you go along to series $s_{1}$,~$s_{2}$, $s_{3}$,~\dots, $s_{n}$,~\dots\ +from left to right, after a time you come to +terms \emph{all} of which are nearer to~$l$ than any +number which you may like to assign. In +other words you approximate to~$l$ as closely +as you like. The close connection of this +definition of the limit of a series with the +definition of a continuous function given in +\ChapRef[chapter]{XI}.\ will be immediately perceived. + +Then coming back to the original series $u_{1}$,~$u_{2}$, +$u_{3}$,~\dots, $u_{n}$,~\dots, the limit of the terms of +the series $s_{1}$,~$s_{2}$, $s_{3}$,~\dots, $s_{n}$,~\dots, is called +the ``sum to infinity'' of the original series. +But it is evident that this use of the word +\PageSep{202} +``sum'' is very artificial, and we must not +assume the analogous properties to those of +the ordinary sum of a finite number of terms +without some special investigation. + +Let us look at an example of a ``sum to +infinity.'' Consider the recurring decimal +$.1111\dots$. This decimal is merely a way of +symbolizing the ``sum to infinity'' of the series +$.1$, $.01$, $.001$, $.0001$, etc. The corresponding +series found by summation is $s_{1} = .1$, +$s_{2} = .11$, $s_{3} = .111$, $s_{4} = .1111$, etc. The limit +of the terms of this series is~$\frac{1}{9}$; this is easy to +see by simple division, for +\[ +\tfrac{1}{9} + = .1 + \tfrac{1}{90} + = .11 + \tfrac{1}{900} + = .111 + \tfrac{1}{9000} = \text{etc.} +\] +Hence, if $\frac{3}{17}$ is given (the $k$ of the definition), +$.1$~and \emph{all} succeeding terms differ from~$\frac{1}{9}$ by +less than~$\frac{3}{17}$; if $\frac{1}{1000}$ is given (another choice +for the $k$ of the definition), $.111$ and all +succeeding terms differ from~$\frac{1}{9}$ by less than~$\frac{1}{1000}$; +and so on, whatever choice for~$k$ be +made. + +It is evident that nothing that has been +said gives the slightest idea as to how the +``sum to infinity'' of a series is to be +found. We have merely stated the conditions +which such a number is to satisfy. Indeed, +a general method for finding in all +cases the sum to infinity of a series is intrinsically +out of the question, for the simple reason +that such a ``sum,'' as here defined, does not +always exist. Series which possess a sum to +\PageSep{203} +\index{Convergent|EtSeq}% +\index{Divergent|EtSeq}% +infinity are called \emph{convergent}, and those which +do not possess a sum to infinity are called +\emph{divergent}. + +An obvious example of a divergent series +is $1$,~$2$, $3$,~\dots, $n$~\dots\Add{,} \ie~the series of integers +in their order of magnitude. For +whatever number~$l$ you try to take as its +sum to infinity, and whatever standard of +approximation~$k$ you choose, by taking +enough terms of the series you can always +make their sum differ from~$l$ by more than~$k$. +Again, another example of a divergent +series is $1$,~$1$, $1$,~etc., \ie~the series of +which each term is equal to~$1$. Then the +sum of $n$~terms is~$n$, and this sum grows +without limit as $n$~increases. Again, another +example of a divergent series is $1$,~$-1$, $1$,~$-1$, +$1$,~$-1$, etc., \ie~the series in which the terms +are alternately $1$ and~$-1$. The sum of an +odd number of terms is~$1$, and of an even +number of terms is~$0$. Hence the terms of +the series $s_{1}$,~$s_{2}$, $s_{3}$,~\dots\Add{,} $s_{n}$,~\dots\ do not approximate +to a limit, although they do not +increase without limit. + +It is tempting to suppose that the condition +for $u_{1}$,~$u_{2}$,~\dots\Add{,} $u_{n}$,~\dots\ to have a sum +to infinity is that $u_{n}$~should decrease indefinitely +as $n$~increases. Mathematics would +be a much easier science than it is, if this +were the case. Unfortunately the supposition +is not true. +\PageSep{204} + +For example the series +\[ +1,\quad +\frac{1}{2},\quad +\frac{1}{3},\quad +\frac{1}{4},\ \dots,\quad +\frac{1}{n},\ \dots +\] +is divergent. It is easy to see that this is +the case; for consider the sum of $n$~terms +%[** TN: "(n + 1)^{th} term" in the original +beginning at the $(n + 1)$th term. These $n$~terms +are $\dfrac{1}{n + 1}$, $\dfrac{1}{n + 2}$, $\dfrac{1}{n + 3}$,~\dots\Add{,} $\dfrac{1}{2n}$: there +are $n$~of them and $\dfrac{1}{2n}$~is the least among them. +Hence their sum is greater than $n$~times~$\dfrac{1}{2n}$, +\ie~is greater than~$\dfrac{1}{2}$. Now, without +altering the sum to infinity, if it exist, we +can add together neighbouring terms, and +obtain the series +\[ +1,\quad +\tfrac{1}{2},\quad +\tfrac{1}{3} + \tfrac{1}{4},\quad +\tfrac{1}{5} + \tfrac{1}{6} + \tfrac{1}{7} + \tfrac{1}{8},\quad +\text{etc.}, +\] +that is, by what has been said above, a series +whose terms after the~$2$nd are greater than +those of the series, +\[ +1,\quad +\tfrac{1}{2},\quad +\tfrac{1}{2},\quad +\tfrac{1}{2},\quad +\text{etc.}, +\] +where all the terms after the first are equal. +But this series is divergent. Hence the +original series is divergent.\footnote + {\Chg{Cf.}{\Cf}\ Note~C, \Pageref{noteC}.\Pagelabel{204}} + +This question of divergency shows how +careful we must be in arguing from the properties +\PageSep{205} +of the sum of a finite number of terms +to that of the sum of an infinite series. For +the most elementary property of a finite +number of terms is that of course they +possess a sum: but even this fundamental +property is not necessarily possessed by an +infinite series. This caution merely states +that we must not be misled by the suggestion +of the technical term ``\emph{sum} of an infinite +series.'' It is usual to indicate the sum of +the infinite series +\[ +u_{1},\quad +u_{2},\quad +u_{3},\ \dots\Add{,}\quad +u_{n}\Add{,}\ \dots +\] +by +\[ +u_{1} + u_{2} + u_{3} + \dots + u_{n} + \dots\Add{.} +\] + +We now pass on to a generalization of the +idea of a series, which mathematics, true to +its method, makes by use of the variable. +Hitherto, we have only contemplated series +in which each definite term was a definite +number. But equally well we can generalize, +and make each term to be some mathematical +expression containing a variable~$x$. Thus +we may consider the series $1$,~$x$, $x^{2}$, $x^{3}$,~\dots, +$x^{n}$,~\dots, and the series +\[ +x,\quad +\frac{x^{2}}{2},\quad +\frac{x^{3}}{3},\ \dots,\quad +\frac{x^{n}}{n},\ \dots\Add{.} +\] + +In order to symbolize the general idea of +any such function, conceive of a function of~$x$, +$f_{n}(x)$~say, which involves in its formation +a variable integer~$n$, then, by giving~$n$ the +\PageSep{206} +values $1$,~$2$, $3$,~etc., in succession, we get the +series +\[ +f_{1}(x),\quad +f_{2}(x),\quad +f_{3}(x),\ \dots,\quad +f_{n}(x),\dots\Add{.} +\] +Such a series may be convergent for some +values of~$x$ and divergent for others. It is, +in fact, rather rare to find a series involving a +variable~$x$ which is convergent for all values +of~$x$,---at least in any particular instance it is +very unsafe to assume that this is the case. +For example, let us examine the simplest of +all instances, namely, the ``geometrical'' +\index{Geometrical Series|EtSeq}% +series +\[ +1,\quad x,\quad x^{2},\quad x^{3},\ \dots,\quad x^{n},\ \dots\Add{.} +\] +The sum of $n$~terms is given by +\[ +s_{n} = 1 + x + x^{2} + x^{3} + \dots + x^{n}. +\] + +Now multiply both sides by~$x$ and we get +\[ +xs_{n} = x + x^{2} + x^{3} + x^{4} + \dots + x^{n} + x^{n+1}\Add{.} +\] +Now subtract the last line from the upper +line and we get +\[ +s_{n}(1 - x) = s_{n} - xs_{n} = 1 - x^{n+1}, +\] +and hence (if $x$~be not equal to~$1$) +\[ +s_{n} = \frac{1 - x^{n+1}}{1 - x} + = \frac{1}{1 - x} - \frac{x^{n+1}}{1 - x}\Add{.} +\] +Now if $x$~be numerically less than~$1$, for sufficiently +large values of~$n$, $\dfrac{x^{n+1}}{1 - x}$~is always numerically +\PageSep{207} +less than~$k$, however $k$~be chosen. Thus, +if $x$~be numerically less than~$1$, the series $1$,~$x$, +$x^{2}$,~\dots\Add{,} $x^{n}$,~\dots\ is convergent, and $\dfrac{1}{1 - x}$~is its +limit. This statement is symbolized by +\[ +\frac{1}{1 - x} = 1 + x + x^{2} + \dots + x^{n} + \dots,\quad +(-1 < x < 1). +\] +But if $x$~is numerically greater than~$1$, or +numerically equal to~$1$, the series is divergent. +In other words, if $x$~lie between $-1$ and~$+1$, +the series is convergent; but if $x$~be equal +to~$-1$ or~$+1$, or if $x$~lie outside the interval +$-1$~to~$+1$, then the series is divergent. Thus +the series is convergent at all ``points'' +within the interval $-1$~to~$+1$, exclusive of +the end points. + +At this stage of our enquiry another question +arises. Suppose that the series +\[ +f_{1}(x) + f_{2}(x) + f_{3}(x) + \dots + f_{n}(x) + \dots +\] +is convergent for all values of~$x$ lying within +the interval $a$~to~$b$, \ie~the series is convergent +for any value of~$x$ which is greater than~$a$ and +less than~$b$. Also, suppose we want to be +sure that in approximating to the limit we +add together enough terms to come within +some standard of approximation~$k$. Can we +always state some number of terms, say~$n$, +such that, if we take $n$~or more terms to +form the sum, then \emph{whatever} value $x$~has +\PageSep{208} +within the interval we have satisfied the +desired standard of approximation? + +Sometimes we can and sometimes we cannot +\index{Non-Uniform Convergence|EtSeq}% +\index{Uniform Convergence|EtSeq}% +do this for each value of~$k$. When we +can, the series is called uniformly convergent +throughout the interval, and when we cannot +do so, the series is called non-uniformly convergent +throughout the interval. It makes +a great difference to the properties of a series +whether it is or is not uniformly convergent +through an interval. Let us illustrate the +matter by the simplest example and the +simplest numbers. + +Consider the geometric series +\[ +1 + x + x^{2} + x^{3} + \dots + x^{n} + \dots\Add{.} +\] + +It is convergent throughout the interval +$-1$~to~$+1$, excluding the end values $x = ±1$. + +But it is not uniformly convergent throughout +this interval. For if $s_{n}(x)$~be the sum of +$n$~terms, we have proved that the difference +between $s_{n}(x)$ and the limit~$\dfrac{1}{1 - x}$ is~$\dfrac{x^{n+1}}{1 - x}$. +Now suppose $n$~be any given number of terms, +say~$20$, and let $k$~be any assigned standard +of approximation, say~$.001$. Then, by taking +$x$~near enough to~$+1$ or near enough to~$-1$, +we can make the numerical value of~$\dfrac{x^{21}}{1 - x}$ to +be greater than~$.001$. Thus $20$~terms will +\PageSep{209} +not do over the whole interval, though it is +more than enough over some parts of it. + +The same reasoning can be applied whatever +other number we take instead of~$20$, +and whatever standard of approximation instead +of~$.001$. Hence the geometric series +$1 + x + x^{2} + x^{3} + \dots + x^{n} + \dots$ is non-uniformly +convergent over its \emph{whole} interval of +convergence $-1$~to~$+1$. But if we take any +smaller interval lying at both ends within the +interval $-1$~to~$+1$, the geometric series is +uniformly convergent within it. For example, +take the interval $0$~to~$+\frac{1}{10}$. Then any +value for~$n$ which makes $\dfrac{x^{n+1}}{1 - x}$~numerically +less than~$k$ \emph{at} these limits for~$x$ also serves +for all values of~$x$ between these limits, since +it so happens that $\dfrac{x^{n+1}}{1 - x}$ diminishes in numerical +value as $x$~diminishes in numerical value. +For example, take $k = .001$; then, putting +$x = \frac{1}{10}$, we find:\Add{---} +\begin{alignat*}{3} +&\text{for $n = 1$,}\quad & \frac{x^{n+1}}{1 - x} + &= \frac{(\frac{1}{10})^{2}}{1 - \frac{1}{10}} + &&= \tfrac{1}{90} = .0111\dots, \\ +% +&\text{for $n = 2$,}\quad & \frac{x^{n+1}}{1 - x} + &= \frac{(\frac{1}{10})^{3}}{1 - \frac{1}{10}} + &&= \tfrac{1}{900} = .00111\dots, \\ +% +&\text{for $n = 3$,}\quad & \frac{x^{n+1}}{1 - x} + &= \frac{(\frac{1}{10})^{4}}{1 - \frac{1}{10}} + &&= \tfrac{1}{9000} = .000111\dots\Typo{,}{.} +\end{alignat*} + +Thus three terms will do for the whole interval, +\PageSep{210} +though, of course, for some parts of +the interval it is more than is necessary. +Notice that, because $1 + x + x^{2} + \dots + x^{n} + \dots$ +is convergent (though not uniformly) +throughout the interval $-1$~to~$+1$, +for each value of~$x$ in the interval some number +of terms~$n$ can be found which will satisfy +a desired standard of approximation; but, +as we take $x$ nearer and nearer to either end +value $+1$ or~$-1$, larger and larger values of~$n$ +have to be employed. + +It is curious that this important distinction +between uniform and non-uniform convergence +was not published till 1847 by Stokes---afterwards, +\index{Stokes, Sir George}% +Sir~George Stokes---and later, independently +in~1850 by Seidel, a German +\index{Seidel}% +mathematician. + +The critical points, where non-uniform convergence +comes in, are not necessarily at the +limits of the interval throughout which convergence +holds. This is a speciality belonging +to the geometric series. + +In the case of the geometric series $1 + x + x^{2} + \dots + x^{n} + \dots$, +a simple algebraic +expression~$\dfrac{1}{1 - x}$ can be given for its limit in +its interval of convergence. But this is not +always the case. Often we can prove a series +to be convergent within a certain interval, +though we know nothing more about its +limit except that it is the limit of the series. +\PageSep{211} +But this is a very good way of defining a +function; \viz.\ as the limit of an infinite convergent +series, and is, in fact, the way in which +most functions are, or ought to be, defined. + +Thus, the most important series in elementary +\index{Exponential Series|EtSeq}% +analysis is +\[ +1 + x + \frac{x^{2}}{2!} + \frac{x^{3}}{3!} + \dots + \frac{x^{n}}{n!} + \dots, +\] +where $n!$ has the meaning defined earlier in +this chapter. This series can be proved to +be absolutely convergent for \emph{all} values of~$x$, +and to be uniformly convergent within any +interval which we like to take. Hence it has +all the comfortable mathematical properties +which a series should have. It is called the +exponential series. Denote its sum to infinity +by~$\exp x$. Thus, by definition, +\[ +\exp x = 1 + x + \frac{x^{2}}{2!} + \frac{x^{3}}{3!} + \dots + + \frac{x^{n}}{n!} + \dots\Add{.} +\] +$\exp x$ is called the exponential function. + +It is fairly easy to prove, with a little +knowledge of elementary mathematics, that +\[ +(\exp x) × (\exp y) = \exp(x + y). +\Tag{(A)} +\] +In other words that +\begin{multline*} +(\exp x) × (\exp y) \\ + = 1 + (x + y) + \frac{(x + y)^{2}}{2!} + \frac{(x + y)^{3}}{3!} + \dots + + \frac{(x + y)^{n}}{n!} + \dots\Add{.} +\end{multline*} +\PageSep{212} + +This property~\Eq{(A)} is an example of what +is called an addition-theorem. When any +\index{Addition-Theorem}% +function [say~$f(x)$] has been defined, the first +thing we do is to try to express $f(x + y)$ in terms +of known functions of $x$~only, and known functions +of $y$~only. If we can do so, the result +is called an addition-theorem. Addition-theorems +play a great part in mathematical +analysis. Thus the addition-theorem for the +sine is given by +\[ +\sin(x + y) = \sin x \cos y + \cos x \sin y, +\] +and for the cosine by +\[ +\cos(x + y) = \cos x \cos y - \sin x \sin y. +\] + +As a matter of fact the best ways of defining +$\sin x$ and $\cos x$ are not by the elaborate +geometrical methods of the previous chapter, +but as the limits respectively of the series +\[ +x - \frac{x^{3}}{3!} + \frac{x^{5}}{5!} - \frac{x^{7}}{7!} + \text{etc.} \dots, +\] +and +\[ +1 - \frac{x^{2}}{2!} + \frac{x^{4}}{4!} - \frac{x^{6}}{6!} + \text{etc.} \dots, +\] +so that we put +\begin{align*} +\sin x &= x - \frac{x^{3}}{3!} + \frac{x^{5}}{5!} - \frac{x^{7}}{7!} + \text{etc.} \dots, \\ +\cos x &= 1 - \frac{x^{2}}{2!} + \frac{x^{4}}{4!} - \frac{x^{6}}{6!} + \text{etc.} \dots\Typo{,}{.} +\end{align*} +\PageSep{213} + +These definitions are equivalent to the geometrical +definitions, and both series can be +proved to be convergent for all values of~$x$, +and uniformly convergent throughout any +interval. These series for sine and cosine +have a general likeness to the exponential +series given above. They are, indeed, intimately +connected with it by means of the +theory of imaginary numbers explained in +Chapters \ChapNum{VII}.\ and~\ChapNum{VIII}. +\Figure{29} + +The graph of the exponential function is +given in \Fig[fig.]{29}. It cuts the axis~$OY$ at the +point $y = 1$, as evidently it ought to do, since +when $x = 0$ every term of the series except +the first is zero. The importance of the exponential +function is that it represents any +changing physical quantity whose rate of +increase at any instant is a uniform percentage +of its value at that instant. For +\PageSep{214} +example, the above graph represents the size +at any time of a population with a uniform +birth-rate, a uniform death-rate, and no emigration, +where the $x$ corresponds to the time +reckoned from any convenient day, and the +$y$ represents the population to the proper +scale. The scale must be such that $OA$~represents +the population at the date which is +taken as the origin. But we have here come +upon the idea of ``rates of increase'' which +is the topic for the next chapter. + +An important function nearly allied to the +\index{Normal Error, Curve of}% +exponential function is found by putting~$-x^{2}$ +for~$x$ as the argument in the exponential function. +%[** TN: Omitted period following "exp"] +We thus get $\exp (-x^{2})$. The graph +$y = \exp(-x^{2})$ is given in \Fig[fig.]{30}. +\Figure{30} + +The curve, which is something like a cocked +hat, is called the curve of normal error. Its +\PageSep{215} +corresponding function is vitally important +to the theory of statistics, and tells us in +many cases the sort of deviations from the +average results which we are to expect. + +Another important function is found by +combining the exponential function with the +sine, in this way:\Add{---} +\[ +y = \exp(-cx) × \sin \frac{2\pi x}{p}\Add{.} +\] +\Figure{31} + +Its graph is given in \Fig[fig.]{31}. The points +$A$,~$B$, $O$, $C$, $D$, $E$,~$F$, are placed at equal intervals~$\frac{1}{2}p$, +and an unending series of them +should be drawn forwards and backwards. +This function represents the dying away of +vibrations under the influence of friction or of +``damping'' forces. Apart from the friction, +the vibrations would be periodic, with a +period~$p$; but the influence of the friction +\PageSep{216} +makes the extent of each vibration smaller +than that of the preceding by a constant percentage +of that extent. This combination +of the idea of ``periodicity'' (which requires +\index{Periodicity}% +the sine or cosine for its symbolism) and of +``constant percentage'' (which requires the +exponential function for its symbolism) is the +reason for the form of this function, namely, +its form as a product of a sine-function into +an exponential function. +\PageSep{217} + + +\Chapter{XV}{The Differential Calculus} + +\First{The} invention of the differential calculus +\index{Differential Calculus|EtSeq}% +marks a crisis in the history of mathematics. +The progress of science is divided between +periods characterized by a slow accumulation +of ideas and periods, when, owing to the new +material for thought thus patiently collected, +some genius by the invention of a new method +or a new point of view, suddenly transforms +the whole subject on to a higher level. These +contrasted periods in the progress of the +history of thought are compared by Shelley +to the formation of an avalanche. +\begin{verse} +\footnotesize +\index{Shelley (quotation from)}% +The sun-awakened avalanche! whose mass, \\ +Thrice sifted by the storm, had gathered there \\ +Flake after flake,---in heaven-defying minds \\ +As thought by thought is piled, till some great truth \\ +Is loosened, and the nations echo round, \\ +\dotfill +\end{verse} + +The comparison will bear some pressing. +The final burst of sunshine which awakens +the avalanche is not necessarily beyond comparison +in magnitude with the other powers +of nature which have presided over its slow +\PageSep{218} +formation. The same is true in science. The +genius who has the good fortune to produce +the final idea which transforms a whole +region of thought, does not necessarily excel +all his predecessors who have worked at the +preliminary formation of ideas. In considering +the history of science, it is both silly and +ungrateful to confine our admiration with a +gaping wonder to those men who have made +the final advances towards a new epoch\Add{.} + +In the particular instance before us, the +\index{Leibniz|EtSeq}% +\index{Newton|EtSeq}% +subject had a long history before it assumed +its final form at the hands of its +two inventors. There are some traces of its +methods even among the Greek mathematicians, +and finally, just before the actual +production of the subject, Fermat (born 1601~\AD, +\index{Fermat}% +and died 1665~\AD), a distinguished +French mathematician, had so improved on +previous ideas that the subject was all but +created by him. Fermat, also, may lay +claim to be the joint inventor of coordinate +geometry in company with his contemporary +and countryman, Descartes. It was, in fact, +\index{Descartes}% +Descartes from whom the world of science +received the new ideas, but Fermat had certainly +arrived at them independently. + +We need not, however, stint our admiration +either for Newton or for Leibniz. Newton +was a mathematician and a student of +physical science, Leibniz was a mathematician +\PageSep{219} +and a philosopher, and each of them +in his own department of thought was one of +the greatest men of genius that the world +has known. The joint invention was the +occasion of an unfortunate and not very +creditable dispute. Newton was using the +methods of Fluxions, as he called the subject, +\index{Fluxions}% +in~1666, and employed it in the composition +of his \Title{Principia}, although in the work as +printed any special algebraic notation is +avoided. But he did not print a direct statement +of his method till~1693. Leibniz published +his first statement in~1684. He was +accused by Newton's friends of having got +it from a MS. by Newton, which he had been +shown privately. Leibniz also accused Newton +of having plagiarized from him. There +is now not very much doubt but that both +should have the credit of being independent +discoverers. The subject had arrived at a +stage in which it was ripe for discovery, and +there is nothing surprising in the fact that +two such able men should have independently +hit upon it. + +These joint discoveries are quite common +in science. Discoveries are not in general +made before they have been led up to +by the previous trend of thought, and by +that time many minds are in hot pursuit +of the important idea. If we merely keep +to discoveries in which Englishmen are +\PageSep{220} +concerned, the simultaneous enunciation of +the law of natural selection by Darwin and +\index{Darwin}% +Wallace, and the simultaneous discovery of +\index{Wallace}% +Neptune by Adams and the French astronomer, +\index{Adams}% +Leverrier, at once occur to the mind. +\index{Leverrier}% +The disputes, as to whom the credit ought to +be given, are often influenced by an unworthy +spirit of nationalism. The really inspiring +reflection suggested by the history of mathematics +is the unity of thought and interest +among men of so many epochs, so many nations, +and so many races. Indians, Egyptians, +Assyrians, Greeks, Arabs, Italians, Frenchmen, +Germans, Englishmen, and Russians, have +all made essential contributions to the progress +of the science. Assuredly the jealous +exaltation of the contribution of one particular +nation is not to show the larger spirit. + +The importance of the differential calculus +\index{Rate of Increase of Functions|EtSeq}% +arises from the very nature of the subject, +which is the systematic consideration of the +rates of increase of functions. This idea is +immediately presented to us by the study of +nature; velocity is the rate of increase of the +distance travelled, and acceleration is the +rate of increase of velocity. Thus the fundamental +idea of change, which is at the basis of +our whole perception of phenomena, immediately +suggests the enquiry as to the rate of +change. The familiar terms of ``quickly'' +and ``slowly'' gain their meaning from a tacit +\PageSep{221} +reference to rates of change. Thus the differential +calculus is concerned with the very +key of the position from which mathematics +can be successfully applied to the explanation +of the course of nature. + +This idea of the rate of change was certainly +in Newton's mind, and was embodied in the +\Figure{32} +language in which he explained the subject. +It may be doubted, however, whether this +point of view, derived from natural phenomena, +was ever much in the minds of the preceding +mathematicians who prepared the subject +for its birth. They were concerned with the +more abstract problems of drawing tangents +\index{Tangents}% +to curves, of finding the lengths of curves, and +of finding the areas enclosed by curves. The +\PageSep{222} +last two problems, of the rectification of curves +and the quadrature of curves as they are +named, belong to the Integral Calculus, which +\index{Integral Calculus}% +is however involved in the same general subject +as the Differential Calculus. + +The introduction of coordinate geometry +\index{Tangents}% +makes the two points of view coalesce. For +(\Chg{cf.}{\cf}\ \Fig[fig.]{32}) let $AQP$ be any curved line and let +$PT$ be the tangent at the point~$P$ on it. Let +the axes of coordinates be $OX$ and~$OY$; and +let $y = f(x)$ be the equation to the curve, so that +$OM = x$, and $PM = y$. Now let $Q$ be any +moving point on the curve, with coordinates +$x_{1}$,~$y_{1}$; then $y_{1} = f(x_{1})$. And let $Q'$ be the point +on the tangent with the same abscissa~$x_{1}$; +suppose that the coordinates of~$Q'$ are $x_{1}$ and~$y'$. +Now suppose that $N$~moves along the +axis~$OX$ from left to right with a uniform +velocity; then it is easy to see that the ordinate~$y'$ +of the point~$Q'$ on the tangent~$TP$ also +increases uniformly as $Q'$~moves along the +tangent in a corresponding way. In fact it is +easy to see that the ratio of the rate of increase +of~$Q'N$ to the rate of increase of~$ON$ is in the +ratio of $Q'N$ to~$TN$, which is the same at all +points of the straight line. But the rate of +increase of~$QN$, which is the rate of increase +of~$f(x_{1})$, varies from point to point of the curve +so long as it is not straight. As $Q$~passes +through the point~$P$, the rate of increase of~$f(x_{1})$ +(where $x_{1}$~coincides with~$x$ for the moment) +\PageSep{223} +is the same as the rate of increase of~$y'$ on the +tangent at~$P$. Hence, if we have a general +method of determining the rate of increase +of a function~$f(x)$ of a variable~$x$, we can +determine the slope of the tangent at any +point $(x, y\Typo{,}{})$ on a curve, and thence can +draw it. Thus the problems of drawing tangents +to a curve, and of determining the +rates of increase of a function are really +identical. + +It will be noticed that, as in the cases of +Conic Sections and Trigonometry, the more +artificial of the two points of view is the one +in which the subject took its rise. The really +fundamental aspect of the science only rose +into prominence comparatively late in the +day. It is a well-founded historical generalization, +that the last thing to be discovered +in any science is what the science is really +about. Men go on groping for centuries, +guided merely by a dim instinct and a puzzled +curiosity, till at last ``some great truth is +loosened.'' + +Let us take some special cases in order to +familiarize ourselves with the sort of ideas +which we want to make precise. A train is +in motion---how shall we determine its velocity +at some instant, let us say, at noon? We can +take an interval of five minutes which includes +noon, and measure how far the train has gone +in that period. Suppose we find it to be five +\PageSep{224} +miles, we may then conclude that the train +was running at the rate of $60$~miles per~hour. +But five miles is a long distance, and we +cannot be sure that just at noon the train +was moving at this pace. At noon it may +have been running $70$~miles per~hour, and +afterwards the \Typo{break}{brake} may have been put on. +It will be safer to work with a smaller interval, +say one minute, which includes noon, and to +measure the space traversed during that +period. But for some purposes greater +accuracy may be required, and one minute +may be too long. In practice, the necessary +inaccuracy of our measurements makes it +useless to take too small a period for measurement. +But in theory the smaller the period +the better, and we are tempted to say that +for ideal accuracy an infinitely small period +is required. The older mathematicians, in +particular Leibniz, were not only tempted, +but yielded to the temptation, and did say +it. Even now it is a useful fashion of speech, +provided that we know how to interpret it +into the language of common sense. It is +curious that, in his exposition of the foundations +of the calculus, Newton, the natural +scientist, is much more philosophical than +Leibniz, the philosopher, and on the other +hand, Leibniz provided the admirable notation +which has been so essential for the progress +of the subject. +\PageSep{225} + +Now take another example within the region +of pure mathematics. Let us proceed to find +the rate of increase of the function~$x^{2}$ for +any value~$x$ of its argument. We have not +yet really defined what we mean by rate of +increase. We will try and grasp its meaning +in relation to this particular case. When $x$~increases +to $x + h$, the function~$x^{2}$ increases to +$(x + h)^{2}$; so that the total increase has been +$(x + h)^{2} - x^{2}$, due to an increase~$h$ in the argument. +Hence throughout the interval $x$~to +$(x + h)$ the average increase of the function per +unit increase of the argument is $\dfrac{(x + h)^{2} - x^{2}}{h}$. +But +\[ +(x + h)^{2} = x^{2} + 2hx + h^{2}, +\] +and therefore +\[ +\frac{(x + h)^{2} - x^{2}}{h} = \frac{2hx + h^{2}}{h} = 2x + h. +\] +Thus $2x + h$ is the average increase of the +function~$x^{2}$ per unit increase in the argument, +the average being taken over by the interval +$x$~to~$x + h$. But $2x + h$ depends on~$h$, the size +of the interval. We shall evidently get what +we want, namely the \emph{rate} of increase at the +value~$x$ of the argument, by diminishing~$h$ +more and more. Hence \emph{in the limit} when $h$~has +\PageSep{226} +\index{Infinitely Small Quantities|EtSeq}% +\emph{decreased indefinitely}, we say that $2x$~is the +rate of increase of~$x^{2}$ at the value~$x$ of the +argument. + +Here again we are apparently driven up +against the idea of infinitely small quantities +in the use of the words ``in the limit when $h$~has +decreased indefinitely.'' Leibniz held that, +mysterious as it may sound, there were actually +existing such things as infinitely small +quantities, and of course infinitely small numbers +corresponding to them. Newton's language +and ideas were more on the modern +lines; but he did not succeed in explaining +the matter with such explicitness so as to be +evidently doing more than explain Leibniz's +ideas in rather indirect language. The real +explanation of the subject was first given by +Weierstrass and the Berlin School of mathematicians +\index{Weierstrass}% +about the middle of the nineteenth +century. But between Leibniz and Weierstrass +a copious literature, both mathematical +and philosophical, had grown up round these +mysterious infinitely small quantities which +mathematics had discovered and philosophy +proceeded to explain. Some philosophers, +\index{Berkeley, Bishop}% +Bishop Berkeley, for instance, correctly denied +the validity of the whole idea, though for +reasons other than those indicated here. But +the curious fact remained that, despite all +criticisms of the foundations of the subject, +there could be no doubt but that the mathematical +\PageSep{227} +procedure was substantially right. In +fact, the subject was right, though the explanations +were wrong. It is this possibility of +being right, albeit with entirely wrong explanations +as to what is being done, that so +often makes external criticism---that is so far +as it is meant to stop the pursuit of a method---singularly +barren and futile in the progress of +science. The instinct of trained observers, +and their sense of curiosity, due to the fact +that they are obviously getting at something, +are far safer guides. Anyhow the general +effect of the success of the Differential Calculus +was to generate a large amount of bad philosophy, +centring round the idea of the infinitely +small. The relics of this verbiage +may still be found in the explanations of +many elementary mathematical text-books on +the Differential Calculus. It is a safe rule to +apply that, when a mathematical or philosophical +author writes with a misty profundity, +he is talking nonsense. +\medskip + +Newton would have phrased the question +\index{Limit of a Function|EtSeq}% +by saying that, as $h$~approaches zero, in the +limit $2x + h$ becomes~$2x$. It is our task so to +explain this statement as to show that it does +not in reality covertly assume the existence +of Leibniz's infinitely small quantities. In +reading over the Newtonian method of statement, +it is tempting to seek simplicity by +\PageSep{228} +saying that $2x + h$ is~$2x$, when $h$~is zero. But +this will not do; for it thereby abolishes the +interval from $x$ to~$x + h$, over which the average +increase was calculated. The problem is, how +to keep an interval of length~$h$ over which to +calculate the average increase, and at the same +time to treat~$h$ as if it were zero. Newton did +this by the conception of a limit, and we now +\index{Weierstrass}% +proceed to give Weierstrass's explanation of +its real meaning. + +In the first place notice that, in discussing +$2x + h$, we have been considering~$x$ as fixed in +value and $h$~as varying. In other words $x$~has +been treated as a ``constant'' variable, +or parameter, as explained in \ChapRef{IX}.; +and we have really been considering $2x + h$ as +a function of the argument~$h$. Hence we can +generalize the question on hand, and ask +what we mean by saying that the function~$f(h)$ +tends to the limit~$l$, say, as its argument~$h$ +tends to the value zero. But again we shall +see that the special value \emph{zero} for the argument +does not belong to the essence of the subject; +and again we generalize still further, and ask, +what we mean by saying that the function~$f(h)$ +tends to the limit~$l$ as $h$~tends to the value~$a$. + +Now, according to the Weierstrassian explanation +the whole idea of $h$~tending to the +value~$a$, though it gives a sort of metaphorical +picture of what we are driving at, is really off +the point entirely. Indeed it is fairly obvious +\PageSep{229} +that, as long as we retain anything like ``$h$~tending +to~$a$,'' as a fundamental idea, we are +really in the clutches of the infinitely small; +for we imply the notion of $h$~being infinitely +near to~$a$. This is just what we want to get +rid of. + +Accordingly, we shall yet again restate our +phrase to be explained, and ask what we +mean by saying that the limit of the function~$f(h)$ +at~$a$ is~$l$. + +The limit of~$f(h)$ at~$a$ is a property of the +\index{Standard of Approximation|EtSeq}% +neighbourhood of~$a$, where ``neighbourhood'' +is used in the sense defined in \ChapRef{XI}.\ +during the discussion of the continuity of +functions. The value of the function~$f(h)$ at~$a$ +is~$f(a)$; but the limit is distinct in idea +from the value, and may be different from +it, and may exist when the value has not +been defined. We shall also use the term +``standard of approximation'' in the sense +in which it is defined in \ChapRef{XI}. In +fact, in the definition of ``continuity'' given +towards the end of that chapter we have +practically defined a limit. The definition of +a limit is:--- + +A function~$f(x)$ has the limit~$l$ at a value~$a$ +of its argument~$x$, when in the neighbourhood +of~$a$ its values approximate to~$l$ within +\emph{every} standard of approximation. + +Compare this definition with that already +given for continuity, namely:--- +\PageSep{230} + +A function~$f(x)$ is continuous at a value~$a$ +of its argument, when in the neighbourhood +of~$a$ its values approximate to its value at~$a$ +within \emph{every} standard of approximation. + +It is at once evident that a function is continuous +at~$a$ when (i)~it possesses a limit at~$a$, +and (ii)~that limit is equal to its value at~$a$. +Thus the illustrations of continuity which +have been given at the end of \ChapRef{XI}.\ are +illustrations of the idea of a limit, namely, +they were all directed to proving that $f(a)$~was +the limit of~$f(x)$ at~$a$ for the functions +considered and the value of~$a$ considered. It +is really more instructive to consider the +limit at a point where a function is not continuous. +For example, consider the function +of which the graph is given in \Fig[fig.]{20} of \ChapRef{XI}. +This function~$f(x)$ is defined to have +the value~$1$ for all values of the argument +except the integers $0$,~$1$, $2$, $3$,~etc., and for these +integral values it has the value~$0$. Now let +us think of its limit when $x = 3$. We notice +that in the definition of the limit the value +of the function at~$a$ (in this case, $a = 3$) is excluded. +But, excluding~$f(3)$, the values of~$f(x)$, +when $x$~lies within any interval which +(i)~contains $3$ not as an end-point, and (ii)~does +not extend so far as $2$ and~$4$, are all +equal to~$1$; and hence these values approximate +to~$1$ within every standard of approximation. +Hence $1$~is the limit of~$f(x)$ at the +\PageSep{231} +value~$3$ of the argument~$x$, but by definition +$f(3) = 0$. + +This is an instance of a function which +possesses both a value and a limit at the +value~$3$ of the argument, but the value is not +equal to the limit. At the end of \ChapRef{XI}.\ +the function~$x^{2}$ was considered at the +value~$2$ of the argument. Its value at~$2$ is~$2^{2}$, +\ie~$4$, and it was proved that its limit is also~$4$. +Thus here we have a function with a +value and a limit which are equal. + +Finally we come to the case which is essentially +important for our purposes, namely, to +a function which possesses a limit, but no +defined value at a certain value of its argument. +We need not go far to look for +such a function, $\dfrac{2x}{x}$~will serve our purpose. +Now in any mathematical book, we might +find the equation, $\dfrac{2x}{x} = 2$, written without +hesitation or comment. But there is a difficulty +in this; for when $x$~is zero, $\dfrac{2x}{x} = \dfrac{0}{0}$; and +$\dfrac{0}{0}$~has no defined meaning. Thus the value +of the function~$\dfrac{2x}{x}$ at $x = 0$ has no defined +\PageSep{232} +meaning. But for every other value of~$x$, +the value of the function~$\dfrac{2x}{x}$ is~$2$. Thus the +limit of~$\dfrac{2x}{x}$ at $x = 0$ is~$2$, and it has no value +at $x = 0$. Similarly the limit of~$\dfrac{x^{2}}{x}$ at $x = a$ is~$a$ +whatever $a$~may be, so that the limit of~$\dfrac{x^{2}}{x}$ +at $x = 0$ is~$0$. But the value of~$\dfrac{x^{2}}{x}$ at $x = 0$ +takes the form~$\dfrac{0}{0}$, which has no defined +meaning. Thus the function~$\dfrac{x^{2}}{x}$ has a limit +but no value at~$0$. + +We now come back to the problem from +which we started this discussion on the nature +of a limit. How are we going to define the +rate of increase of the function~$x^{2}$ at any +value~$x$ of its argument. Our answer is that +this rate of increase is the limit of the function +$\dfrac{(x + h)^{2} - x^{2}}{h}$ at the value zero for its +argument~$h$. (Note that $x$~is here a ``constant.'') +Let us see how this answer works +\PageSep{233} +in the light of our definition of a limit. We +have +\[ +\frac{(x + h)^{2} - x^{2}}{h} + = \frac{2hx + h^{2}}{h} + = \frac{h(2x + h)}{h}\Add{.} +\] + +Now in finding the limit of~$\dfrac{h(2x + h)}{h}$ at the +value~$0$ of the argument~$h$, the value (if any) +of the function at $h = 0$ is excluded. But for +all values of~$h$, except $h = 0$, we can divide +through by~$h$. Thus the limit of~$\dfrac{h(2x + h)}{h}$ at +$h = 0$ is the same as that of $2x + h$ at $h = 0$. +Now, whatever standard of approximation~$k$ +we choose to take, by considering the interval +from $-\frac{1}{2}k$ to~$+\frac{1}{2}k$ we see that, for values of~$h$ +which fall within it, $2x + h$~differs from~$2x$ +by less than~$\frac{1}{2}k$, that is by less than~$k$. This +is true for \emph{any} standard~$k$. Hence in the neighbourhood +of the value~$0$ for~$h$, $2x + h$~approximates +to~$2x$ within \emph{every} standard of approximation, +and therefore $2x$~is the limit of~$2x + h$ +at $h = 0$. Hence by what has been said above +$2x$~is the limit of $\dfrac{(x + h)^{2} - x^{2}}{h}$ at the value~$0$ +for~$h$. It follows, therefore, that $2x$~is what +we have called the rate of increase of~$x^{2}$ at +the value~$x$ of the argument. Thus this +method conducts us to the same rate of increase +\PageSep{234} +for~$x^{2}$ as did the Leibnizian way of +making $h$~grow ``infinitely small.'' + +The more abstract terms ``differential coefficient,'' +\index{Differential Coefficient}% +or ``derived function,'' are generally +\index{Derived Function}% +used for what we have hitherto called the +``rate of increase'' of a function. The +general definition is as follows: the differential +coefficient of the function~$f(x)$ is the +limit, if it exist, of the function $\dfrac{f(x + h) - f(x)}{h}$ +of the argument~$h$ at the value~$0$ of its argument. + +How have we, by this definition and the +subsidiary definition of a limit, really managed +to avoid the notion of ``infinitely small numbers'' +which so worried our mathematical +forefathers? For them the difficulty arose +because on the one hand they had to use an +interval $x$~to $x + h$ over which to calculate +the average increase, and, on the other hand, +they finally wanted to put $h = 0$. The result +was they seemed to be landed into the notion +of an existent interval of zero size. Now +how do we avoid this difficulty? In this +way---we use the notion that corresponding +to \emph{any} standard of approximation, \emph{some} interval +with such and such properties can be +found. The difference is that we have +\index{Variable, The}% +grasped the importance of the notion of ``the +variable,'' and they had not done so. Thus, +\PageSep{235} +at the end of our exposition of the essential +notions of mathematical analysis, we are led +back to the ideas with which in \ChapRef{II}.\ +we commenced our enquiry---that in mathematics +the fundamentally important ideas +are those of ``\emph{some} things'' and ``\emph{any} +things.'' +\PageSep{236} + + +\Chapter{XVI}{Geometry} + +\First{Geometry}, like the rest of mathematics, is +\index{Geometry|EtSeq}% +abstract. In it the properties of the shapes +and relative positions of things are studied. +But we do not need to consider who is observing +the things, or whether he becomes acquainted +with them by sight or touch or +hearing. In short, we ignore all particular +sensations. Furthermore, particular things +such as the Houses of Parliament, or the +terrestrial globe are ignored. Every proposition +refers to any things with such and +such geometrical properties. Of course it +helps our imagination to look at particular +examples of spheres and cones and triangles +and squares. But the propositions do not +merely apply to the actual figures printed in +the book, but to any such figures. + +Thus geometry, like algebra, is dominated +by the ideas of ``any'' and ``some'' things. +Also, in the same way it studies the interrelations +of sets of things. For example, consider +any two triangles $ABC$ and~$DEF$. +\PageSep{237} + +What relations must exist between some of +\index{Triangle}% +the parts of these triangles, in order that the +triangles may be in all respects equal? This +is one of the first investigations undertaken +in all elementary geometries. It is a study +\Figure{33} +of a certain set of possible correlations between +the two triangles. The answer is that +the triangles are in all respects equal, if:--- +Either, (a)~Two sides of the one and the included +angle are respectively equal to two +sides of the other and the included angle: + +Or, (b)~Two angles of the one and the side +joining them are respectively equal to two +angles of the other and the side joining them: + +Or, (c)~Three sides of the one are respectively +equal to three sides of the other. + +This answer at once suggests a further enquiry. +What is the nature of the correlation +between the triangles, when the three angles +of the one are respectively equal to the three +angles of the other? This further investigation +leads us on to the whole theory of similarity +\index{Similarity}% +\PageSep{238} +(\Chg{cf.}{\cf}\ \ChapRef{XIII}.), which is another +type of correlation. + +Again, to take another example, consider +the internal structure of the triangle~$ABC$. +Its sides and angles are inter-related---the +greater angle is opposite to the greater side, +and the base angles of an isosceles triangle +are equal. If we proceed to trigonometry +this correlation receives a more exact determination +in the familiar shape +\[ +\frac{\sin A}{a} = \frac{\sin B}{b} = \frac{\sin C}{c}, +\] +$a^{2} = b^{2} + c^{2} - 2bc \cos A$, with two similar +formulæ. + +Also there is the still simpler correlation +between the angles of the triangle, namely, +that their sum is equal to two right angles; +and between the three sides, namely, that the +sum of the lengths of any two is greater than +the length of the third\Add{.} + +Thus the true method to study geometry is +to think of interesting simple figures, such as +the triangle, the parallelogram, and the circle, +and to investigate the correlations between +their various parts. The geometer has in his +mind not a detached proposition, but a figure +with its various parts mutually inter-dependent. +Just as in algebra, he generalizes the +triangle into the polygon, and the side into +\PageSep{239} +the conic section. Or, pursuing a converse +route, he classifies triangles according as they +are equilateral, isosceles, or scalene, and +polygons according to their number of sides, +and conic sections according as they are hyperbolas, +ellipses, or parabolas. + +The preceding examples illustrate how the +fundamental ideas of geometry are exactly +the same as those of algebra; except that +algebra deals with numbers and geometry +with lines, angles, areas, and other geometrical +entities. This fundamental identity +is one of the reasons why so many geometrical +truths can be put into an algebraic dress. +Thus if $A$,~$B$, and~$C$ are the numbers of degrees +respectively in the angles of the triangle~$ABC$, +the correlation between the angles is represented +by the equation +\[ +A + B + C = 180°; +\] +and if $a$,~$b$,~$c$ are the number of feet respectively +in the three sides, the correlation between the +sides is represented by $a < b + c$, $b < c + a$, +$c < a + b$. Also the trigonometrical formulæ +quoted above are other examples of the same +\index{Variable, The}% +fact. Thus the notion of the variable and +the correlation of variables is just as essential +in geometry as it is in algebra. + +But the parallelism between geometry and +algebra can be pushed still further, owing to +the fact that lengths, areas, volumes, and +\PageSep{240} +angles are all measurable; so that, for example, +the size of any length can be determined +by the number (not necessarily integral) of +times which it contains some arbitrarily known +unit, and similarly for areas, volumes, and +angles. The trigonometrical formulæ, given +above, are examples of this fact. But it receives +its crowning application in analytical +geometry. This great subject is often misnamed +as Analytical Conic Sections, thereby +\index{Analytical Conic Sections}% +fixing attention on merely one of its subdivisions. +It is as though the great science +of Anthropology were named the Study of +Noses, owing to the fact that noses are a +prominent part of the human body. + +Though the mathematical procedures in +geometry and algebra are in essence identical +and intertwined in their development, there +is necessarily a fundamental distinction between +the properties of space and the properties +of number---in fact all the essential difference +between space and number. The ``spaciness'' +of space and the ``numerosity'' of +number are essentially different things, and +must be directly apprehended. None of the +applications of algebra to geometry or of +geometry to algebra go any step on the road +to obliterate this vital distinction. + +One very marked difference between space +and number is that the former seems to be so +much less abstract and fundamental than the +\PageSep{241} +latter. The number of the archangels can be +counted just because they are things. When +we once know that their names are Raphael, +Gabriel, and Michael, and that these distinct +names represent distinct beings, we know without +further question that there are three of +them. All the subtleties in the world about +the nature of angelic existences cannot alter +this fact, granting the premisses. + +But we are still quite in the dark as to their +relation to space. Do they exist in space at +all? Perhaps it is equally nonsense to say +that they are here, or there, or anywhere, or +everywhere. Their existence may simply have +no relation to localities in space. Accordingly, +while numbers must apply to all things, +space need not do so. + +The perception of the locality of things +would appear to accompany, or be involved +in many, or all, of our sensations. It is independent +of any particular sensation in the +sense that it accompanies many sensations. +But it is a special peculiarity of the things +which we apprehend by our sensations. The +direct apprehension of what we mean by the +positions of things in respect to each other +is a thing \Foreign{sui generis}, just as are the apprehensions +of sounds, colours, tastes, and smells. +At first sight therefore it would appear that +mathematics, in so far as it includes geometry +in its scope, is not abstract in the sense in +\PageSep{242} +which abstractness is ascribed to it in +\ChapRef{I}. + +This, however, is a mistake; the truth being +\index{Abstract Nature of Geometry|EtSeq}% +that the ``spaciness'' of space does not enter +into our geometrical \emph{reasoning} at all. It +enters into the geometrical intuitions of +mathematicians in ways personal and peculiar +to each individual. But what enter into the +reasoning are merely certain properties of +things in space, or of things forming space, +which properties are completely abstract in +the sense in which abstract was defined in +\ChapRef{I}.; these properties do not involve +any peculiar space-apprehension or space-intuition +or space-sensation. They are on +exactly the same basis as the mathematical +properties of number. Thus the space-intuition +which is so essential an aid to the study +of geometry is logically irrelevant: it does +not enter into the premisses when they are +properly stated, nor into any step of the reasoning. +It has the practical importance of an +example, which is essential for the stimulation +of our thoughts. Examples are equally necessary +to stimulate our thoughts on number. +When we think of ``two'' and ``three'' we +see strokes in a row, or balls in a heap, or +some other physical aggregation of particular +things. The peculiarity of geometry is the +fixity and overwhelming importance of the +one particular example which occurs to our +\PageSep{243} +minds. The abstract logical form of the +propositions when fully stated is, ``If any +collections of things have such and such +abstract properties, they also have such and +such other abstract properties.'' But what +appears before the mind's eye is a collection +of points, lines, surfaces, and volumes in the +space: this example inevitably appears, and +is the sole example which lends to the proposition +its interest. However, for all its overwhelming +importance, it is but an example. + +Geometry, viewed as a mathematical science, +is a division of the more general science of +order. It may be called the science of dimensional +order; the qualification ``dimensional'' +has been introduced because the limitations, +which reduce it to only a part of the general +science of order, are such as to produce the +regular relations of straight lines to planes, +and of planes to the whole of space. + +It is easy to understand the practical importance +of space in the formation of the +scientific conception of an external physical +world. On the one hand our space-perceptions +are intertwined in our various sensations +and connect them together. We normally +judge that we touch an object in the same +place as we see it; and even in abnormal +cases we touch it in the same space as we see +it, and this is the real fundamental fact which +ties together our various sensations. Accordingly, +\PageSep{244} +the space perceptions are in a sense the +common part of our sensations. Again it +happens that the abstract properties of space +form a large part of whatever is of spatial +interest. It is not too much to say that to +every property of space there corresponds an +abstract mathematical statement. To take +the most unfavourable instance, a curve may +have a special beauty of shape: but to this +shape there will correspond some abstract +mathematical properties which go with this +shape and no others. + +Thus to sum up: (1)~the properties of space +which are investigated in geometry, like those +of number, are properties belonging to things +as things, and without special reference to +any particular mode of apprehension: (2)~Space-perception +accompanies our sensations, +perhaps all of them, certainly many; but it +does not seem to be a necessary quality of +things that they should all exist in one space +or in any space. +\PageSep{245} + + +\Chapter{XVII}{Quantity} + +\First{In} the previous chapter we pointed out +\index{Quantity|EtSeq}% +that lengths are measurable in terms of some +unit length, areas in term of a unit area, and +volumes in terms of a unit volume. + +When we have a set of things such as +lengths which are measurable in terms of any +one of them, we say that they are quantities +of the same kind. Thus lengths are quantities +of the same kind, so are areas, and so are +volumes. But an area is not a quantity of +the same kind as a length, nor is it of the +same kind as a volume. Let us think a little +more on what is meant by being measurable, +taking lengths as an example. + +Lengths are measured by the foot-rule. By +transporting the foot-rule from place to place +we judge of the equality of lengths. Again, +three adjacent lengths, each of one foot, form +one whole length of three feet. Thus to +measure lengths we have to determine the +equality of lengths and the addition of lengths. +When some test has been applied, such as the +transporting of a foot-rule, we say that the +lengths are equal; and when some process +\PageSep{246} +has been applied, so as to secure lengths being +contiguous and not overlapping, we say that +the lengths have been added to form one +whole length. But we cannot arbitrarily take +any test as the test of equality and any +process as the process of addition. The results +of operations of addition and of judgments +of equality must be in accordance with +certain preconceived conditions. For example, +the addition of two greater lengths must +yield a length greater than that yielded by +the addition of two smaller lengths. These +preconceived conditions when accurately formulated +may be called axioms of quantity. +The only question as to their truth or falsehood +\index{Axioms of Quantity|EtSeq}% +which can arise is whether, when the axioms +are satisfied, we necessarily get what ordinary +people call quantities. If we do not, then +the name ``axioms of quantity'' is ill-judged---that +is all. + +These axioms of quantity are entirely abstract, +just as are the mathematical properties +of space. They are the same for all quantities, +and they presuppose no special mode of perception. +The ideas associated with the notion +of quantity are the means by which a continuum +like a line, an area, or a volume can +be split up into definite parts. Then these +parts are counted; so that numbers can be +used to determine the exact properties of a +continuous whole. +\PageSep{247} + +Our perception of the flow of time and of +\index{Time|EtSeq}% +the succession of events is a chief example +of the application of these ideas of quantity. +We measure time (as has been said in considering +periodicity) by the repetition of +similar events---the burning of successive +inches of a uniform candle, the rotation of +the earth relatively to the fixed stars, the +rotation of the hands of a clock are all examples +of such repetitions. Events of these +types take the place of the foot-rule in relation +to lengths. It is not necessary to assume +that events of any one of these types are +exactly equal in duration at each recurrence. +What is necessary is that a rule should be +known which will enable us to express the +relative durations of, say, two examples of +some type. For example, we may if we like +suppose that the rate of the earth's rotation +is decreasing, so that each day is longer than +the preceding by some minute fraction of a +second. Such a rule enables us to compare +the length of any day with that of any other +day. But what is essential is that one series +of repetitions, such as successive days, should +be taken as the standard series; and, if the +various events of that series are not taken as +of equal duration, that a rule should be +stated which regulates the duration to be +assigned to each day in terms of the duration +of any other day. +\PageSep{248} + +What then are the requisites which such +a rule ought to have? In the first place it +should lead to the assignment of nearly equal +durations to events which common sense +judges to possess equal durations. A rule +which made days of violently different lengths, +and which made the speeds of apparently +similar operations vary utterly out of proportion +to the apparent minuteness of their +differences, would never do. Hence the first +requisite is general agreement with common +sense. But this is not sufficient absolutely +to determine the rule, for common sense is a +rough observer and very easily satisfied. The +next requisite is that minute adjustments of +the rule should be so made as to allow of the +simplest possible statements of the laws of +nature. For example, astronomers tell us +that the earth's rotation is slowing down, so +that each day gains in length by some inconceivably +minute fraction of a second. Their +only reason for their assertion (as stated more +fully in the discussion of periodicity) is that +without it they would have to abandon the +Newtonian laws of motion. In order to keep +\index{Laws of Motion}% +the laws of motion simple, they alter the +measure of time. This is a perfectly legitimate +procedure so long as it is thoroughly +understood. + +What has been said above about the abstract +nature of the mathematical properties +\PageSep{249} +of space applies with appropriate verbal +changes to the mathematical properties of +time. A sense of the flux of time accompanies +all our sensations and perceptions, and practically +all that interests us in regard to time +can be paralleled by the abstract mathematical +properties which we ascribe to it. +Conversely what has been said about the two +requisites for the rule by which we determine +the length of the day, also applies to the rule +for determining the length of a yard measure---namely, +the yard measure appears to retain +the same length as it moves about. Accordingly, +any rule must bring out that, apart +from minute changes, it does remain of invariable +length; Again, the second requisite +is this, a definite rule for minute changes +shall be stated which allows of the simplest +expression of the laws of nature. For example, +in accordance with the second requisite +the yard measures are supposed to +expand and contract with changes of temperature +according to the substances which +they are made of. + +Apart from the facts that our sensations +are accompanied with perceptions of locality +and of duration, and that lines, areas, volumes, +and durations, are each in their way quantities, +the theory of numbers would be of very +subordinate use in the exploration of the laws +of the Universe, As it is, physical science +\PageSep{250} +reposes on the main ideas of number, quantity, +space, and time. The mathematical +sciences associated with them do not form +the whole of mathematics, but they are the +substratum of mathematical physics as at +present existing. + + +\BackMatter +\Appendix{Notes} + +\Note{A} (\Pageref{60}).---In reading these equations it must be noted +that a bracket is used in mathematical symbolism to +mean that the operations within it are to be performed +first. Thus $(1 + 3) + 2$ directs us first to add $3$ to~$1$, and +then to add~$2$ to the result; and $1 + (3 + 2)$ directs us +first to add $2$ to~$3$, and then to add the result to~$1$. Again +a numerical example of equation~\Eq{(5)} is +\[ +2 × (3 + 4) = (2 × 3) + (2 × 4). +\] +We perform first the operations in brackets and obtain +\[ +2 × 7 = 6 + 8 +\] +which is obviously true. + + +\Note{B} (\Pageref{136}).---This fundamental ratio~$\dfrac{SP}{PN}$ is called the +eccentricity of the curve. The shape of the curve, as +\index{Eccentricity}% +distinct from its scale or size, depends upon the value of +its eccentricity. Thus it is wrong to think of ellipses +in general or of hyperbolas in general as having in either +case one definite shape. Ellipses with different eccentricities +have different shapes, and their sizes depend +upon the lengths of their major axes. An ellipse with +small eccentricity is very nearly a circle, and an ellipse +of eccentricity only slightly less than unity is a long +flat oval. All parabolas have the same eccentricity and +are therefore of the same shape, though they can be +drawn to different scales. +\PageSep{251} + +\Note{C} (\Pageref{204}).---If a series with all its terms positive is +\index{Absolute Convergence}% +\index{Convergence, Absolute}% +convergent, the modified series found by making some +terms positive and some negative according to any +definite rule is also convergent. Each one of the set of +series thus found, including the original series, is called +``absolutely convergent.'' But it is possible for a series +with terms partly positive and partly negative to be +convergent, although the corresponding series with all +its terms positive is divergent. For example, the series +\[ +1 - \tfrac{1}{2} + \tfrac{1}{3} - \tfrac{1}{4} + \text{etc.} +\] +is convergent though we have just proved that +\[ +1 + \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{4} + \text{etc.} +\] +is divergent. Such convergent series, which are not +absolutely convergent, are much more difficult to deal +with than absolutely convergent series. + + +\Appendix[Note on the Study of Mathematics]{Bibliography} + + +\First{The} difficulty that beginners find in the study of this +science is due to the large amount of technical detail which +has been allowed to accumulate in the elementary text-books, +obscuring the important ideas. + +The first subjects of study, apart from a knowledge of +arithmetic which is presupposed, must be elementary +geometry and elementary algebra. The courses in both +subjects should be short, giving only the necessary ideas; +the algebra should be studied graphically, so that in +practice the ideas of elementary coordinate geometry are +also being assimilated. The next pair of subjects should +be elementary trigonometry and the coordinate geometry +of the straight line and circle. The latter subject is a +short one; for it really merges into the algebra. The +student is then prepared to enter upon conic sections, a +very short course of geometrical conic sections and a longer +one of analytical conics. But in all these courses great +care should be taken not to overload the mind with more +\PageSep{252} +detail than is necessary for the exemplification of the +fundamental ideas. + +The differential calculus and afterwards the integral +calculus now remain to be attacked on the same system. +A good teacher will already have illustrated them by the +consideration of special cases in the course on algebra +and coordinate geometry. Some short book on three-dimensional +geometry must be also read. + +This elementary course of mathematics is sufficient for +some types of professional career. It is also the necessary +preliminary for any one wishing to study the subject for +its intrinsic interest. He is now prepared to commence +on a more extended course. He must not, however, hope +to be able to master it as a whole. The science has grown +to such vast proportions that probably no living mathematician +can claim to have achieved this. + +Passing to the serious treatises on the subject to be read +\emph{after} this preliminary course, the following may be mentioned: +Cremona's \Title{Pure Geometry} (English Translation, +Clarendon Press, Oxford), Hobson's \Title{Treatise on Trigonometry}, +Chrystal's \Title{Treatise on Algebra} (2~volumes), Salmon's +\Title{Conic Sections}, Lamb's \Title{Differential Calculus}, and some +book on \Title{Differential Equations}. The student will probably +not desire to direct equal attention to all these subjects, +but will study one or more of them, according as his interest +dictates. He will then be prepared to select more advanced +works for himself, and to plunge into the higher +parts of the subject. If his interest lies in analysis, he +should now master an elementary treatise on the theory +of Functions of the Complex Variable; if he prefers to +specialize in Geometry, he must now proceed to the +standard treatises on the Analytical Geometry of three +dimensions. But at this stage of his career in learning +he will not require the advice of this note. + +I have deliberately refrained from mentioning any +elementary works. They are very numerous, and of +various merits, but none of such outstanding superiority +as to require special mention by name to the exclusion +of all the others. + + +%[** TN: Index text] +% ** Page 253 +\printindex +\iffalse + +Abel 156 + +Abscissa 95 + +Absolute Convergence 251 + +Abstract Nature of Geometry|EtSeq 242 + +Abstractness (\emph{defined}) 9, 13 + +Adams 220 + +Addition-Theorem 212 + +Ahmes 71 + +Alexander the Great 128, 129 + +Algebra, Fundamental Laws of 60 + +Ampere@Ampère 34 + +Analytical Conic Sections 240 + +Apollonius of Perga 131, 134 + +Approximation|EtSeq 197 + +Arabic Notation|EtSeq 58 + +Archimedes|EtSeq 37 + +Argument of a Function 146 + +Aristotle 30, 42, 128 + +Astronomy 137, 173, 174 + +Axes 125 + +Axioms of Quantity|EtSeq 246 + +Bacon 156 + +Ball, W. W. R. 58 + +Beaconsfield, Lord 41 + +Berkeley, Bishop 226 + +Bhaskara 58 + +Cantor, Georg 79 + +Circle 120, 130 + +Circle@Circle|EtSeq 180 + +Circular Cylinder 143 + +Clerk Maxwell 34, 35 + +Columbus 122 + +Compact Series 76 + +Complex Quantities 109 + +Conic Sections|EtSeq 128 + +Constants 69, 117 + +Continuous Functions@Continuous Functions|EtSeq 150 + +Continuous Functions@Continuous Functions (\emph{defined}) 162 + +Convergence, Absolute 251 + +Convergent|EtSeq 203 + +Coordinate Geometry|EtSeq 112 + +Coordinates 95 + +Copernicus 45, 137 + +%[** TN: Entry italicized in the original, "Sine" not italicized] +Cosine|EtSeq 182 + +Coulomb 33 + +Cross Ratio 140 + +Darwin 138, 220 + +Derived Function 234 + +Descartes 95, 113, 116, 122, 218 + +Differential Calculus|EtSeq 217 + +Differential Coefficient 234 + +Directrix 135 + +Discontinuous Functions|EtSeq 150 + +Distance 30 + +Divergent|EtSeq 203 +% ** Page 254 + +Dynamical Explanation 13, 14 + +Dynamical Explanation@Dynamical Explanation|EtSeq 47 + +Dynamics 30 + +Dynamics@Dynamics|EtSeq 43 + +Eccentricity 250 + +Electric Current 33 + +Electricity|EtSeq 32 + +Electromagnetism|EtSeq 31 + +Ellipse 45, 120 + +Ellipse@Ellipse|EtSeq 130 + +Euclid 114 + +Exponential Series|EtSeq 211 + +Faraday 34 + +Fermat 218 + +Fluxions 219 + +Focus 120, 135 + +Force 30 + +Form, Algebraic@Form, Algebraic|EtSeq 66 + +Form, Algebraic 82, 117 + +Fourier's Theorem 191 + +Fractions|EtSeq 71 + +Franklin 32, 122 + +Function|EtSeq 144 + +Galileo@Galileo|EtSeq 42 + +Galileo 30, 122 + +Galvani 33 + +Generality in Mathematics 82 + +Geometrical Series|EtSeq 206 + +Geometry 36 + +Geometry@Geometry|EtSeq 236 + +Gilbert, Dr. 32 + +Graphs|EtSeq 148 + +Gravitation 29, 139 + +Halley 139 + +Harmonic Analysis 192 + +Harriot, Thomas 66 + +Herz 35 + +Hiero 38 + +Hipparchus 173 + +Hyperbola|EtSeq 131 + +Imaginary Numbers|EtSeq 87 + +Imaginary Quantities 109 + +Incommensurable Ratios|EtSeq 72 + +Infinitely Small Quantities|EtSeq 226 + +Integral Calculus 222 + +Interval|EtSeq 158 + +Kepler 45, 46, 137, 138 + +Kepler's Laws 138 + +Laputa 10 + +Laws of Motion@Laws of Motion|EtSeq 167 + +Laws of Motion 248 + +Leibniz 16 + +Leibniz@Leibniz|EtSeq 218 + +Leonardo da Vinci 42 + +Leverrier 220 + +Light 35 + +Limit of a Function|EtSeq 227 + +Limit of a Series|EtSeq 199 + +Limits 77 + +Locus@Locus|EtSeq 121 + +Locus 141 + +Macaulay 156 + +Malthus 138 + +Marcellus 37 + +Mass 30 + +Mechanics 46 + +Menaechmus 128, 129 + +Motion, First Law of 43 +% ** Page 255 + +Neighbourhood|EtSeq 159 + +Newton 10, 16, 30, 34, 37, 38, 43, 46, 139 + +Newton@Newton|EtSeq 218 + +Non-Uniform Convergence|EtSeq 208 + +Normal Error, Curve of 214 + +Oersted@Öersted 34 + +Order|EtSeq 194 + +Order, Type of@Order, Type of|EtSeq 75 + +Order, Type of 196 + +Ordered Couples|EtSeq 93 + +Ordinate 95 + +Origin 95, 126 + +Pappus 135, 136 + +Parabola|EtSeq 131 + +Parallelogram Law@Parallelogram Law|EtSeq 51 + +Parallelogram Law 99, 126 + +Parameters 69, 117 + +Pencils 140 + +Period 170 + +Period@Period|EtSeq 189 + +Periodicity@Periodicity|EtSeq 164 + +Periodicity 188, 216 + +Pitt, William 194 + +Pizarro 122 + +Plutarch 37 + +Positive and Negative Numbers|EtSeq 83 + +Projective Geometry 139 + +Ptolemy 137, 173 + +Pythagoras 18 + +Quantity|EtSeq 245 + +Rate of Increase of Functions|EtSeq 220 + +Ratio|EtSeq 72 + +Real Numbers|EtSeq 73 + +Rectangle 57 + +Relations between Variables|EtSeq 18 + +Resonance 170, 171 + +Rosebery, Lord 194 + +Scale of a Map 178 + +Seidel 210 + +Series|EtSeq 74, 194 + +Shelley (quotation from) 217 + +Similarity@Similarity|EtSeq 177 + +Similarity 237 + +Sine|EtSeq 182 + +Specific Gravity 41 + +Squaring the Circle 187 + +Standard of Approximation|EtSeq 159, 201, 229 + +Steps@Steps|EtSeq 79 + +Steps 96 + +Stifel 85 + +Stokes, Sir George 210 + +Sum to Infinity|EtSeq 201 + +Surveys|EtSeq 176 + +Swift 10 + +Tangents 221, 222 + +Taylor's Theorem 156, 157 + +Time|EtSeq 166, 247 + +Transportation, Vector of|EtSeq 54 + +Triangle@Triangle|EtSeq 176 + +Triangle 237 + +Triangulation 177 + +Trigonometry|EtSeq 173 + +Uniform Convergence|EtSeq 208 + +Unknown, The 17, 23 +% ** Page 256 + +Value of a Function 146 + +Variable, The 18, 24, 49, 82, 234, 239 + +Variable Function 147 + +Vectors@Vectors|EtSeq 51 + +Vectors 85, 96 + +Vertex 134 + +Volta 33 + +Wallace 220 + +Weierstrass 156, 226, 228 + +Zero@Zero|EtSeq 63 + +Zero 103 +%[** TN: End of index] +\fi + +% Printed by Hazell, Walton \& Viney, Ld., London and Aylesbury. +%[** TN: Raw OCR output of book catalog follows] +\iffalse + +The + +Home University +Library + + + +of Modern +Knowledge + + + +jj Comprehensive Series of New +and Specially Written (Books + + + +EDITORS: + +PROF. GILBERT MURRAY, D.Litt., LL.D., F.B.A. +HERBERT FISHER, M.A., F.B.A. +PKOF. J. ARTHUR THOMSON, M.A. +PROF. WM. T. BREWSTER, M.A. + +The Home University Library + +" Is without the slightest doubt the pioneer in supplying serious literature +for a large section of the public who are interested in the liberal educa- +tion of the State." The Daily Mail. + +" It is a thing very favourable to the real success of The Home +University Library that its volumes do not merely attempt to feed +ignorance with knowledge. The authors noticeably realise that the +simple willing appetite of sharp-set ignorance is not specially common +nowadays; what is far more common is a hunger which has been +partially but injudiciously filled, with more or less serious results of +indigestion. The food supplied is therefore frequently medicinal as +well as nutritious; and this is certainly what the time requires. " +Manchester Guardian. + +"Each volume represents a three-hours' traffic with the talking-power +of a good brain, operating with the ease and interesting freedom of a +specialist dealing with his own subject. ... A series which promises to +perform a real social service." The Times. + +"We can think of no series now being issued which better deserves +support." The Observer. + + + +We think if they were given as prizes in place of the more costly + +di: + +id prol +series they might well take: + + + +ispensed on prize days, the pupils would +rofit. If the publishers want a motto for the + + + +rubbish that is wont to be + +find more pleasure and + +series they might well take: ' Infinite riches in a little room.'" Irish + +Journal of Education, + +" The scheme was successful at the start because it met a want +among earnest readers; but its wider and* sustained success, surely, +comes from the fact that it has to a large extent created and certainly +refined the taste by which it is appreciated." Daily Chronicle. + +" Here is the world's learning in little, and none too poor t< +house-room!" Daily Telegraph. + + + +to give it + + + +]/- net +in cloth + + +256 Pages + + +2/6 net +in leather + + + +History and (geography + + + +3. THE FRENCH REVOLUTION + +By HILAIKE BELLOC, M.A. (With Maps.) "It is coloured with all the +militancy of the author's temperament." Daily News. + +4. HISTORY OF WAR AND PEACE + +By G. H. FERRIS. The Rt. Hon. JAMES BRYCE writes: " I have read it with +much interest and pleasure, admiring the skill with which you have managed +to compress so many facts and views into so small a volume." + +8. POLAR EXPLORATION + +By Dr W. S. BRUCE, F.R.S.E., Leader of the "Scotia" Expedition. (With +Maps.) "A very freshly written and interesting narrative." The Times. +"A fascinating book." Portsmouth Times. + +12. THE OPENING-UP OF AFRICA + +By Sir H. H. JOHNSTON. G.C.M.G., K.C.B., D.Sc., F.Z.S. (With Maps.) +" The Home University Library is much enriched by this excellent work." +Daily Mail. + +13. MEDIAEVAL EUROPE + +By H. W. C. DAVIS, M.A. (With Maps.) "One more illustration of the +fact that it takes a complete master of the subject to write briefly upon it." +Manchester Guardian. + +14. THE PAPACY \&* MODERN TIMES (1303-1870) + +By WILLIAM BARRY, D.D. "Dr Barry has a wide range of knowledge +and an artist's power of selection." Manchester Guardian. + +23. HISTORY OF OUR TIME, 1885-1911 + +By G. P. GOOCH, M.A. " Mr Gooch contrives to breathe vitality into his story, +and to give us the flesh as well as the bones of recent happenings." Observer. + +25. THE CIVILISATION OF CHINA + +By H. A. GILES, LL.D., Professor of Chinese in the University of Cambridge. +"In all the mass of facts, Professor Giles never becomes dull. He is always +ready with a ghost story or a street adventure for the reader's recreation." +Spectator. + +29. THE DA WN OF HISTORY + +By J.L.MYRES, M. A., F.S. A., Wykeham Professor of Ancient History, Oxford. +"There is not a page in it that is not suggestive." Manchester Guardian. + +33. THE HISTORY OF ENGLAND: +A Study in Political Evolution. + +By Prof. A. F. POLLARD, M.A. With a Chronological Table. " It takes its +place at once among the authoritative works on English history." Observer. + +34. CANADA + +By A. G. BRADLEY. " Who knows Canada, better than Mr A. G. Bradley? " +Daily Chronicle. "The volume makes an immediate appeal to the man who +wants to know something vivid and true about Canada." Canadian Gazette. + + + +37. PEOPLES 6* PROBLEMS OF INDIA + +By Sir T. W. HOLDERNESS, K.C.S.I., Secretary of the Revenue, Statistics, +! and Commerce Department of the India Office. "Just the book which news- +paper readers require to-day, and a marvel of comprehensiveness." Pall +\ Mall Gazette. + +42. ROME + +By W. WARDE FOWLHR, M.A. " A masterly sketch of Roman character and +of what it did for the world." The Spectator. "It has all the lucidity and +charm of presentation we expect from this writer." Manchester Guardian. + +48. THE AMERICAN CIVIL WAR + +By F. L. PAXSON, Professor of American History, Wisconsin University. +(With Maps.) "A stirring study." The Guardian. + +51. WARFARE IN BRITAIN + +By HILAIRE BELLOC, M.A. An account of how and where great battles of the +past were fought on British soil, the roads and physical conditions determining +the island's strategy, the castles, walled towns, etc. + +55. MASTER MARINERS + +By J. R. SPEARS. The romance of the sea, the great voyages of discovery, +naval battles, the heroism of the sailor, and the development of the ship, from +ancient times to to-day. + +IN PREPARATION + +ANCIENT GREECE. By Prof. GILBERT MURRAY, D.Litt., LL.D., F.B.A +ANCIENT EGYPT. By F. LL. GRIFFITH, M.A. +THE ANCIENT EAST. By D. G. HOGARTH, M.A., F.B.A. +A SHORT h'ISTOR YOFEUROPE. By HERBERT FISHER, M. A., F.B.A. +PREHISTORIC BRITAIN. By ROBERT MUNRO, M.A., M.D., LL.D. +THE BYZANTINE EMPIRE. By NORMAN H. BAVNES. +THE REFORM A TION. By Principal LINDSAY, LL.D. +NAPOLEON. By HERBERT FISHER, M.A., F.B.A. +A SHORT HISTORY OF RUSSIA. By Prof. MILYOUKOV. +MODERN TURKEY. By D. G. HOGARTH, M.A. +FRANCE OF TO-DAY. By ALBERT THOMAS. +GERMANY OF TO-DA Y. By CHARLES TOWER. +THE NAVY AND SEA POWER. By DAVID HANNAY. +HISTORY OF SCOTLAND. By R. S. RAIT, M.A. +SOUTH AMERICA. By Prof. W. R. SHEPHERD. +LONDON. By Sir LAURENCE GOMME, F.S.A. + +HISTORY AND LITERATURE OF SPAIN. By J. FITZMAURICE- +KELLY, F.B.A., Litt.D. + + + +Literature and + + + +2. SHAKESPEARE + +By JOHN MASEFIELD. " The book is a joy. We have had half-a-dozen more +learned books on Shakespeare in the last few years, but not one so wise." +Manchester Guardian. + +27. ENGLISH LITERATURE: MODERN + +By G. H. MAIR, M.A. " Altogether a fresh and individual book." Olstrver. + +35. LANDMARKS IN FRENCH LITERATURE + +By G. L. STRACHEY. " Mr Strachey is to be congratulated on his courage and +success. It is difficult to imagine how a better account of French Literature +could be given in 250 small pages than he has given here." The Times. + + + +39- ARCHITECTURE + +By Prof. W. R. LETHABY. (Over forty Illustrations.) " Popular guide-books +to architecture are, as a rule, not worth ranch. This volume is a welcome excep- +tion." Building News. " Delightfully bright reading." Christian World. + +43. ENGLISH LITERATURE: MEDIAEVAL + +By Prof. W. P. KER, M.A. "Prof. Ker has long proved his worth as one of +the soundest scholars in English we have, and he is the very man to put an +outline of English Mediaeval Literature before the uninstructed public. His +knowledge and taste are unimpeachable, and his style is effective, simple, yet +never dry." The Athemeum. + +45. THE ENGLISH LANGUAGE + +By L. PEARSALL SMI-TH, M.A. "A wholly fascinating study of the different +streams that went to the making of the great river of the English speech." +Daily News. + +52. GREAT WRITERS OF AMERICA + +By Prof. J. EKSKINE and Prof. W. P. TRENT. A popular sketch by two +foremost authorities. + +IN PREPARATION + +ANCIENT ART AND RITUAL. By Miss JANE HARRISON, LL.D., + +D.Litt. + +GREEK LITERA TURE. By Prof. GILBERT MURRAY, D.Litt. +LA TIN LITER A TURE. By Prof. J. S. PHILLIMORE. +CHA UCER AND HIS TIME. By Miss G. E. HADOW. +THE RENAISSANCE. By Mrs R. A. TAYLOR. + +ITALIAN A RTOF THE RENAISSANCE. By ROGER E. FRY, M.A. +THE ART OF PAINTING. By Sir FREUERICK WEDMORE. +DR JOHNSON AND HIS CIRCLE. By JOHN BAILEY, M.A. +THE VIC IORIAN AGE. By G. K- CHESTERTON. +ENGLISH COMPOSITION. By Prof. WM. T. BREWSTER. +GREA T WRITERS OF RUSSIA. By C. T. HAGBERG WRIGHT, LL.D. +THE LITERATURE OF GERMANY. By Prof. J. G. ROBERTSON, + +M.A., Ph.D. +SCANDINAVIAN HISTORY AND LITERATURE. By T. C. + +SNOW, M.A. + + + +Science + + + +7. MODERN GEOGRAPHY + +By Dr MARION NEWBIGIN. (Illustrated.) "Geography, again: what a dull, +tedious study that was wont to be I . . . But Miss Marion Newbigin invests its +dry bones with the flesh and blood of romantic interest, taking stock of +geography as a fairy-book of science." Daily Telegraph. + +9. THE EVOLUTION OF PLANTS + +By Dr D. H. SCOTT, M.A., F.R.S., late Hon. Keeper of the Jodrell Laboratory, +Kew. (Fully illustrated.) "The information which the book provides is as +trustworthy as first-band knowledge can make it. ... Dr Scott's candid and +familiar style makes the difficult subject both fascinating and easy." +Gardeners' Chronicle. + +17. HEALTH AND DISEASE + +By W. LESLIE MACKKNZIE, M.D., Local Government Board, Edinburgh. +"The science of public health administration has had no abler or more attractive +exponent than Dr Mackenzie. He adds to a thorough grasp of the problems +an illuminating style, and an arresting manner of treating a subject often +dull and sometimes unsavoury." Economist. + + + +1 8. INTRODUCTION TO MATHEMATICS + +' By A. N. WHITEHEAD, Sc.D., F.R.S. (With Diagrams.) "MrWhitehead +has discharged with conspicuous success the task he is so exceptionally qualified + +I to undertake. For he is one of our great authorities upon the foundations of the +science, and has the breadth of view which is so requisite in presenting to the +reader its aims. His exposition is clear and striking." Westminster Gazette. + +19. THE ANIMAL WORLD + +By Professor F. W. GAMBLE, D.Sc., F.R.S. With Introduction hy Sir Oliver +Lodge. (Many Illustrations.) " A delightful and instructive epitome of animal +(and vegetable) life. ... A most fascinating and suggestive survey." Morning +Post. + +20. EVOLUTION + +By Professor J. ARTHUR THOMSON and Professor PATRICK GEDDES. "A +many-coloured and romantic panorama, opening up, like no other book we know, +a rational vision of world-development." Belfast News-Letter. + +22. CRIME AND INSANITY + +By Dr C. A. MERCIER, F.R.C.P., F.R.C.S., Author of "Text-Book of In- +sanity," etc- " Furnishes much valuable information from one occupying the +highest position among medico-legal psychologists." Asylum NCVJS. + +28. PSYCHICAL RESEARCH + + + +and thus what he has to say on thought-reading, hypnotism, telepathy, crystal- +vision, spiritualism, divinings, and so on, will be read with avidity." Dundee + + + + +31. ASTRONOMY + +By A. R. HINKS, M.A., Chief Assistant, Cambridge Observatory. "Original +in thought, eclectic in substance, and critical in treatment. . . . No better +little book is available." School World. + +32. INTRODUCTION TO SCIENCE + +By J. ARTHUR THOMSON, M.A., Regius Professor of Natural History, Aberdeen +University. " Professor Thomson's delightful literary style is well known; and +here he discourses freshly and easily on the methods of science and its relations +with philosophy, art, religion, and practical life." Aberdeen Journal, + +36. + + + +By H. N. DICKSON, D.Sc. Oxon., M.A., F.R.S.E., President of the Royal +Meteorological Society; Professor of Geography in University College, Reading. +(With Diagrams.) "The author has succeeded in presenting in a very lucid +and agreeable manner the causes of the movement of the atmosphere and of +the more stable winds." Manchester Guardian. + +41. ANTHROPOLOGY + +By R R. MARETT, M.A., Reade +"An absolutely perfect handboo +fascinating and human that it bea + +44. THE PRINCIPLES OF PHYSIOLOGY + +By Prof. J. G. McKENDRiCK, M.D. " It is a delightful and wonderfully com- +prehensive handling of a subject which, while of importance to all, does not +readily lend itself to untechnical explanation. . . . The little book is more than +a mere repository of knowledge; upon every page of it is stamped the impress +of a creative imagination." Glasgow Herald. + + + +By R. R. MARETT, M.A., Reader in Social Anthropology in Oxford University. +"An absolutely perfect handbook, so clear that a child could understand it, so +fascinating and human that it beats fiction ' to a frazzle.' " Morning Leader. + + + +46. MATTER AND ENERGY + +By F. SODDY, M.A., F.R.S. "A most fascinating and instructive account or +the great facts of physical science, concerning which our knowledge, of later +years, has made such wonderful progress." The Bookseller. + +49. PSYCHOLOGY, THE STUDY OF BEHAVIOUR + +By Prof. W. McDouGALL, F.R.S., M.B. "A happy example of the non- +technical handling of an unwieldy science, suggesting rather than dogmatising. +It should whet appetites for deeper study." Christian World. + +53. THE MAKING OF THE EARTH + +ByProf.J.W. GREGORY, F.R.S. (With 38 Maps and Figures.) The Professor +of Geology at Glasgow describes the origin of the earth, the formation and +changes of its surface and structure, its geological history, the first appearance +of life, and its influence upon the globe. + +57. THE HUMAN BODY + +By A. KEITH, M.D., LL,D., Conservator of Museum and Hunterian Pro- +fessor, Royal College of Surgeons. (Illustrated.) The work of the dissecting- +room is described, and among other subjects dealt with are: the development +of the body; malformations and monstrosities; changes of youth and age; sex +differences, are they increasing or decreasing? race characters; bodily features +as indexes of mental character; degeneration and regeneration; and the +genealogy and antiquity of man. + +58. ELECTRICITY + +By GisBERT KAPP, D.Eng., M.I.E.E., M.I.C.E., Professor of Electrical +Engineering in the University of Birmingham. (Illustrated.) Deals with +frictional and contact electricity; potential; electrification by mechanical +means; the electric current; the dynamics of electric currents; alternating +currents; the distribution of electricity, etc. + +IN PREPARATION + +CHEMISTRY. Py Prof. R. MELDOLA, F.R.S. + +THE MINERAL WORLD. By Sir T. H. HOLLAND, K.C.I. E., D.Sc. + +PLANT LII-'E. By Prof. J. B. FARMER, F.R.S. + +NERVES. By Prof. D. FRASER HARRIS, M.D., D.Sc. + +A STUDY OF SEX. By Prof. J. A. THOMSON and Prof. PATRICK GEDDES. + +THE GROWTH OF EUROPE. By Prof. GRKNVILLE COLE. + + + +Philosophy and "Religion + + + +ig's +:tate + + + +15. MOHAMMEDANISM + +By Prof. D. S. MARGOLIOUTH, M.A., D.Litt. "This generous shilling': +worth of wisdom. ... A delicate, humorous, and most responsible tractati +by an illuminative professor." Daily Mail. + +40. THE PROBLEMS OF PHILOSOPHY + +By the Hon. BERTRAND RUSSELL, F.R.S.: 'A book that the ' man in the +street ' will recognise at once to be a boon. . . . Consistently lucid and non- +technical throughout." Christian World. + +47. BUDDHISM + + + +go. NONCONFORMITY: Its ORIGIN and PROGRESS + +I'.'- Principal W. B. SELBIE, M.A. "The historical part is brilliant in its +:., clarity, and proportion, and in the later chapters on the present position +.urns of Nonconformity Dr Selbie proves himself to be an ideal exponent +of sound and moderate views." Christian World. + +54. ETHICS + +By G. E. MOORE, M.A., Lecturer in Moral Science in Cambridge University. +Discusses Utilitarianism, the Objectivity of Moral Judgments, the Test of +Right and Wrong, Free Will, and Intrinsic Value. + +56. THE MAKING OF THE NEW TESTAMENT + +By Prof. B. W. BACON, LL. LX, D.D. An authoritative summary of the results +of modern critical research with regard to the origins of the New Testament, in +" the formative period when conscious inspiration was still in its full glow rather +than the period of collection into an official canon," showing the mingling of the +two great currents of Christian thought " Pauline and 'Apostolic,' the Greek- +Christian gospel about Jesus, and the Jewish-Christian gospel of Jesus, the +gospel of the Spirit and the gospel of au thority." + +jo. MISSIONS: THEIR RISE and DEVELOPMENT + +By Mrs CREIGHTON. The beginning of modern missions after the Reforma- +tion and their growth are traced, and an account is given of their present +work, its extent and character. + +IN PREPARATION + +THE OLD TESTAMENT. By Prof. GEORGE MOORE, D.D., LL.D. +BETWEEN THE OLD AND NEW TESTAMENTS. By R. H. + +CHARLES, D.D. + +COMPARATIVE RELIGION. By Prof. J. ESTLIN CARPENTER, D.Litt. +A HISTOR Y of FREEDOM of THOUGHT. By Prof. J. B. BURY, LL.D. +A HISTORY OF PHILOSOPHY. By CLEMKNT WKBB, M.A. + + + +Social Science + + + +. PARLIAMENT + +Its History, Constitution, and Practice. By Sir COURTENAY P. ILBERT. +K.C.B., K.C.S.I., Clerk of the House of Commons. "The best book on the +history and practice of the House of Commons since Bagehot's 'Constitution.'" +Yorkshire Post. + +. THE STOCK EXCHANGE + +By F. W. HIRST, Editor of " The Economist." " To an unfinancial mind must +be a revelation. . . . The book is as clear, vigorous, and sane as Bagehot's ' Lom- +bard Street,' than which there is no higher compliment." Morning Leader + +. IRISH NATIONALITY + +By Mrs J. R. GREEN. " As glowing as it is learned. No book could be more +timely." Daily News. "A powerful study. . . . A magnificent demonstration +of the deserved vitality of the Gaelic spirit." Freeman s Journal. + +3. THE SOCIALIST MOVEMENT + +RAMSAY MACDONALD, M.T. "Admirably adapted for the purpose of +exposition." The Times. "Mr MacDonald is a very lucid exponent. . . . The +volume will be of great use in dispelling illusions about the tendencies of +Socialism in this country." The Nation. + +i. CONSERVATISM + +Jy Lord HUGH CECIL, M.A., M.P. "One of those great little books which +seldom appear more than once in a generation." Morning Post. + + + +1 6. THE SCIENCE OF WEALTH + +By J. A. HOUSON, M.A. "Mr J. A. Hobson holds an unique position among +living economists. . . . The text-book produced is altogether admirable. +Original, reasonable, and illuminating." The Nation. + +21. LIBERALISM + +By L. T. HOBHOUSE, M. A., Professor of Sociology in the University of London. +"A book of rare quality. . . . We have nothing but praise for the rapid and +masterly summaries of the arguments from first principles which form a large +part of this book." Westminster Gazette. + +24. THE EVOLUTION OF INDUSTRY + +ByD. H. MACGREGCR, M.A., Professor of Political Economy in the University +of Leeds. "A volume so dispassionate in terms may be read with profit by all +interested in the present state of unrest." Aberdeen Journal. + +26. AGRICULTURE + +By Prof. W. SOMERVILLE, F.L.S. " It makes the results of laboratory work +at the University accessible to the practical farmer." Athena-urn. + +30. ELEMENTS OF ENGLISH LA W + +By W. M. GELDART, M.A., B.C.L., Vinerian Professor of English Law at +Oxford. "Contains a very clear account of the elementary principles under- +lying the rules of English law; and we can recommend it to all who wish to +become acquainted with these elementary principles with a minimum of +trouble." Scots Law Times. + +38. THE SCHOOL + +An Introduction to the Study of Education. + +By J. J. FINDLAY, M.A., Ph.D., Professor of Education in Manchester +University. <: An amazingly comprehensive volume. . . . It is a remarkable +performance, distinguished in its crisp, striking phraseology as well as its +inclusiveness of subject-matter." Morning Post. + +-59. ELEMENTS OF POLITICAL ECONOMY + +By S. J. CHAPMAN, M.A., Professor of Political Economy in Manchester +University. A simple explanation, in the light of the latest economic thought, +of the working of demand and supply; the nature of monopoly; money and +international trade; the relation of wages, profit, interest, and rent; and the +effects of labour combination prefaced by a short sketch of economic study +since Adam Smith. + +IN PREPARATION + +THE CRIMINAL AND THE COMMUNITY. By Viscount ST. + +CYRES, M.A. + +COMMONSENSE IN LA W. By Prof. P. VINOGRADOFF, D.C.L. +THE CIVIL SERVICE. By GRAHAM WALLAS, M.A. +PRACTICAL IDEALISM. By MAURICE HEWLETT. +NEWSPAPERS. By G. BINNEY DIBBLEE. +ENGLISH VILLAGE LIFE. By E. N. BENNETT, M.A. +CO -PARTNERSHIP At\D PROFIT-SHARING. By ANEURIN + +WILLIAMS, J.P. + +THE SOCIAL SETTLEMENT. By JANE ADDAMS and R. A. WOODS. +GREA T INVENTIONS. By Prof. J. L. MYRES, M.A., F.S.A. +TOWN PLANNING. By RAYMOND UNWIN. +POLITICAL THOUGHT IN ENGLAND: From Bentham to J. S. + +Mill. By Prof. W. L. DAVIDSON. +POLITICAL THOUGHT IN ENGLAKD: From Herbert Spencer + +to To-day. By ERNEST BARKER, M.A. + +London: WimTMS^AND~NORGATE + +And of all Bookshops and Bookstalls. +%[** TN: End of catalog OCR text] +\fi +%%%%%%%%%%%%%%%%%%%%%%%%% GUTENBERG LICENSE %%%%%%%%%%%%%%%%%%%%%%%%%% +\PGLicense +\begin{PGtext} +End of the Project Gutenberg EBook of An Introduction to Mathematics, by +Alfred North Whitehead + +*** END OF THIS PROJECT GUTENBERG EBOOK AN INTRODUCTION TO MATHEMATICS *** + +***** This file should be named 41568-tex.tex or 41568-tex.zip ***** +This and all associated files of various formats will be found in: + http://www.gutenberg.org/4/1/5/6/41568/ + +Produced by Andrew D. Hwang. (This ebook was produced using +OCR text generously provided by the University of +California, Santa Barbara, through the Internet Archive.) + + +Updated editions will replace the previous one--the old editions +will be renamed. + +Creating the works from public domain print editions means that no +one owns a United States copyright in these works, so the Foundation +(and you!) can copy and distribute it in the United States without +permission and without paying copyright royalties. Special rules, +set forth in the General Terms of Use part of this license, apply to +copying and distributing Project Gutenberg-tm electronic works to +protect the PROJECT GUTENBERG-tm concept and trademark. Project +Gutenberg is a registered trademark, and may not be used if you +charge for the eBooks, unless you receive specific permission. If you +do not charge anything for copies of this eBook, complying with the +rules is very easy. You may use this eBook for nearly any purpose +such as creation of derivative works, reports, performances and +research. They may be modified and printed and given away--you may do +practically ANYTHING with public domain eBooks. Redistribution is +subject to the trademark license, especially commercial +redistribution. + + + +*** START: FULL LICENSE *** + +THE FULL PROJECT GUTENBERG LICENSE +PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK + +To protect the Project Gutenberg-tm mission of promoting the free +distribution of electronic works, by using or distributing this work +(or any other work associated in any way with the phrase "Project +Gutenberg"), you agree to comply with all the terms of the Full Project +Gutenberg-tm License available with this file or online at + www.gutenberg.org/license. + + +Section 1. General Terms of Use and Redistributing Project Gutenberg-tm +electronic works + +1.A. By reading or using any part of this Project Gutenberg-tm +electronic work, you indicate that you have read, understand, agree to +and accept all the terms of this license and intellectual property +(trademark/copyright) agreement. If you do not agree to abide by all +the terms of this agreement, you must cease using and return or destroy +all copies of Project Gutenberg-tm electronic works in your possession. +If you paid a fee for obtaining a copy of or access to a Project +Gutenberg-tm electronic work and you do not agree to be bound by the +terms of this agreement, you may obtain a refund from the person or +entity to whom you paid the fee as set forth in paragraph 1.E.8. + +1.B. "Project Gutenberg" is a registered trademark. It may only be +used on or associated in any way with an electronic work by people who +agree to be bound by the terms of this agreement. There are a few +things that you can do with most Project Gutenberg-tm electronic works +even without complying with the full terms of this agreement. See +paragraph 1.C below. There are a lot of things you can do with Project +Gutenberg-tm electronic works if you follow the terms of this agreement +and help preserve free future access to Project Gutenberg-tm electronic +works. See paragraph 1.E below. + +1.C. The Project Gutenberg Literary Archive Foundation ("the Foundation" +or PGLAF), owns a compilation copyright in the collection of Project +Gutenberg-tm electronic works. Nearly all the individual works in the +collection are in the public domain in the United States. If an +individual work is in the public domain in the United States and you are +located in the United States, we do not claim a right to prevent you from +copying, distributing, performing, displaying or creating derivative +works based on the work as long as all references to Project Gutenberg +are removed. Of course, we hope that you will support the Project +Gutenberg-tm mission of promoting free access to electronic works by +freely sharing Project Gutenberg-tm works in compliance with the terms of +this agreement for keeping the Project Gutenberg-tm name associated with +the work. You can easily comply with the terms of this agreement by +keeping this work in the same format with its attached full Project +Gutenberg-tm License when you share it without charge with others. + +1.D. The copyright laws of the place where you are located also govern +what you can do with this work. Copyright laws in most countries are in +a constant state of change. If you are outside the United States, check +the laws of your country in addition to the terms of this agreement +before downloading, copying, displaying, performing, distributing or +creating derivative works based on this work or any other Project +Gutenberg-tm work. The Foundation makes no representations concerning +the copyright status of any work in any country outside the United +States. + +1.E. Unless you have removed all references to Project Gutenberg: + +1.E.1. The following sentence, with active links to, or other immediate +access to, the full Project Gutenberg-tm License must appear prominently +whenever any copy of a Project Gutenberg-tm work (any work on which the +phrase "Project Gutenberg" appears, or with which the phrase "Project +Gutenberg" is associated) is accessed, displayed, performed, viewed, +copied or distributed: + +This eBook is for the use of anyone anywhere at no cost and with +almost no restrictions whatsoever. You may copy it, give it away or +re-use it under the terms of the Project Gutenberg License included +with this eBook or online at www.gutenberg.org + +1.E.2. If an individual Project Gutenberg-tm electronic work is derived +from the public domain (does not contain a notice indicating that it is +posted with permission of the copyright holder), the work can be copied +and distributed to anyone in the United States without paying any fees +or charges. If you are redistributing or providing access to a work +with the phrase "Project Gutenberg" associated with or appearing on the +work, you must comply either with the requirements of paragraphs 1.E.1 +through 1.E.7 or obtain permission for the use of the work and the +Project Gutenberg-tm trademark as set forth in paragraphs 1.E.8 or +1.E.9. + +1.E.3. If an individual Project Gutenberg-tm electronic work is posted +with the permission of the copyright holder, your use and distribution +must comply with both paragraphs 1.E.1 through 1.E.7 and any additional +terms imposed by the copyright holder. Additional terms will be linked +to the Project Gutenberg-tm License for all works posted with the +permission of the copyright holder found at the beginning of this work. + +1.E.4. Do not unlink or detach or remove the full Project Gutenberg-tm +License terms from this work, or any files containing a part of this +work or any other work associated with Project Gutenberg-tm. + +1.E.5. Do not copy, display, perform, distribute or redistribute this +electronic work, or any part of this electronic work, without +prominently displaying the sentence set forth in paragraph 1.E.1 with +active links or immediate access to the full terms of the Project +Gutenberg-tm License. + +1.E.6. You may convert to and distribute this work in any binary, +compressed, marked up, nonproprietary or proprietary form, including any +word processing or hypertext form. However, if you provide access to or +distribute copies of a Project Gutenberg-tm work in a format other than +"Plain Vanilla ASCII" or other format used in the official version +posted on the official Project Gutenberg-tm web site (www.gutenberg.org), +you must, at no additional cost, fee or expense to the user, provide a +copy, a means of exporting a copy, or a means of obtaining a copy upon +request, of the work in its original "Plain Vanilla ASCII" or other +form. Any alternate format must include the full Project Gutenberg-tm +License as specified in paragraph 1.E.1. + +1.E.7. Do not charge a fee for access to, viewing, displaying, +performing, copying or distributing any Project Gutenberg-tm works +unless you comply with paragraph 1.E.8 or 1.E.9. + +1.E.8. You may charge a reasonable fee for copies of or providing +access to or distributing Project Gutenberg-tm electronic works provided +that + +- You pay a royalty fee of 20% of the gross profits you derive from + the use of Project Gutenberg-tm works calculated using the method + you already use to calculate your applicable taxes. The fee is + owed to the owner of the Project Gutenberg-tm trademark, but he + has agreed to donate royalties under this paragraph to the + Project Gutenberg Literary Archive Foundation. Royalty payments + must be paid within 60 days following each date on which you + prepare (or are legally required to prepare) your periodic tax + returns. Royalty payments should be clearly marked as such and + sent to the Project Gutenberg Literary Archive Foundation at the + address specified in Section 4, "Information about donations to + the Project Gutenberg Literary Archive Foundation." + +- You provide a full refund of any money paid by a user who notifies + you in writing (or by e-mail) within 30 days of receipt that s/he + does not agree to the terms of the full Project Gutenberg-tm + License. You must require such a user to return or + destroy all copies of the works possessed in a physical medium + and discontinue all use of and all access to other copies of + Project Gutenberg-tm works. + +- You provide, in accordance with paragraph 1.F.3, a full refund of any + money paid for a work or a replacement copy, if a defect in the + electronic work is discovered and reported to you within 90 days + of receipt of the work. + +- You comply with all other terms of this agreement for free + distribution of Project Gutenberg-tm works. + +1.E.9. If you wish to charge a fee or distribute a Project Gutenberg-tm +electronic work or group of works on different terms than are set +forth in this agreement, you must obtain permission in writing from +both the Project Gutenberg Literary Archive Foundation and Michael +Hart, the owner of the Project Gutenberg-tm trademark. Contact the +Foundation as set forth in Section 3 below. + +1.F. + +1.F.1. Project Gutenberg volunteers and employees expend considerable +effort to identify, do copyright research on, transcribe and proofread +public domain works in creating the Project Gutenberg-tm +collection. Despite these efforts, Project Gutenberg-tm electronic +works, and the medium on which they may be stored, may contain +"Defects," such as, but not limited to, incomplete, inaccurate or +corrupt data, transcription errors, a copyright or other intellectual +property infringement, a defective or damaged disk or other medium, a +computer virus, or computer codes that damage or cannot be read by +your equipment. + +1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the "Right +of Replacement or Refund" described in paragraph 1.F.3, the Project +Gutenberg Literary Archive Foundation, the owner of the Project +Gutenberg-tm trademark, and any other party distributing a Project +Gutenberg-tm electronic work under this agreement, disclaim all +liability to you for damages, costs and expenses, including legal +fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT +LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE +PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE +TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE +LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR +INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH +DAMAGE. + +1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a +defect in this electronic work within 90 days of receiving it, you can +receive a refund of the money (if any) you paid for it by sending a +written explanation to the person you received the work from. If you +received the work on a physical medium, you must return the medium with +your written explanation. The person or entity that provided you with +the defective work may elect to provide a replacement copy in lieu of a +refund. If you received the work electronically, the person or entity +providing it to you may choose to give you a second opportunity to +receive the work electronically in lieu of a refund. If the second copy +is also defective, you may demand a refund in writing without further +opportunities to fix the problem. + +1.F.4. Except for the limited right of replacement or refund set forth +in paragraph 1.F.3, this work is provided to you 'AS-IS', WITH NO OTHER +WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE. + +1.F.5. Some states do not allow disclaimers of certain implied +warranties or the exclusion or limitation of certain types of damages. +If any disclaimer or limitation set forth in this agreement violates the +law of the state applicable to this agreement, the agreement shall be +interpreted to make the maximum disclaimer or limitation permitted by +the applicable state law. The invalidity or unenforceability of any +provision of this agreement shall not void the remaining provisions. + +1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the +trademark owner, any agent or employee of the Foundation, anyone +providing copies of Project Gutenberg-tm electronic works in accordance +with this agreement, and any volunteers associated with the production, +promotion and distribution of Project Gutenberg-tm electronic works, +harmless from all liability, costs and expenses, including legal fees, +that arise directly or indirectly from any of the following which you do +or cause to occur: (a) distribution of this or any Project Gutenberg-tm +work, (b) alteration, modification, or additions or deletions to any +Project Gutenberg-tm work, and (c) any Defect you cause. + + +Section 2. Information about the Mission of Project Gutenberg-tm + +Project Gutenberg-tm is synonymous with the free distribution of +electronic works in formats readable by the widest variety of computers +including obsolete, old, middle-aged and new computers. It exists +because of the efforts of hundreds of volunteers and donations from +people in all walks of life. + +Volunteers and financial support to provide volunteers with the +assistance they need are critical to reaching Project Gutenberg-tm's +goals and ensuring that the Project Gutenberg-tm collection will +remain freely available for generations to come. In 2001, the Project +Gutenberg Literary Archive Foundation was created to provide a secure +and permanent future for Project Gutenberg-tm and future generations. +To learn more about the Project Gutenberg Literary Archive Foundation +and how your efforts and donations can help, see Sections 3 and 4 +and the Foundation information page at www.gutenberg.org + + +Section 3. Information about the Project Gutenberg Literary Archive +Foundation + +The Project Gutenberg Literary Archive Foundation is a non profit +501(c)(3) educational corporation organized under the laws of the +state of Mississippi and granted tax exempt status by the Internal +Revenue Service. The Foundation's EIN or federal tax identification +number is 64-6221541. Contributions to the Project Gutenberg +Literary Archive Foundation are tax deductible to the full extent +permitted by U.S. federal laws and your state's laws. + +The Foundation's principal office is located at 4557 Melan Dr. S. +Fairbanks, AK, 99712., but its volunteers and employees are scattered +throughout numerous locations. Its business office is located at 809 +North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email +contact links and up to date contact information can be found at the +Foundation's web site and official page at www.gutenberg.org/contact + +For additional contact information: + Dr. Gregory B. Newby + Chief Executive and Director + gbnewby@pglaf.org + +Section 4. Information about Donations to the Project Gutenberg +Literary Archive Foundation + +Project Gutenberg-tm depends upon and cannot survive without wide +spread public support and donations to carry out its mission of +increasing the number of public domain and licensed works that can be +freely distributed in machine readable form accessible by the widest +array of equipment including outdated equipment. Many small donations +($1 to $5,000) are particularly important to maintaining tax exempt +status with the IRS. + +The Foundation is committed to complying with the laws regulating +charities and charitable donations in all 50 states of the United +States. Compliance requirements are not uniform and it takes a +considerable effort, much paperwork and many fees to meet and keep up +with these requirements. We do not solicit donations in locations +where we have not received written confirmation of compliance. To +SEND DONATIONS or determine the status of compliance for any +particular state visit www.gutenberg.org/donate + +While we cannot and do not solicit contributions from states where we +have not met the solicitation requirements, we know of no prohibition +against accepting unsolicited donations from donors in such states who +approach us with offers to donate. + +International donations are gratefully accepted, but we cannot make +any statements concerning tax treatment of donations received from +outside the United States. U.S. laws alone swamp our small staff. + +Please check the Project Gutenberg Web pages for current donation +methods and addresses. Donations are accepted in a number of other +ways including checks, online payments and credit card donations. +To donate, please visit: www.gutenberg.org/donate + + +Section 5. General Information About Project Gutenberg-tm electronic +works. + +Professor Michael S. Hart was the originator of the Project Gutenberg-tm +concept of a library of electronic works that could be freely shared +with anyone. For forty years, he produced and distributed Project +Gutenberg-tm eBooks with only a loose network of volunteer support. + +Project Gutenberg-tm eBooks are often created from several printed +editions, all of which are confirmed as Public Domain in the U.S. +unless a copyright notice is included. Thus, we do not necessarily +keep eBooks in compliance with any particular paper edition. + +Most people start at our Web site which has the main PG search facility: + + www.gutenberg.org + +This Web site includes information about Project Gutenberg-tm, +including how to make donations to the Project Gutenberg Literary +Archive Foundation, how to help produce our new eBooks, and how to +subscribe to our email newsletter to hear about new eBooks. +\end{PGtext} + +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % +% % +% End of the Project Gutenberg EBook of An Introduction to Mathematics, by +% Alfred North Whitehead % +% % +% *** END OF THIS PROJECT GUTENBERG EBOOK AN INTRODUCTION TO MATHEMATICS *** +% % +% ***** This file should be named 41568-tex.tex or 41568-tex.zip ***** % +% This and all associated files of various formats will be found in: % +% http://www.gutenberg.org/4/1/5/6/41568/ % +% % +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % + +\end{document} +### +@ControlwordReplace = ( + ['\\AD', 'A.D.'], + ['\\BC', 'B.C.'], + ['\\cf', 'cf.'], + ['\\Cf', 'Cf.'], + ['\\eg', 'e.g.'], + ['\\ie', 'i.e.'], + ['\\viz', 'viz.'] + ); + +@ControlwordArguments = ( + ['\\Diagram', 1, 0, '', ''], + ['\\Figure', 0, 0, '', '', 1, 0, '', ''], + ['\\ToCLine', 1, 1, '', ' ', 1, 1, '', '', 1, 0, '', ''], + ['\\BookMark', 1, 0, '', '', 1, 0, '', ''], + ['\\First', 1, 1, '', ''], + ['\\Chapter', 0, 0, '', '', 1, 1, 'Chapter ', '. ', 1, 1, '', ''], + ['\\ChapRef', 0, 0, '', '', 1, 1, 'Chapter ', ''], + ['\\Appendix', 0, 0, '', '', 1, 1, '', ''], + ['\\Note', 1, 1, '', ''], + ['\\Fig', 0, 0, '', '', 1, 1, 'Fig. ', ''], + ['\\FigNum', 1, 1, '', ''], + ['\\Pagelabel', 1, 0, '', ''], + ['\\Pageref', 0, 0, '', '', 1, 0, 'p. ', '00'], + ['\\Eq', 0, 0, '', '', 1, 1, '', ''], + ['\\Typo', 1, 0, '', '', 1, 1, '', ''], + ['\\Add', 1, 1, '', ''], + ['\\Chg', 1, 0, '', '', 1, 1, '', ''] + ); +$PageSeparator = qr/^\\PageSep/; +$CustomClean = 'print "\\nCustom cleaning in progress..."; +my $cline = 0; + while ($cline <= $#file) { + $file[$cline] =~ s/--------[^\n]*\n//; # strip page separators + $cline++ + } + print "done\\n";'; +### +This is pdfTeX, Version 3.1415926-1.40.10 (TeX Live 2009/Debian) (format=pdflatex 2012.9.24) 6 DEC 2012 09:22 +entering extended mode + %&-line parsing enabled. +**41568-t.tex +(./41568-t.tex +LaTeX2e <2009/09/24> +Babel and hyphenation patterns for english, usenglishmax, dumylang, noh +yphenation, farsi, arabic, croatian, bulgarian, ukrainian, russian, czech, slov +ak, danish, dutch, finnish, french, basque, ngerman, german, german-x-2009-06-1 +9, ngerman-x-2009-06-19, ibycus, monogreek, greek, ancientgreek, hungarian, san +skrit, italian, latin, latvian, lithuanian, mongolian2a, mongolian, bokmal, nyn +orsk, romanian, irish, coptic, serbian, turkish, welsh, esperanto, uppersorbian +, estonian, indonesian, interlingua, icelandic, kurmanji, slovenian, polish, po +rtuguese, spanish, galician, catalan, swedish, ukenglish, pinyin, loaded. +(/usr/share/texmf-texlive/tex/latex/base/book.cls +Document Class: book 2007/10/19 v1.4h Standard LaTeX document class +(/usr/share/texmf-texlive/tex/latex/base/leqno.clo +File: leqno.clo 1998/08/17 v1.1c Standard LaTeX option (left equation numbers) +) (/usr/share/texmf-texlive/tex/latex/base/bk12.clo +File: bk12.clo 2007/10/19 v1.4h Standard LaTeX file (size option) +) +\c@part=\count79 +\c@chapter=\count80 +\c@section=\count81 +\c@subsection=\count82 +\c@subsubsection=\count83 +\c@paragraph=\count84 +\c@subparagraph=\count85 +\c@figure=\count86 +\c@table=\count87 +\abovecaptionskip=\skip41 +\belowcaptionskip=\skip42 +\bibindent=\dimen102 +) (/usr/share/texmf-texlive/tex/latex/base/inputenc.sty +Package: inputenc 2008/03/30 v1.1d Input encoding file +\inpenc@prehook=\toks14 +\inpenc@posthook=\toks15 +(/usr/share/texmf-texlive/tex/latex/base/latin1.def +File: latin1.def 2008/03/30 v1.1d Input encoding file +)) (/usr/share/texmf-texlive/tex/latex/base/ifthen.sty +Package: ifthen 2001/05/26 v1.1c Standard LaTeX ifthen package (DPC) +) (/usr/share/texmf-texlive/tex/latex/amsmath/amsmath.sty +Package: amsmath 2000/07/18 v2.13 AMS math features +\@mathmargin=\skip43 +For additional information on amsmath, use the `?' option. +(/usr/share/texmf-texlive/tex/latex/amsmath/amstext.sty +Package: amstext 2000/06/29 v2.01 +(/usr/share/texmf-texlive/tex/latex/amsmath/amsgen.sty +File: amsgen.sty 1999/11/30 v2.0 +\@emptytoks=\toks16 +\ex@=\dimen103 +)) (/usr/share/texmf-texlive/tex/latex/amsmath/amsbsy.sty +Package: amsbsy 1999/11/29 v1.2d +\pmbraise@=\dimen104 +) (/usr/share/texmf-texlive/tex/latex/amsmath/amsopn.sty +Package: amsopn 1999/12/14 v2.01 operator names +) +\inf@bad=\count88 +LaTeX Info: Redefining \frac on input line 211. +\uproot@=\count89 +\leftroot@=\count90 +LaTeX Info: Redefining \overline on input line 307. +\classnum@=\count91 +\DOTSCASE@=\count92 +LaTeX Info: Redefining \ldots on input line 379. +LaTeX Info: Redefining \dots on input line 382. +LaTeX Info: Redefining \cdots on input line 467. +\Mathstrutbox@=\box26 +\strutbox@=\box27 +\big@size=\dimen105 +LaTeX Font Info: Redeclaring font encoding OML on input line 567. +LaTeX Font Info: Redeclaring font encoding OMS on input line 568. +\macc@depth=\count93 +\c@MaxMatrixCols=\count94 +\dotsspace@=\muskip10 +\c@parentequation=\count95 +\dspbrk@lvl=\count96 +\tag@help=\toks17 +\row@=\count97 +\column@=\count98 +\maxfields@=\count99 +\andhelp@=\toks18 +\eqnshift@=\dimen106 +\alignsep@=\dimen107 +\tagshift@=\dimen108 +\tagwidth@=\dimen109 +\totwidth@=\dimen110 +\lineht@=\dimen111 +\@envbody=\toks19 +\multlinegap=\skip44 +\multlinetaggap=\skip45 +\mathdisplay@stack=\toks20 +LaTeX Info: Redefining \[ on input line 2666. +LaTeX Info: Redefining \] on input line 2667. +) (/usr/share/texmf-texlive/tex/latex/amsfonts/amssymb.sty +Package: amssymb 2009/06/22 v3.00 +(/usr/share/texmf-texlive/tex/latex/amsfonts/amsfonts.sty +Package: amsfonts 2009/06/22 v3.00 Basic AMSFonts support +\symAMSa=\mathgroup4 +\symAMSb=\mathgroup5 +LaTeX Font Info: Overwriting math alphabet `\mathfrak' in version `bold' +(Font) U/euf/m/n --> U/euf/b/n on input line 96. +)) (/usr/share/texmf-texlive/tex/latex/base/alltt.sty +Package: alltt 1997/06/16 v2.0g defines alltt environment +) (/usr/share/texmf-texlive/tex/latex/tools/indentfirst.sty +Package: indentfirst 1995/11/23 v1.03 Indent first paragraph (DPC) +) (/usr/share/texmf-texlive/tex/latex/footmisc/footmisc.sty +Package: footmisc 2009/09/15 v5.5a a miscellany of footnote facilities +\FN@temptoken=\toks21 +\footnotemargin=\dimen112 +\c@pp@next@reset=\count100 +\c@@fnserial=\count101 +Package footmisc Info: Declaring symbol style bringhurst on input line 855. +Package footmisc Info: Declaring symbol style chicago on input line 863. +Package footmisc Info: Declaring symbol style wiley on input line 872. +Package footmisc Info: Declaring symbol style lamport-robust on input line 883. + +Package footmisc Info: Declaring symbol style lamport* on input line 903. +Package footmisc Info: Declaring symbol style lamport*-robust on input line 924 +. +) (/usr/share/texmf-texlive/tex/latex/tools/multicol.sty +Package: multicol 2008/12/05 v1.6h multicolumn formatting (FMi) +\c@tracingmulticols=\count102 +\mult@box=\box28 +\multicol@leftmargin=\dimen113 +\c@unbalance=\count103 +\c@collectmore=\count104 +\doublecol@number=\count105 +\multicoltolerance=\count106 +\multicolpretolerance=\count107 +\full@width=\dimen114 +\page@free=\dimen115 +\premulticols=\dimen116 +\postmulticols=\dimen117 +\multicolsep=\skip46 +\multicolbaselineskip=\skip47 +\partial@page=\box29 +\last@line=\box30 +\mult@rightbox=\box31 +\mult@grightbox=\box32 +\mult@gfirstbox=\box33 +\mult@firstbox=\box34 +\@tempa=\box35 +\@tempa=\box36 +\@tempa=\box37 +\@tempa=\box38 +\@tempa=\box39 +\@tempa=\box40 +\@tempa=\box41 +\@tempa=\box42 +\@tempa=\box43 +\@tempa=\box44 +\@tempa=\box45 +\@tempa=\box46 +\@tempa=\box47 +\@tempa=\box48 +\@tempa=\box49 +\@tempa=\box50 +\@tempa=\box51 +\c@columnbadness=\count108 +\c@finalcolumnbadness=\count109 +\last@try=\dimen118 +\multicolovershoot=\dimen119 +\multicolundershoot=\dimen120 +\mult@nat@firstbox=\box52 +\colbreak@box=\box53 +) (/usr/share/texmf-texlive/tex/latex/base/makeidx.sty +Package: makeidx 2000/03/29 v1.0m Standard LaTeX package +) (/usr/share/texmf-texlive/tex/latex/graphics/graphicx.sty +Package: graphicx 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR) +(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty +Package: keyval 1999/03/16 v1.13 key=value parser (DPC) +\KV@toks@=\toks22 +) (/usr/share/texmf-texlive/tex/latex/graphics/graphics.sty +Package: graphics 2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR) +(/usr/share/texmf-texlive/tex/latex/graphics/trig.sty +Package: trig 1999/03/16 v1.09 sin cos tan (DPC) +) (/etc/texmf/tex/latex/config/graphics.cfg +File: graphics.cfg 2009/08/28 v1.8 graphics configuration of TeX Live +) +Package graphics Info: Driver file: pdftex.def on input line 91. +(/usr/share/texmf-texlive/tex/latex/pdftex-def/pdftex.def +File: pdftex.def 2009/08/25 v0.04m Graphics/color for pdfTeX +\Gread@gobject=\count110 +)) +\Gin@req@height=\dimen121 +\Gin@req@width=\dimen122 +) (/usr/share/texmf-texlive/tex/latex/caption/caption.sty +Package: caption 2009/10/09 v3.1k Customizing captions (AR) +(/usr/share/texmf-texlive/tex/latex/caption/caption3.sty +Package: caption3 2009/10/09 v3.1k caption3 kernel (AR) +\captionmargin=\dimen123 +\captionmargin@=\dimen124 +\captionwidth=\dimen125 +\caption@indent=\dimen126 +\caption@parindent=\dimen127 +\caption@hangindent=\dimen128 +) +\c@ContinuedFloat=\count111 +) (/usr/share/texmf-texlive/tex/latex/tools/calc.sty +Package: calc 2007/08/22 v4.3 Infix arithmetic (KKT,FJ) +\calc@Acount=\count112 +\calc@Bcount=\count113 +\calc@Adimen=\dimen129 +\calc@Bdimen=\dimen130 +\calc@Askip=\skip48 +\calc@Bskip=\skip49 +LaTeX Info: Redefining \setlength on input line 76. +LaTeX Info: Redefining \addtolength on input line 77. +\calc@Ccount=\count114 +\calc@Cskip=\skip50 +) (/usr/share/texmf-texlive/tex/latex/fancyhdr/fancyhdr.sty +\fancy@headwidth=\skip51 +\f@ncyO@elh=\skip52 +\f@ncyO@erh=\skip53 +\f@ncyO@olh=\skip54 +\f@ncyO@orh=\skip55 +\f@ncyO@elf=\skip56 +\f@ncyO@erf=\skip57 +\f@ncyO@olf=\skip58 +\f@ncyO@orf=\skip59 +) (/usr/share/texmf-texlive/tex/latex/geometry/geometry.sty +Package: geometry 2008/12/21 v4.2 Page Geometry +(/usr/share/texmf-texlive/tex/generic/oberdiek/ifpdf.sty +Package: ifpdf 2009/04/10 v2.0 Provides the ifpdf switch (HO) +Package ifpdf Info: pdfTeX in pdf mode detected. +) (/usr/share/texmf-texlive/tex/generic/oberdiek/ifvtex.sty +Package: ifvtex 2008/11/04 v1.4 Switches for detecting VTeX and its modes (HO) +Package ifvtex Info: VTeX not detected. +) +\Gm@cnth=\count115 +\Gm@cntv=\count116 +\c@Gm@tempcnt=\count117 +\Gm@bindingoffset=\dimen131 +\Gm@wd@mp=\dimen132 +\Gm@odd@mp=\dimen133 +\Gm@even@mp=\dimen134 +\Gm@dimlist=\toks23 +(/usr/share/texmf-texlive/tex/xelatex/xetexconfig/geometry.cfg)) (/usr/share/te +xmf-texlive/tex/latex/hyperref/hyperref.sty +Package: hyperref 2009/10/09 v6.79a Hypertext links for LaTeX +(/usr/share/texmf-texlive/tex/generic/ifxetex/ifxetex.sty +Package: ifxetex 2009/01/23 v0.5 Provides ifxetex conditional +) (/usr/share/texmf-texlive/tex/latex/oberdiek/hycolor.sty +Package: hycolor 2009/10/02 v1.5 Code for color options of hyperref/bookmark (H +O) +(/usr/share/texmf-texlive/tex/latex/oberdiek/xcolor-patch.sty +Package: xcolor-patch 2009/10/02 xcolor patch +)) +\@linkdim=\dimen135 +\Hy@linkcounter=\count118 +\Hy@pagecounter=\count119 +(/usr/share/texmf-texlive/tex/latex/hyperref/pd1enc.def +File: pd1enc.def 2009/10/09 v6.79a Hyperref: PDFDocEncoding definition (HO) +) (/usr/share/texmf-texlive/tex/generic/oberdiek/etexcmds.sty +Package: etexcmds 2007/12/12 v1.2 Prefix for e-TeX command names (HO) +(/usr/share/texmf-texlive/tex/generic/oberdiek/infwarerr.sty +Package: infwarerr 2007/09/09 v1.2 Providing info/warning/message (HO) +) +Package etexcmds Info: Could not find \expanded. +(etexcmds) That can mean that you are not using pdfTeX 1.50 or +(etexcmds) that some package has redefined \expanded. +(etexcmds) In the latter case, load this package earlier. +) (/etc/texmf/tex/latex/config/hyperref.cfg +File: hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive +) (/usr/share/texmf-texlive/tex/latex/oberdiek/kvoptions.sty +Package: kvoptions 2009/08/13 v3.4 Keyval support for LaTeX options (HO) +(/usr/share/texmf-texlive/tex/generic/oberdiek/kvsetkeys.sty +Package: kvsetkeys 2009/07/30 v1.5 Key value parser with default handler suppor +t (HO) +)) +Package hyperref Info: Option `hyperfootnotes' set `false' on input line 2864. +Package hyperref Info: Option `bookmarks' set `true' on input line 2864. +Package hyperref Info: Option `linktocpage' set `false' on input line 2864. +Package hyperref Info: Option `pdfdisplaydoctitle' set `true' on input line 286 +4. +Package hyperref Info: Option `pdfpagelabels' set `true' on input line 2864. +Package hyperref Info: Option `bookmarksopen' set `true' on input line 2864. +Package hyperref Info: Option `colorlinks' set `true' on input line 2864. +Package hyperref Info: Hyper figures OFF on input line 2975. +Package hyperref Info: Link nesting OFF on input line 2980. +Package hyperref Info: Hyper index ON on input line 2983. +Package hyperref Info: Plain pages OFF on input line 2990. +Package hyperref Info: Backreferencing OFF on input line 2995. +Implicit mode ON; LaTeX internals redefined +Package hyperref Info: Bookmarks ON on input line 3191. +(/usr/share/texmf-texlive/tex/latex/ltxmisc/url.sty +\Urlmuskip=\muskip11 +Package: url 2006/04/12 ver 3.3 Verb mode for urls, etc. +) +LaTeX Info: Redefining \url on input line 3428. +(/usr/share/texmf-texlive/tex/generic/oberdiek/bitset.sty +Package: bitset 2007/09/28 v1.0 Data type bit set (HO) +(/usr/share/texmf-texlive/tex/generic/oberdiek/intcalc.sty +Package: intcalc 2007/09/27 v1.1 Expandable integer calculations (HO) +) (/usr/share/texmf-texlive/tex/generic/oberdiek/bigintcalc.sty +Package: bigintcalc 2007/11/11 v1.1 Expandable big integer calculations (HO) +(/usr/share/texmf-texlive/tex/generic/oberdiek/pdftexcmds.sty +Package: pdftexcmds 2009/09/23 v0.6 LuaTeX support for pdfTeX utility functions + (HO) +(/usr/share/texmf-texlive/tex/generic/oberdiek/ifluatex.sty +Package: ifluatex 2009/04/17 v1.2 Provides the ifluatex switch (HO) +Package ifluatex Info: LuaTeX not detected. +) (/usr/share/texmf-texlive/tex/generic/oberdiek/ltxcmds.sty +Package: ltxcmds 2009/08/05 v1.0 Some LaTeX kernel commands for general use (HO +) +) +Package pdftexcmds Info: LuaTeX not detected. +Package pdftexcmds Info: \pdf@primitive is available. +Package pdftexcmds Info: \pdf@ifprimitive is available. +))) +\Fld@menulength=\count120 +\Field@Width=\dimen136 +\Fld@charsize=\dimen137 +\Field@toks=\toks24 +Package hyperref Info: Hyper figures OFF on input line 4377. +Package hyperref Info: Link nesting OFF on input line 4382. +Package hyperref Info: Hyper index ON on input line 4385. +Package hyperref Info: backreferencing OFF on input line 4392. +Package hyperref Info: Link coloring ON on input line 4395. +Package hyperref Info: Link coloring with OCG OFF on input line 4402. +Package hyperref Info: PDF/A mode OFF on input line 4407. +(/usr/share/texmf-texlive/tex/generic/oberdiek/atbegshi.sty +Package: atbegshi 2008/07/31 v1.9 At begin shipout hook (HO) +) +\Hy@abspage=\count121 +\c@Item=\count122 +) +*hyperref using driver hpdftex* +(/usr/share/texmf-texlive/tex/latex/hyperref/hpdftex.def +File: hpdftex.def 2009/10/09 v6.79a Hyperref driver for pdfTeX +\Fld@listcount=\count123 +) +\TmpLen=\skip60 +\@indexfile=\write3 +\openout3 = `41568-t.idx'. + +Writing index file 41568-t.idx +(./41568-t.aux) +\openout1 = `41568-t.aux'. + +LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 494. +LaTeX Font Info: ... okay on input line 494. +LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 494. +LaTeX Font Info: ... okay on input line 494. +LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 494. +LaTeX Font Info: ... okay on input line 494. +LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 494. +LaTeX Font Info: ... okay on input line 494. +LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 494. +LaTeX Font Info: ... okay on input line 494. +LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 494. +LaTeX Font Info: ... okay on input line 494. +LaTeX Font Info: Checking defaults for PD1/pdf/m/n on input line 494. +LaTeX Font Info: ... okay on input line 494. +(/usr/share/texmf/tex/context/base/supp-pdf.mkii +[Loading MPS to PDF converter (version 2006.09.02).] +\scratchcounter=\count124 +\scratchdimen=\dimen138 +\scratchbox=\box54 +\nofMPsegments=\count125 +\nofMParguments=\count126 +\everyMPshowfont=\toks25 +\MPscratchCnt=\count127 +\MPscratchDim=\dimen139 +\MPnumerator=\count128 +\everyMPtoPDFconversion=\toks26 +) +Package caption Info: Begin \AtBeginDocument code. +Package caption Info: hyperref package is loaded. +Package caption Info: End \AtBeginDocument code. +*geometry auto-detecting driver* +*geometry detected driver: pdftex* +-------------------- Geometry parameters +paper: class default +landscape: -- +twocolumn: -- +twoside: true +asymmetric: -- +h-parts: 9.03375pt, 307.14749pt, 9.03375pt +v-parts: 1.26749pt, 466.58623pt, 1.90128pt +hmarginratio: 1:1 +vmarginratio: 2:3 +lines: -- +heightrounded: -- +bindingoffset: 0.0pt +truedimen: -- +includehead: true +includefoot: true +includemp: -- +driver: pdftex +-------------------- Page layout dimensions and switches +\paperwidth 325.215pt +\paperheight 469.75499pt +\textwidth 307.14749pt +\textheight 404.71243pt +\oddsidemargin -63.23624pt +\evensidemargin -63.23624pt +\topmargin -71.0025pt +\headheight 12.0pt +\headsep 19.8738pt +\footskip 30.0pt +\marginparwidth 98.0pt +\marginparsep 7.0pt +\columnsep 10.0pt +\skip\footins 10.8pt plus 4.0pt minus 2.0pt +\hoffset 0.0pt +\voffset 0.0pt +\mag 1000 +\@twosidetrue \@mparswitchtrue +(1in=72.27pt, 1cm=28.45pt) +----------------------- +(/usr/share/texmf-texlive/tex/latex/graphics/color.sty +Package: color 2005/11/14 v1.0j Standard LaTeX Color (DPC) +(/etc/texmf/tex/latex/config/color.cfg +File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive +) +Package color Info: Driver file: pdftex.def on input line 130. +) +Package hyperref Info: Link coloring ON on input line 494. +(/usr/share/texmf-texlive/tex/latex/hyperref/nameref.sty +Package: nameref 2007/05/29 v2.31 Cross-referencing by name of section +(/usr/share/texmf-texlive/tex/latex/oberdiek/refcount.sty +Package: refcount 2008/08/11 v3.1 Data extraction from references (HO) +) +\c@section@level=\count129 +) +LaTeX Info: Redefining \ref on input line 494. +LaTeX Info: Redefining \pageref on input line 494. +(./41568-t.out) (./41568-t.out) +\@outlinefile=\write4 +\openout4 = `41568-t.out'. + +\AtBeginShipoutBox=\box55 + +Overfull \hbox (20.10721pt too wide) in paragraph at lines 501--501 +[]\OT1/cmtt/m/n/8 Project Gutenberg's An Introduction to Mathematics, by Alfred + North Whitehead[] + [] + + +Overfull \hbox (15.85715pt too wide) in paragraph at lines 519--519 +[]\OT1/cmtt/m/n/8 *** START OF THIS PROJECT GUTENBERG EBOOK AN INTRODUCTION TO +MATHEMATICS ***[] + [] + +LaTeX Font Info: Try loading font information for U+msa on input line 521. +(/usr/share/texmf-texlive/tex/latex/amsfonts/umsa.fd +File: umsa.fd 2009/06/22 v3.00 AMS symbols A +) +LaTeX Font Info: Try loading font information for U+msb on input line 521. +(/usr/share/texmf-texlive/tex/latex/amsfonts/umsb.fd +File: umsb.fd 2009/06/22 v3.00 AMS symbols B +) [1 + +{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}] [2] [1 + + +] [2 + +] [1 + + + +] [2] [3] [4] [5] [6] [7 + +] [8] [9] [10] <./images/fig1.pdf, id=236, 299.1175pt x 166.6225pt> +File: ./images/fig1.pdf Graphic file (type pdf) + [11 <./images/fig1.pdf>] <./images/fig2.pdf, id=255, 31 +1.1625pt x 166.6225pt> +File: ./images/fig2.pdf Graphic file (type pdf) + [12] [13 <./images/fig2.pdf>] [14] [15 + +] [16] [17] [18] [19] [20] [21] +LaTeX Font Info: Try loading font information for OMS+cmr on input line 1529 +. +(/usr/share/texmf-texlive/tex/latex/base/omscmr.fd +File: omscmr.fd 1999/05/25 v2.5h Standard LaTeX font definitions +) +LaTeX Font Info: Font shape `OMS/cmr/m/n' in size <8> not available +(Font) Font shape `OMS/cmsy/m/n' tried instead on input line 1529. + +LaTeX Font Info: Font shape `OMS/cmr/m/n' in size <7> not available +(Font) Font shape `OMS/cmsy/m/n' tried instead on input line 1531. + +[22] [23] [24] [25] <./images/fig3.pdf, id=327, 324.21124pt x 150.5625pt> +File: ./images/fig3.pdf Graphic file (type pdf) + [26] [27 <./images/fig3.pdf>] [28] [29 + +] [30] <./images/fig4.pdf, id=362, 150.5625pt x 128.48pt> +File: ./images/fig4.pdf Graphic file (type pdf) + <./images/fig5.pdf, id=364, 150.5625pt x 126.4725pt> +File: ./images/fig5.pdf Graphic file (type pdf) + [31] [32 <./images/fig4.pdf> <./images/fig5.pdf>] [33] +[34] [35] [36] <./images/fig6.pdf, id=405, 162.6075pt x 136.51pt> +File: ./images/fig6.pdf Graphic file (type pdf) + [37 <./images/fig6.pdf>] [38] [39] <./images/fig7.pdf, +id=428, 230.8625pt x 161.60374pt> +File: ./images/fig7.pdf Graphic file (type pdf) + [40] [41 <./images/fig7.pdf>] [42] [43 + +] [44] [45] [46] [47] [48] [49] [50] [51] [52] [53] [54 + +] <./images/pg76.pdf, id=515, 302.12875pt x 36.135pt> +File: ./images/pg76.pdf Graphic file (type pdf) + [55] [56 <./images/pg76.pdf>] [57] [58] [59] [60] [61] +[62] [63] <./images/pg86.pdf, id=567, 324.21124pt x 32.12pt> +File: ./images/pg86.pdf Graphic file (type pdf) + [64 <./images/pg86.pdf>] [65] [66] [67 + +] [68] [69] [70] <./images/fig8.pdf, id=617, 341.275pt x 230.8625pt> +File: ./images/fig8.pdf Graphic file (type pdf) + [71 <./images/fig8.pdf>] <./images/fig9.pdf, id=633, 33 +8.26375pt x 239.89626pt> +File: ./images/fig9.pdf Graphic file (type pdf) + [72] [73 <./images/fig9.pdf>] [74] [75] [76] <./images/ +fig10.pdf, id=672, 341.275pt x 236.885pt> +File: ./images/fig10.pdf Graphic file (type pdf) + [77 <./images/fig10.pdf>] [78] [79] [80 + +] [81] [82] [83] <./images/fig11.pdf, id=720, 319.1925pt x 166.6225pt> +File: ./images/fig11.pdf Graphic file (type pdf) + [84] [85 <./images/fig11.pdf>] <./images/fig12.pdf, id +=742, 250.9375pt x 199.74625pt> +File: ./images/fig12.pdf Graphic file (type pdf) + [86 <./images/fig12.pdf>] [87] [88] [89] <./images/fig +13.pdf, id=768, 319.1925pt x 274.02374pt> +File: ./images/fig13.pdf Graphic file (type pdf) + [90 + +] [91 <./images/fig13.pdf>] [92] [93] [94] [95] [96] [97] [98] <./images/fig14. +pdf, id=819, 319.1925pt x 279.0425pt> +File: ./images/fig14.pdf Graphic file (type pdf) + [99] [100 <./images/fig14.pdf>] [101] [102] [103 + +] [104] <./images/fig15.pdf, id=864, 337.26pt x 357.335pt> +File: ./images/fig15.pdf Graphic file (type pdf) + [105] <./images/fig16.pdf, id=870, 290.08376pt x 156.5 +85pt> +File: ./images/fig16.pdf Graphic file (type pdf) + <./images/fig17.pdf, id=871, 199.74625pt x 186.6975pt> +File: ./images/fig17.pdf Graphic file (type pdf) + <./images/fig18.pdf, id=875, 351.3125pt x 257.96375pt> +File: ./images/fig18.pdf Graphic file (type pdf) + [106 <./images/fig15.pdf>] [107 <./images/fig16.pdf>] +[108 <./images/fig17.pdf>] [109 <./images/fig18.pdf>] [110] [111] [112] <./imag +es/fig19.pdf, id=959, 178.6675pt x 131.49126pt> +File: ./images/fig19.pdf Graphic file (type pdf) + [113] [114 <./images/fig19.pdf>] [115] [116] [117] [11 +8 + +] [119] [120] <./images/fig20.pdf, id=1007, 275.0275pt x 120.45pt> +File: ./images/fig20.pdf Graphic file (type pdf) + [121 <./images/fig20.pdf>] [122] [123] <./images/fig21 +.pdf, id=1039, 305.14pt x 230.8625pt> +File: ./images/fig21.pdf Graphic file (type pdf) + [124] [125 <./images/fig21.pdf>] [126] [127] [128] [12 +9] [130] [131] [132] [133] [134 + +] [135] [136] [137] [138] [139] [140] [141 + +] <./images/fig22.pdf, id=1139, 163.61125pt x 135.50626pt> +File: ./images/fig22.pdf Graphic file (type pdf) + <./images/fig23.pdf, id=1140, 145.54375pt x 92.345pt> +File: ./images/fig23.pdf Graphic file (type pdf) + [142] [143 <./images/fig22.pdf>] <./images/fig24.pdf, +id=1156, 348.30125pt x 143.53625pt> +File: ./images/fig24.pdf Graphic file (type pdf) + <./images/fig25.pdf, id=1157, 202.7575pt x 126.4725pt> +File: ./images/fig25.pdf Graphic file (type pdf) + <./images/fig26.pdf, id=1160, 309.155pt x 265.99374pt> +File: ./images/fig26.pdf Graphic file (type pdf) + [144 <./images/fig23.pdf>] [145 <./images/fig24.pdf>] +[146 <./images/fig25.pdf>] [147] [148 <./images/fig26.pdf>] [149] <./images/fig +27.pdf, id=1226, 351.3125pt x 291.0875pt> +File: ./images/fig27.pdf Graphic file (type pdf) + [150] [151] [152 <./images/fig27.pdf>] [153] [154] <./ +images/fig28.pdf, id=1267, 298.11375pt x 69.25874pt> +File: ./images/fig28.pdf Graphic file (type pdf) + [155 <./images/fig28.pdf>] [156] [157] [158] [159 + +] [160] [161] [162] [163] [164] [165] [166] +Overfull \hbox (0.85368pt too wide) in paragraph at lines 6806--6814 +[]\OT1/cmr/m/n/12 It is tempt-ing to sup-pose that the con-di-tion for $\OML/cm +m/m/it/12 u[]$\OT1/cmr/m/n/12 , $\OML/cmm/m/it/12 u[]$\OT1/cmr/m/n/12 , ..., + [] + +[167] [168] [169] [170] [171] [172] +Underfull \hbox (badness 1565) in paragraph at lines 7074--7079 +[]\OT1/cmr/m/n/12 The crit-i-cal points, where non-uniform con-ver-gence + [] + +[173] [174] <./images/fig29.pdf, id=1377, 341.275pt x 183.68625pt> +File: ./images/fig29.pdf Graphic file (type pdf) + [175] <./images/fig30.pdf, id=1385, 305.14pt x 129.483 +75pt> +File: ./images/fig30.pdf Graphic file (type pdf) + [176 <./images/fig29.pdf>] <./images/fig31.pdf, id=140 +0, 293.095pt x 149.55875pt> +File: ./images/fig31.pdf Graphic file (type pdf) + [177 <./images/fig30.pdf>] [178 <./images/fig31.pdf>] +[179 + +] [180] [181] <./images/fig32.pdf, id=1442, 309.155pt x 166.6225pt> +File: ./images/fig32.pdf Graphic file (type pdf) + [182 <./images/fig32.pdf>] [183] [184] [185] [186] [18 +7] [188] [189] [190] [191] [192] [193] <./images/fig33.pdf, id=1514, 339.2675pt + x 114.4275pt> +File: ./images/fig33.pdf Graphic file (type pdf) + [194 + +] [195 <./images/fig33.pdf>] [196] [197] [198] [199] [200] [201] [202 + +] [203] [204] [205] [206] [207 + + + +] [208] [209 + +] [210] (./41568-t.ind [211] [212 + +] [213] [214] [215]) +Overfull \hbox (7.35703pt too wide) in paragraph at lines 9490--9490 +[]\OT1/cmtt/m/n/8 *** END OF THIS PROJECT GUTENBERG EBOOK AN INTRODUCTION TO MA +THEMATICS ***[] + [] + +[1 + + +] +Overfull \hbox (3.10696pt too wide) in paragraph at lines 9560--9560 +[]\OT1/cmtt/m/n/8 1.C. The Project Gutenberg Literary Archive Foundation ("the + Foundation"[] + [] + + +Overfull \hbox (3.10696pt too wide) in paragraph at lines 9565--9565 +[]\OT1/cmtt/m/n/8 located in the United States, we do not claim a right to prev +ent you from[] + [] + +[2] +Overfull \hbox (3.10696pt too wide) in paragraph at lines 9570--9570 +[]\OT1/cmtt/m/n/8 freely sharing Project Gutenberg-tm works in compliance with +the terms of[] + [] + +[3] +Overfull \hbox (3.10696pt too wide) in paragraph at lines 9633--9633 +[]\OT1/cmtt/m/n/8 posted on the official Project Gutenberg-tm web site (www.gut +enberg.org),[] + [] + +[4] [5] [6] [7] [8] [9] (./41568-t.aux) + + *File List* + book.cls 2007/10/19 v1.4h Standard LaTeX document class + leqno.clo 1998/08/17 v1.1c Standard LaTeX option (left equation numbers) + bk12.clo 2007/10/19 v1.4h Standard LaTeX file (size option) +inputenc.sty 2008/03/30 v1.1d Input encoding file + latin1.def 2008/03/30 v1.1d Input encoding file + ifthen.sty 2001/05/26 v1.1c Standard LaTeX ifthen package (DPC) + amsmath.sty 2000/07/18 v2.13 AMS math features + amstext.sty 2000/06/29 v2.01 + amsgen.sty 1999/11/30 v2.0 + amsbsy.sty 1999/11/29 v1.2d + amsopn.sty 1999/12/14 v2.01 operator names + amssymb.sty 2009/06/22 v3.00 +amsfonts.sty 2009/06/22 v3.00 Basic AMSFonts support + alltt.sty 1997/06/16 v2.0g defines alltt environment +indentfirst.sty 1995/11/23 v1.03 Indent first paragraph (DPC) +footmisc.sty 2009/09/15 v5.5a a miscellany of footnote facilities +multicol.sty 2008/12/05 v1.6h multicolumn formatting (FMi) + makeidx.sty 2000/03/29 v1.0m Standard LaTeX package +graphicx.sty 1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR) + keyval.sty 1999/03/16 v1.13 key=value parser (DPC) +graphics.sty 2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR) + trig.sty 1999/03/16 v1.09 sin cos tan (DPC) +graphics.cfg 2009/08/28 v1.8 graphics configuration of TeX Live + pdftex.def 2009/08/25 v0.04m Graphics/color for pdfTeX + caption.sty 2009/10/09 v3.1k Customizing captions (AR) +caption3.sty 2009/10/09 v3.1k caption3 kernel (AR) + calc.sty 2007/08/22 v4.3 Infix arithmetic (KKT,FJ) +fancyhdr.sty +geometry.sty 2008/12/21 v4.2 Page Geometry + ifpdf.sty 2009/04/10 v2.0 Provides the ifpdf switch (HO) + ifvtex.sty 2008/11/04 v1.4 Switches for detecting VTeX and its modes (HO) +geometry.cfg +hyperref.sty 2009/10/09 v6.79a Hypertext links for LaTeX + ifxetex.sty 2009/01/23 v0.5 Provides ifxetex conditional + hycolor.sty 2009/10/02 v1.5 Code for color options of hyperref/bookmark (HO +) +xcolor-patch.sty 2009/10/02 xcolor patch + pd1enc.def 2009/10/09 v6.79a Hyperref: PDFDocEncoding definition (HO) +etexcmds.sty 2007/12/12 v1.2 Prefix for e-TeX command names (HO) +infwarerr.sty 2007/09/09 v1.2 Providing info/warning/message (HO) +hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive +kvoptions.sty 2009/08/13 v3.4 Keyval support for LaTeX options (HO) +kvsetkeys.sty 2009/07/30 v1.5 Key value parser with default handler support +(HO) + url.sty 2006/04/12 ver 3.3 Verb mode for urls, etc. + bitset.sty 2007/09/28 v1.0 Data type bit set (HO) + intcalc.sty 2007/09/27 v1.1 Expandable integer calculations (HO) +bigintcalc.sty 2007/11/11 v1.1 Expandable big integer calculations (HO) +pdftexcmds.sty 2009/09/23 v0.6 LuaTeX support for pdfTeX utility functions ( +HO) +ifluatex.sty 2009/04/17 v1.2 Provides the ifluatex switch (HO) + ltxcmds.sty 2009/08/05 v1.0 Some LaTeX kernel commands for general use (HO) + +atbegshi.sty 2008/07/31 v1.9 At begin shipout hook (HO) + hpdftex.def 2009/10/09 v6.79a Hyperref driver for pdfTeX +supp-pdf.mkii + color.sty 2005/11/14 v1.0j Standard LaTeX Color (DPC) + color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive + nameref.sty 2007/05/29 v2.31 Cross-referencing by name of section +refcount.sty 2008/08/11 v3.1 Data extraction from references (HO) + 41568-t.out + 41568-t.out + umsa.fd 2009/06/22 v3.00 AMS symbols A + umsb.fd 2009/06/22 v3.00 AMS symbols B +./images/fig1.pdf +./images/fig2.pdf + omscmr.fd 1999/05/25 v2.5h Standard LaTeX font definitions +./images/fig3.pdf +./images/fig4.pdf +./images/fig5.pdf +./images/fig6.pdf +./images/fig7.pdf +./images/pg76.pdf +./images/pg86.pdf +./images/fig8.pdf +./images/fig9.pdf +./images/fig10.pdf +./images/fig11.pdf +./images/fig12.pdf +./images/fig13.pdf +./images/fig14.pdf +./images/fig15.pdf +./images/fig16.pdf +./images/fig17.pdf +./images/fig18.pdf +./images/fig19.pdf +./images/fig20.pdf +./images/fig21.pdf +./images/fig22.pdf +./images/fig23.pdf +./images/fig24.pdf +./images/fig25.pdf +./images/fig26.pdf +./images/fig27.pdf +./images/fig28.pdf +./images/fig29.pdf +./images/fig30.pdf +./images/fig31.pdf +./images/fig32.pdf +./images/fig33.pdf + 41568-t.ind + *********** + + ) +Here is how much of TeX's memory you used: + 7739 strings out of 493848 + 110834 string characters out of 1152823 + 197518 words of memory out of 3000000 + 10386 multiletter control sequences out of 15000+50000 + 16794 words of font info for 64 fonts, out of 3000000 for 9000 + 714 hyphenation exceptions out of 8191 + 37i,13n,44p,298b,544s stack positions out of 5000i,500n,10000p,200000b,50000s + + +Output written on 41568-t.pdf (228 pages, 1021150 bytes). +PDF statistics: + 2077 PDF objects out of 2487 (max. 8388607) + 462 named destinations out of 1000 (max. 500000) + 392 words of extra memory for PDF output out of 10000 (max. 10000000) + diff --git a/latex/math/apssamp_456d02.tex b/latex/math/apssamp_456d02.tex new file mode 100644 index 0000000..ae2eb52 --- /dev/null +++ b/latex/math/apssamp_456d02.tex @@ -0,0 +1,753 @@ +% ****** Start of file apssamp.tex ****** +% +% This file is part of the APS files in the REVTeX 4.2 distribution. +% Version 4.2a of REVTeX, December 2014 +% +% Copyright (c) 2014 The American Physical Society. +% +% See the REVTeX 4 README file for restrictions and more information. +% +% TeX'ing this file requires that you have AMS-LaTeX 2.0 installed +% as well as the rest of the prerequisites for REVTeX 4.2 +% +% See the REVTeX 4 README file +% It also requires running BibTeX. The commands are as follows: +% +% 1) latex apssamp.tex +% 2) bibtex apssamp +% 3) latex apssamp.tex +% 4) latex apssamp.tex +% +\documentclass[% + reprint, +%superscriptaddress, +%groupedaddress, +%unsortedaddress, +%runinaddress, +%frontmatterverbose, +%preprint, +%preprintnumbers, +%nofootinbib, +%nobibnotes, +%bibnotes, + amsmath,amssymb, + aps, +%pra, +%prb, +%rmp, +%prstab, +%prstper, +%floatfix, +]{revtex4-2} + +\usepackage{graphicx}% Include figure files +\usepackage{dcolumn}% Align table columns on decimal point +\usepackage{bm}% bold math +%\usepackage{hyperref}% add hypertext capabilities +%\usepackage[mathlines]{lineno}% Enable numbering of text and display math +%\linenumbers\relax % Commence numbering lines + +%\usepackage[showframe,%Uncomment any one of the following lines to test +%%scale=0.7, marginratio={1:1, 2:3}, ignoreall,% default settings +%%text={7in,10in},centering, +%%margin=1.5in, +%%total={6.5in,8.75in}, top=1.2in, left=0.9in, includefoot, +%%height=10in,a5paper,hmargin={3cm,0.8in}, +%]{geometry} + +\begin{document} + +\preprint{APS/123-QED} + +\title{Manuscript Title:\\with Forced Linebreak}% Force line breaks with \\ +\thanks{A footnote to the article title}% + +\author{Ann Author} + \altaffiliation[Also at ]{Physics Department, XYZ University.}%Lines break automatically or can be forced with \\ +\author{Second Author}% + \email{Second.Author@institution.edu} +\affiliation{% + Authors' institution and/or address\\ + This line break forced with \textbackslash\textbackslash +}% + +\collaboration{MUSO Collaboration}%\noaffiliation + +\author{Charlie Author} + \homepage{http://www.Second.institution.edu/~Charlie.Author} +\affiliation{ + Second institution and/or address\\ + This line break forced% with \\ +}% +\affiliation{ + Third institution, the second for Charlie Author +}% +\author{Delta Author} +\affiliation{% + Authors' institution and/or address\\ + This line break forced with \textbackslash\textbackslash +}% + +\collaboration{CLEO Collaboration}%\noaffiliation + +\date{\today}% It is always \today, today, + % but any date may be explicitly specified + +\begin{abstract} +An article usually includes an abstract, a concise summary of the work +covered at length in the main body of the article. +\begin{description} +\item[Usage] +Secondary publications and information retrieval purposes. +\item[Structure] +You may use the \texttt{description} environment to structure your abstract; +use the optional argument of the \verb+\item+ command to give the category of each item. +\end{description} +\end{abstract} + +%\keywords{Suggested keywords}%Use showkeys class option if keyword + %display desired +\maketitle + +%\tableofcontents + +\section{\label{sec:level1}First-level heading:\protect\\ The line +break was forced \lowercase{via} \textbackslash\textbackslash} + +This sample document demonstrates proper use of REV\TeX~4.2 (and +\LaTeXe) in mansucripts prepared for submission to APS +journals. Further information can be found in the REV\TeX~4.2 +documentation included in the distribution or available at +\url{http://journals.aps.org/revtex/}. + +When commands are referred to in this example file, they are always +shown with their required arguments, using normal \TeX{} format. In +this format, \verb+#1+, \verb+#2+, etc. stand for required +author-supplied arguments to commands. For example, in +\verb+\section{#1}+ the \verb+#1+ stands for the title text of the +author's section heading, and in \verb+\title{#1}+ the \verb+#1+ +stands for the title text of the paper. + +Line breaks in section headings at all levels can be introduced using +\textbackslash\textbackslash. A blank input line tells \TeX\ that the +paragraph has ended. Note that top-level section headings are +automatically uppercased. If a specific letter or word should appear in +lowercase instead, you must escape it using \verb+\lowercase{#1}+ as +in the word ``via'' above. + +\subsection{\label{sec:level2}Second-level heading: Formatting} + +This file may be formatted in either the \texttt{preprint} or +\texttt{reprint} style. \texttt{reprint} format mimics final journal output. +Either format may be used for submission purposes. \texttt{letter} sized paper should +be used when submitting to APS journals. + +\subsubsection{Wide text (A level-3 head)} +The \texttt{widetext} environment will make the text the width of the +full page, as on page~\pageref{eq:wideeq}. (Note the use the +\verb+\pageref{#1}+ command to refer to the page number.) +\paragraph{Note (Fourth-level head is run in)} +The width-changing commands only take effect in two-column formatting. +There is no effect if text is in a single column. + +\subsection{\label{sec:citeref}Citations and References} +A citation in text uses the command \verb+\cite{#1}+ or +\verb+\onlinecite{#1}+ and refers to an entry in the bibliography. +An entry in the bibliography is a reference to another document. + +\subsubsection{Citations} +Because REV\TeX\ uses the \verb+natbib+ package of Patrick Daly, +the entire repertoire of commands in that package are available for your document; +see the \verb+natbib+ documentation for further details. Please note that +REV\TeX\ requires version 8.31a or later of \verb+natbib+. + +\paragraph{Syntax} +The argument of \verb+\cite+ may be a single \emph{key}, +or may consist of a comma-separated list of keys. +The citation \emph{key} may contain +letters, numbers, the dash (-) character, or the period (.) character. +New with natbib 8.3 is an extension to the syntax that allows for +a star (*) form and two optional arguments on the citation key itself. +The syntax of the \verb+\cite+ command is thus (informally stated) +\begin{quotation}\flushleft\leftskip1em +\verb+\cite+ \verb+{+ \emph{key} \verb+}+, or\\ +\verb+\cite+ \verb+{+ \emph{optarg+key} \verb+}+, or\\ +\verb+\cite+ \verb+{+ \emph{optarg+key} \verb+,+ \emph{optarg+key}\ldots \verb+}+, +\end{quotation}\noindent +where \emph{optarg+key} signifies +\begin{quotation}\flushleft\leftskip1em +\emph{key}, or\\ +\texttt{*}\emph{key}, or\\ +\texttt{[}\emph{pre}\texttt{]}\emph{key}, or\\ +\texttt{[}\emph{pre}\texttt{]}\texttt{[}\emph{post}\texttt{]}\emph{key}, or even\\ +\texttt{*}\texttt{[}\emph{pre}\texttt{]}\texttt{[}\emph{post}\texttt{]}\emph{key}. +\end{quotation}\noindent +where \emph{pre} and \emph{post} is whatever text you wish to place +at the beginning and end, respectively, of the bibliographic reference +(see Ref.~[\onlinecite{witten2001}] and the two under Ref.~[\onlinecite{feyn54}]). +(Keep in mind that no automatic space or punctuation is applied.) +It is highly recommended that you put the entire \emph{pre} or \emph{post} portion +within its own set of braces, for example: +\verb+\cite+ \verb+{+ \texttt{[} \verb+{+\emph{text}\verb+}+\texttt{]}\emph{key}\verb+}+. +The extra set of braces will keep \LaTeX\ out of trouble if your \emph{text} contains the comma (,) character. + +The star (*) modifier to the \emph{key} signifies that the reference is to be +merged with the previous reference into a single bibliographic entry, +a common idiom in APS and AIP articles (see below, Ref.~[\onlinecite{epr}]). +When references are merged in this way, they are separated by a semicolon instead of +the period (full stop) that would otherwise appear. + +\paragraph{Eliding repeated information} +When a reference is merged, some of its fields may be elided: for example, +when the author matches that of the previous reference, it is omitted. +If both author and journal match, both are omitted. +If the journal matches, but the author does not, the journal is replaced by \emph{ibid.}, +as exemplified by Ref.~[\onlinecite{epr}]. +These rules embody common editorial practice in APS and AIP journals and will only +be in effect if the markup features of the APS and AIP Bib\TeX\ styles is employed. + +\paragraph{The options of the cite command itself} +Please note that optional arguments to the \emph{key} change the reference in the bibliography, +not the citation in the body of the document. +For the latter, use the optional arguments of the \verb+\cite+ command itself: +\verb+\cite+ \texttt{*}\allowbreak +\texttt{[}\emph{pre-cite}\texttt{]}\allowbreak +\texttt{[}\emph{post-cite}\texttt{]}\allowbreak +\verb+{+\emph{key-list}\verb+}+. + +\subsubsection{Example citations} +By default, citations are numerical\cite{Beutler1994}. +Author-year citations are used when the journal is RMP. +To give a textual citation, use \verb+\onlinecite{#1}+: +Refs.~\onlinecite{[][{, and references therein}]witten2001,Bire82}. +By default, the \texttt{natbib} package automatically sorts your citations into numerical order and ``compresses'' runs of three or more consecutive numerical citations. +REV\TeX\ provides the ability to automatically change the punctuation when switching between journal styles that provide citations in square brackets and those that use a superscript style instead. This is done through the \texttt{citeautoscript} option. For instance, the journal style \texttt{prb} automatically invokes this option because \textit{Physical +Review B} uses superscript-style citations. The effect is to move the punctuation, which normally comes after a citation in square brackets, to its proper position before the superscript. +To illustrate, we cite several together +\cite{[See the explanation of time travel in ]feyn54,*[The classical relativistic treatment of ][ is a relative classic]epr,witten2001,Berman1983,Davies1998,Bire82}, +and once again in different order (Refs.~\cite{epr,feyn54,Bire82,Berman1983,witten2001,Davies1998}). +Note that the citations were both compressed and sorted. Futhermore, running this sample file under the \texttt{prb} option will move the punctuation to the correct place. + +When the \verb+prb+ class option is used, the \verb+\cite{#1}+ command +displays the reference's number as a superscript rather than in +square brackets. Note that the location of the \verb+\cite{#1}+ +command should be adjusted for the reference style: the superscript +references in \verb+prb+ style must appear after punctuation; +otherwise the reference must appear before any punctuation. This +sample was written for the regular (non-\texttt{prb}) citation style. +The command \verb+\onlinecite{#1}+ in the \texttt{prb} style also +displays the reference on the baseline. + +\subsubsection{References} +A reference in the bibliography is specified by a \verb+\bibitem{#1}+ command +with the same argument as the \verb+\cite{#1}+ command. +\verb+\bibitem{#1}+ commands may be crafted by hand or, preferably, +generated by Bib\TeX. +REV\TeX~4.2 includes Bib\TeX\ style files +\verb+apsrev4-2.bst+, \verb+apsrmp4-2.bst+ appropriate for +\textit{Physical Review} and \textit{Reviews of Modern Physics}, +respectively. + +\subsubsection{Example references} +This sample file employs the \verb+\bibliography+ command, +which formats the \texttt{\jobname .bbl} file +and specifies which bibliographic databases are to be used by Bib\TeX\ +(one of these should be by arXiv convention \texttt{\jobname .bib}). +Running Bib\TeX\ (via \texttt{bibtex \jobname}) +after the first pass of \LaTeX\ produces the file +\texttt{\jobname .bbl} which contains the automatically formatted +\verb+\bibitem+ commands (including extra markup information via +\verb+\bibinfo+ and \verb+\bibfield+ commands). +If not using Bib\TeX, you will have to create the \verb+thebibiliography+ environment +and its \verb+\bibitem+ commands by hand. + +Numerous examples of the use of the APS bibliographic entry types appear in the bibliography of this sample document. +You can refer to the \texttt{\jobname .bib} file, +and compare its information to the formatted bibliography itself. + +\subsection{Footnotes}% +Footnotes, produced using the \verb+\footnote{#1}+ command, +usually integrated into the bibliography alongside the other entries. +Numerical citation styles do this% +\footnote{Automatically placing footnotes into the bibliography requires using BibTeX to compile the bibliography.}; +author-year citation styles place the footnote at the bottom of the text column. +Note: due to the method used to place footnotes in the bibliography, +\emph{you must re-run Bib\TeX\ every time you change any of your document's footnotes}. + +\section{Math and Equations} +Inline math may be typeset using the \verb+$+ delimiters. Bold math +symbols may be achieved using the \verb+bm+ package and the +\verb+\bm{#1}+ command it supplies. For instance, a bold $\alpha$ can +be typeset as \verb+$\bm{\alpha}$+ giving $\bm{\alpha}$. Fraktur and +Blackboard (or open face or double struck) characters should be +typeset using the \verb+\mathfrak{#1}+ and \verb+\mathbb{#1}+ commands +respectively. Both are supplied by the \texttt{amssymb} package. For +example, \verb+$\mathbb{R}$+ gives $\mathbb{R}$ and +\verb+$\mathfrak{G}$+ gives $\mathfrak{G}$ + +In \LaTeX\ there are many different ways to display equations, and a +few preferred ways are noted below. Displayed math will center by +default. Use the class option \verb+fleqn+ to flush equations left. + +Below we have numbered single-line equations; this is the most common +type of equation in \textit{Physical Review}: +\begin{eqnarray} +\chi_+(p)\alt{\bf [}2|{\bf p}|(|{\bf p}|+p_z){\bf ]}^{-1/2} +\left( +\begin{array}{c} +|{\bf p}|+p_z\\ +px+ip_y +\end{array}\right)\;, +\\ +\left\{% + \openone234567890abc123\alpha\beta\gamma\delta1234556\alpha\beta + \frac{1\sum^{a}_{b}}{A^2}% +\right\}% +\label{eq:one}. +\end{eqnarray} +Note the open one in Eq.~(\ref{eq:one}). + +Not all numbered equations will fit within a narrow column this +way. The equation number will move down automatically if it cannot fit +on the same line with a one-line equation: +\begin{equation} +\left\{ + ab12345678abc123456abcdef\alpha\beta\gamma\delta1234556\alpha\beta + \frac{1\sum^{a}_{b}}{A^2}% +\right\}. +\end{equation} + +When the \verb+\label{#1}+ command is used [cf. input for +Eq.~(\ref{eq:one})], the equation can be referred to in text without +knowing the equation number that \TeX\ will assign to it. Just +use \verb+\ref{#1}+, where \verb+#1+ is the same name that used in +the \verb+\label{#1}+ command. + +Unnumbered single-line equations can be typeset +using the \verb+\[+, \verb+\]+ format: +\[g^+g^+ \rightarrow g^+g^+g^+g^+ \dots ~,~~q^+q^+\rightarrow +q^+g^+g^+ \dots ~. \] + + +\subsection{Multiline equations} + +Multiline equations are obtained by using the \verb+eqnarray+ +environment. Use the \verb+\nonumber+ command at the end of each line +to avoid assigning a number: +\begin{eqnarray} +{\cal M}=&&ig_Z^2(4E_1E_2)^{1/2}(l_i^2)^{-1} +\delta_{\sigma_1,-\sigma_2} +(g_{\sigma_2}^e)^2\chi_{-\sigma_2}(p_2)\nonumber\\ +&&\times +[\epsilon_jl_i\epsilon_i]_{\sigma_1}\chi_{\sigma_1}(p_1), +\end{eqnarray} +\begin{eqnarray} +\sum \vert M^{\text{viol}}_g \vert ^2&=&g^{2n-4}_S(Q^2)~N^{n-2} + (N^2-1)\nonumber \\ + & &\times \left( \sum_{i0$\\ +x^3 & else +\end{rcases*} \Rightarrow \cdots +\] + +\[ +\begin{drcases} +E = m c^2 & 5^6 \quad \text{and so on} \\ +\int x-3\, dx & \int x \, dx +\end{drcases} = b +\] + +\[ +\begin{drcases*} +x^2 & for $\int x\,dx>0$\\ +\int x^3\,x & else +\end{drcases*} \Rightarrow \cdots +\] + +\[ +\text{foo} = \begin{cases*} +\pi & if something\\ +\int \Omega^\Xi\,\Omega & otherwise +\end{cases*} +\] + +\section{Gathered} + +\[ +A = \begin{gathered}[t] +\framebox[4cm]{first} \\ +\framebox[4cm]{last} +\end{gathered} B +\] + +\[ +\begin{gathered} +a=b+c\\ +b=c+d\\ +... +\end{gathered} +\] + +\[ +\boxed{hello} +\] + +\begin{align*} +\Aboxed{ f(x) & = \int h(x)\, dx} \\ +& = g(x) +\end{align*} + +\begin{align} +a&=b \intertext{Some text} +c&=d \shortintertext{Some short text} +e&=f +\end{align} + +\section{Delimiters} + +\[ +\lvert \frac{a}{c} \rvert \quad \left\lvert \frac{a}{c} \right\rvert \quad \Bigg\lvert \frac{a}{b} \Bigg\rvert +\] + +\DeclarePairedDelimiter\abs{\lvert}{\rvert} +\[ +\abs{\frac{a}{b}} \quad \abs*{\frac{a}{b}} \quad \abs[\big]{\frac{a}{b}} \quad \abs[\Bigg]{\frac{a}{b}} +\] +\reDeclarePairedDelimiterInnerWrapper\abs{star}{#1\_#2\_#3} +\reDeclarePairedDelimiterInnerWrapper\abs{nostar}{#1@#2@#3} +\[ +\abs{\pi} \quad \abs*{\phi} +\] + +\DeclarePairedDelimiterX\innerp[2]{\langle}{\rangle}{#1,#2} +\DeclarePairedDelimiterX\braket[3]{\langle}{\rangle}{#1\,\delimsize\vert\,#2\,\delimsize\vert\,#3} +\[ +\innerp*{A}{ \frac{1}{2} } \quad +\braket[\Big]{B}{\sum_{k} f_k}{C} +\] + +\providecommand\given{} +\newcommand\SetSymbol[1][]{#1\vert\allowbreak} +\DeclarePairedDelimiterX\Set[1]\{\}{\renewcommand\given{\SetSymbol[\delimsize]}#1} +\[ \Set*{ x \in X \given \frac {\sqrt{x}}{x^2+1} > 1 } \] + +\DeclarePairedDelimiterX\braketdelim[3]{\langle}{\rangle}% +{#1\,\delimsize\vert\,#2\,\delimsize\vert\,#3} +$\braketdelim{1}{\frac{8}{\frac{4}{1}}}{3}$ +$\braketdelim*{1}{\frac{8}{\frac{4}{1}}}{3}$ +$\braketdelim[\big]{1}{\frac{8}{\frac{4}{1}}}{3}$ + +% % XPP not available in v1.13 +% \DeclarePairedDelimiterXPP\lnorm[1]{}\lVert\rVert{_2}{#1} +% \DeclarePairedDelimiterXPP\Prop[1]{\mathbb{P}}(){}{\renewcommand\given{\delimsize\vert}#1} +% \[ +% \lnorm{\frac{\pi}{\int x dx}} \quad \Prop{foo} +% \] + +\[ +\left( \frac{\pi}{\omega} \right) \cdot \left[ \int x dx \right] \ldots \lbrack \sqrt{\frac{\sin x}{\cos z}} \rbrack \cdots \lparen \frac{\frac{foo}{bar}}{\frac{baz}{qux}} \rparen +\] + +\paragraph{Operators} +\[ +a := b \quad +a \vcentcolon= b \quad +a \ordinarycolon= b +\] + +\[ +a \coloneqq b \quad c \Colonapprox d \quad e \dblcolon f +\] + +\[ +\bigtimes \times \nuparrow \ndownarrow \otimes \bigotimes +\] + +\section{Prescripts} + +\[ +{}^{4}_{12}\mathbf{C}^{5+}_{2} \quad +\prescript{14}{2}{\mathbf{C}}^{5+}_{2} \quad +\prescript{4}{12}{\mathbf{C}}^{5+}_{2} \quad +\prescript{14}{}{\mathbf{C}}^{5+}_{2} \quad +\prescript{}{2}{\mathbf{C}}^{5+}_{2} +\] + +\newcommand*\myisotope[3]{% +\begingroup % to keep changes local. We cannot use a brace group +% as it affects spacing! +\mathtoolsset{ +prescript-sup-format=\mathit, +prescript-sub-format=\mathbf, +prescript-arg-format=\mathrm, +}% +\prescript{#1}{#2}{#3}% +\endgroup +} +\[ +\myisotope{A}{Z}{X}\to \myisotope{A-4}{Z-2}{Y}+ +\myisotope{4}{2}{\alpha} +\] + +\[ + a=\frac{ + \splitfrac{xy + xy + \int xy\, \text{dx} + xy + xy} + {+ xy + xy + xy + xy} + } + {z} + =\frac{ + \splitdfrac{xy + xy + \int xy\, \text{dx} + xy + xy} + {+ xy + xy + xy + xy} + } + {z} +\] + +\section{Multlines} + +\begin{multline*} +p(x) = 3x^6 + 14x^5y + 590x^4y^2 + 19x^3y^3\\ +- 12x^2y^4 - 12xy^5 + 2y^6 - a^3b^3 +\end{multline*} + +\[ +A = \begin{multlined}[t] +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\[ +A = \begin{multlined} +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\[ +A = \begin{multlined}[b] +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\mathtoolsset{multlined-pos=t,multlined-width=12em} + +\[ +A = \begin{multlined}[c][1cm] +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\[ +A = \begin{multlined}[c][0.5\textwidth] +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\[ +A = \begin{multlined}[c][2\textwidth] +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\[ +A = \begin{multlined} +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\[ +A = \begin{multlined}[b] +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\[ +A = \begin{multlined}[c][1cm] +\boxed{first} \\ +\boxed{last} +\end{multlined} B +\] + +\begin{equation} +foo\Coloneqq\begin{lgathered}[t] +x=1,\quad x+1=2 \\ +y=2 +\end{lgathered} +\end{equation} + +\begin{equation} +bar\Coloneqq\begin{rgathered}[b] +x=1,\quad x+1=2 \\ +y=2 +\end{rgathered} +\end{equation} + +\section{Spread-lines} +Spread it +\begin{spreadlines}{30pt} + \[ + \begin{matrix} + a & b & c \\ + d & e & f \\ + g & h & i + \end{matrix} + \] + + \[ + \begin{pmatrix} + a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\ + a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\ + \vdots & \vdots & \ddots & \vdots \\ + a_{m,1} & a_{m,2} & \cdots & a_{m,n} + \end{pmatrix} + \] + + $\begin{smallmatrix} a&b \\ c&d \end{smallmatrix}$ + + $\begin{cases} n/2 & \quad \text{if } n \text{ is even}\\ -(n+1)/2 & \quad \text{if } n \text{ is odd}\\ \end{cases}$ + + \begin{equation}\label{xx} + \begin{split} + a& =b+c-d\\ + & \quad +e-f\\ + & =g+h\\ + & =i + \end{split} + \end{equation} + + \begin{multline} + a+b+c+d+e+f\\ + +i+j+k+l+m+n + \end{multline} + + \begin{gather} + a=b\\ + c=d + \end{gather} + + \begin{align} + a_1& =b_1+c_1\\ + a_2& =b_2+c_2-d_2+e_2 + \end{align} + + \begin{flalign*} + a_{11}& =b_{11}& + a_{12}& =b_{12}\\ + a_{21}& =b_{21}& + a_{22}& =b_{22}+c_{22} + \end{flalign*} + + \begin{alignat}{2} + x& = y_1-y_2+y_3-y_5+y_8-\dots + &\quad& \text{by foo}\\ + & = y'\circ y^* && \text{by baz}\\ + & = y(0) y' && \text {by Axiom 1.} + \end{alignat} + + \begin{equation*} + \left.\begin{aligned} + B'&=-\partial\times E,\\ + E'&=\partial\times B - 4\pi j, + \end{aligned} + \right\} + \qquad \text{Maxwell's equations} + \end{equation*} + + \[ + \bigl( \begin{smallmatrix} + a&b\\ c&d + \end{smallmatrix} \bigr) + \] + + \[ + \bigl( \begin{smallmatrix*} + a&b\\ c&d + \end{smallmatrix*} \bigr) + \] + + \[ + \sum_{\begin{subarray}{l} + i\in\Lambda\\ 0{$\displaystyle}c<{$}} +\newcolumntype{L}{>{$\displaystyle}l<{$}} + +\newcommand{\typical}{X} +\newcommand{\tall}{X^Y} +\newcommand{\grande}{\frac{X}{Y}} +\newcommand{\venti}{\sum_{X=0}^N} + +% physics 1.30 +\title{The \texttt{physics} package} +\begin{document} +\section{List of commands} +%====================================================================== +\subsection{Automatic bracing} +\[ +\qty(\typical) +\qquad \qty(\tall) +\qquad\qty(\grande) +\qquad\qty[\typical] +\qquad\qty|\typical| +\qquad\qty{\typical} +\qquad\qty\big{x} +\qquad\qty\Big{x} +\qquad\qty\bigg{x} +\qquad\qty\Bigg{x} +\] +\[ + \qty(a^2(b)c_2) + \] +\[ +\pqty{x} +\qquad\bqty{x} +\qquad\vqty{x} +\qquad\Bqty{x} +\] + +\[ +\abs{a} +\qquad\abs\Big{a} +\qquad \abs*{\grande} +\qquad \norm{a} +\qquad\norm\Big{a} +\qquad\norm*{\grande} +\] + +\[ + \eval{x}_0^\infty +\qquad \eval(x|_0^\infty +\qquad \eval[x|_0^\infty +\qquad \eval[\venti|_0^\infty +\qquad \eval*[\venti|_0^\infty +\] +\[ + \order{x^2} +\qquad \order\Big{x^2} +\qquad \order*{\grande} +\qquad \comm{A}{B} +\qquad \comm\Big{A}{B} +\qquad \comm*{A}{\grande} +\qquad \acomm{A}{B} +\qquad \pb{A}{B} +\] + +\subsection{Vector notation} +\[ \vb{a} +\qquad \vb*{a} +\qquad \va{a} +\qquad \va*{a} +\qquad \vu{a} +\qquad \vu*{a} +\] +\[ + \vdot +\qquad \cross +\qquad \cp +\] +\[ + \grad +\qquad \grad{\Psi} +\qquad \grad(\Psi+\tall) +\qquad \grad[\Psi+\tall] +\] +\[ + \div +\qquad \div{\vb{a}} +\qquad \div(\vb{a}+\tall) +\qquad \div[\vb{a}+\tall] +\] +\[ + \curl +\qquad \curl{\vb{a}} +\qquad \curl(\vb{a}+\tall) +\qquad \curl[\vb{a}+\tall] +\] +\[ + \laplacian +\qquad \laplacian{\Psi} +\qquad \laplacian(\Psi+\tall) +\qquad \laplacian[\Psi+\tall] +\] +\subsection{Operators} +\[ + \sin(\grande) +\qquad \sin[2](x) +\qquad \sin x +\] +But +\[ +\sin[\grande] +\qquad \sin[x][\grande] +\qquad \sin[x]{\grande} +\qquad \sin\{\grande\} +\qquad \sin[x]\{\grande\} + \] + + \begin{tabular}{MMMM} +\sin(x) & \sinh(x) & \arcsin(x) & \asin(x) \\ +\cos(x) & \cosh(x) & \arccos(x) & \acos(x) \\ +\tan(x) & \tanh(x) & \arctan(x) & \atan(x) \\ +\csc(x) & \csch(x) & \arccsc(x) & \acsc(x) \\ +\sec(x) & \sech(x) & \arcsec(x) & \asec(x) \\ +\cot(x) & \coth(x) & \arccot(x) & \acot(x) +\end{tabular} + +% \begin{tabular}{llll} +% \verb|\sine| & \verb|\hypsine| & \verb|\arcsine| & \verb|\asine| \\ +% \verb|\cosine| & \verb|\hypcosine| & \verb|\arccosine| & \verb|\acosine| \\ +% \verb|\tangent| & \verb|\hyptangent| & \verb|\arctangent| & \verb|\atangent| \\ +% \verb|\cosecant| & \verb|\hypcosecant| & \verb|\arccosecant| & \verb|\acosecant| \\ +% \verb|\secant| & \verb|\hypsecant| & \verb|\arcsecant| & \verb|\asecant| \\ +% \verb|\cotangent| & \verb|\hypcotangent| & \verb|\arccotangent| & \verb|\acotangent| +% \end{tabular} + +\[ + \exp(\tall) +\qquad \log(\tall) +\qquad\ln(\tall) +\qquad \det(\tall) +\qquad \Pr(\tall) +\] + + +\[ + \tr\rho +\qquad \tr(\tall) +\qquad \Tr\rho +\qquad \rank M +\qquad \erf(x) +\qquad \Res[f(z)] +\] +\[ +\qquad \pv{\int f(z) \dd{z}} +\qquad \PV{\int f(z) \dd{z}} +\qquad \Re{z} +\qquad \real +\qquad \Im{z} +\qquad \imaginary +\] + +But + \[ \Re(\grande) + \qquad \Re[\grande] + \qquad \Im(\grande) + \qquad \Im[\grande] +\] + +\subsection{Quick quad text} +\[ +[\qq{word or phrase}] +[\qq*{word or phrase}] +\] + +\[ + [\qcomma], [\qcc], [\qif],[\qthen], [\qelse], [\qotherwise], [\qunless], [\qgiven] +\] +\[ + [\qusing],[\qassume], [\qsince], [\qlet], [\qfor], [\qall], [\qeven], [\qodd], +\] +\[ + [\qinteger], [\qand], [\qor], [\qas], [\qin] +\] + +\subsection{Derivatives} + +\[ + \dd + \qquad \dd x + \qquad\dd{x} + \qquad \dd[3]{x} + \qquad \dd(\cos\theta) +\] +\[ + \dv{x} + \qquad \dv{x} f + \qquad \dv{f}{x} + \qquad \dv[n]{f}{x} + \qquad \dv{x}(\grande) + \qquad \dv*{f}{x} +\] +\[ + \pderivative{x} + \qquad \pderivative{x} f + \qquad \pdv{x} + \qquad \pdv{f}{x} + \qquad \pdv[n]{f}{x} + \qquad \pdv{x}(\grande) + \qquad \pdv*{f}{x} +\] + \[ + \var{F[g(x)]} + \qquad \var(E-TS) + \qquad \fdv{g} + \qquad \fdv{F}{g} + \qquad \fdv{V}(E-TS) + \qquad \fdv*{F}{x} +\] +But + \[ + \dd[2][\grande] +\] +And multiple derivatives, sorta; But only for partial: +\[ + \pdv{f}{x}{y} + \qquad \pdv{f}{x}{y}{z} + \qquad \pdv[3]{f}{x}{y}{z} + \qquad \pdv{x}{y}(f) + \] +\[ + \qquad \dv{f}{x}{y} + \qquad \fdv{F}{f}{g} +\] + +\subsection{Dirac bra-ket notation} +\begin{displaymath} + \bra{\phi}\ket{\psi} \qq{as opposed to} \bra{\phi} \ket{\psi} +\end{displaymath} +\begin{displaymath} + \bra{\phi}\dyad{\psi}{\xi}. + \qq{as opposed to} + \bra{\phi}\ket{\psi}\bra{\xi} +\end{displaymath} + +\[ + \ket{\tall} +\qquad \ket*{\tall} +\qquad \bra{\tall} +\qquad \bra*{\tall} +\] +\[ + \bra{\phi}\ket{\psi} +\qquad \bra{\phi}\ket{\tall} +\qquad \bra{\phi}\ket*{\tall} +\qquad \bra*{\phi}\ket{\tall} +\qquad \bra*{\phi}\ket*{\tall} +\] +\[ + \braket{a}{b} +\qquad \braket{a} +\qquad \braket{a}{\tall} +\qquad \braket*{a}{\tall} +\] +\[ + \ip{a}{b} +\qquad \dyad{a}{b} +\qquad \dyad{a} +\qquad \dyad{a}{\tall} +\qquad \dyad*{a}{\tall} +\qquad \ketbra{a}{b} +\] +\[ + \op{a}{b} +\qquad \expval{A} +\qquad \expval{A}{\Psi} +\qquad \ev{A}{\Psi} +\qquad \ev{\grande}{\Psi} +\qquad \ev*{\grande}{\tall} +\qquad \ev**{\grande}{\Psi} +\] +\[ + \matrixel{n}{A}{m} +\qquad \mel{n}{A}{m} +\qquad \mel{n}{\grande}{m} +\qquad \mel*{n}{\grande}{\tall} +\qquad \mel**{n}{\grande}{m} +\] + +\subsection{Matrix macros} +\[\begin{pmatrix} +\imat{2} \\ a & b +\end{pmatrix} +\] + +\[ +\begin{pmatrix} +\mqty{\imat{2}} & \mqty{a\\b} \\ \mqty{c & d} & e +\end{pmatrix} +\] + +\[ +\mqty(\mqty{\imat{2}} & \mqty{a\\b} \\ \mqty{c & d} & e) +\] + +But, alignment is illusion +\[ + \begin{pmatrix} + \mqty{\imat{2}} & \mqty{\displaystyle\frac{x}{y}\\b} \\ \mqty{u+v+w+x+y+z & d} & e + \end{pmatrix} +\] + +\[ + \mqty{a & b \\ c & d} +\qquad {\mqty(a & b \\ c & d)} +\qquad {\mqty*(a & b \\ c & d)} +\qquad {\mqty[a & b \\ c & d]} +\qquad {\mqty|a & b \\ c & d|} +\qquad \smqty{a & b \\ c & d} +\qquad {\mdet{a & b \\ c & d}} +\qquad {\smdet{a & b \\ c & d}} +\] +\[ + \smqty(\imat{3}) +\qquad \smqty(\xmat{1}{2}{3}) +\qquad \smqty(\xmat*{a}{3}{3}) +\qquad \smqty(\xmat*{a}{3}{1}) +\qquad \smqty(\xmat*{a}{1}{3}) +\qquad \smqty(\zmat{2}{2}) +\] +\[ + \smqty(\pmat{0}) +\qquad \smqty(\pmat{1}) +\qquad \smqty(\pmat{2}) +\qquad \smqty(\pmat{3}) +\] +\[ + \mqty(\dmat{1,2,3}) +\qquad \mqty(\dmat[0]{1,2}) +\qquad \mqty(\dmat{1,2&3\\4&5}) +\qquad \mqty(\admat{1,2,3}) +\] + +\end{document} \ No newline at end of file diff --git a/latex/math/sampler_af5d02.tex b/latex/math/sampler_af5d02.tex new file mode 100644 index 0000000..c15003a --- /dev/null +++ b/latex/math/sampler_af5d02.tex @@ -0,0 +1,243 @@ +\documentclass{article} +\usepackage{amsmath} +\usepackage{amsfonts} +\usepackage{mathrsfs} +\usepackage{xcolor} +\usepackage{mathtools} +\usepackage{graphicx} +\newcommand{\mml}[1]{\texttt{m:#1}} +\newcommand{\attr}[1]{\texttt{@#1}} +%\newcommand{\mathsized}[2]{\scalebox{#1}{#2}} +\newcommand{\mathsized}[2]{\mbox{#1 $#2$}} +\title{LaTeXML Math Sampler} +\begin{document} +This document is a sampler of the kind of MathML produced by LaTeXML, +primarily for testing for sufficient MathML support. +It is \emph{not} a comprehensive test, nor a torture test. + +% m:math, @display + + +The \mml{semantics}, \mml{annotation}, and \mml{annotation-xml} elements +will be exercised if you generate both presentation and content during post-processing +using the \verb|--pmml --cmml| options. +%m:semantics +%m:annotation, @encoding +%m:annotation-xml, @encoding + + +\section{Token Elements} +Token elements \mml{mi}, \mml{mo} and \mml{mn}, with various +attributes \attr{mathvariant}, \attr{mathsize} and \attr{class}. +% m:mo, m:mi, m:mn, +% @mathvariant, +% @minsize, @maxsize, @mathsize, @stretchy, +% @mathcolor, @mathbackground, +% @class = ltx_font_mathcaligraphic | ltx_font_mathscript | ltx_font_oldstyle | ltx_font_smallcaps +\begin{equation} + A,\qquad + \mathnormal{A},\qquad + \mathrm{A},\qquad + \mathit{A},\qquad + \mathbf{A},\qquad + \mathsf{A},\qquad + \mathtt{A}, +\end{equation} +\begin{equation} + \mathcal{A},\qquad + \mathscr{A},\qquad + \mathbb{A},\qquad + \mathfrak{A} +\end{equation} +\begin{equation} + \mathsized{\tiny}{X},\qquad + \mathsized{\scriptsize}{X},\qquad + \mathsized{\normalsize}{X},\qquad + \mathsized{\large}{X},\qquad + \mathsized{\Large}{X},\qquad + \mathsized{\LARGE}{X},\qquad + \mathsized{\huge}{X},\qquad + \mathsized{\Huge}{X} +\end{equation} + +And some color, \attr{mathcolor}, \attr{mathbackground}: +\begin{equation} + {\color{red} X}, \qquad + {\color{blue} X}, \qquad + {\color{green} X}, \qquad + \fcolorbox{blue}{red}{\textcolor{green}{X}} +\end{equation} + +Playing with \attr{minsize}, \attr{maxsize}, \attr{stretchy}: +% m:mi, @fence, @separator, @largeop, @symmetric, @lspace, @rspace, @movablelimits +\begin{equation} + (a|b),\qquad + \bigl(a\bigm|b\bigr),\qquad + \Bigl(a\Bigm|b\Bigr),\qquad + \biggl(a\biggm|b\biggr),\qquad + \Biggl(a\Biggm|b\Biggr) +\end{equation} + +\begin{equation} +\left( a^{b} \middle| x \right),\qquad +\left( a^{b^{c}} \middle| x \right),\qquad +\left( a^{b^{c^{d}}} \middle| x \right) +\end{equation} + +Weird arguments for delimiters +\begin{equation} + \left \relax ( x \right \relax ), \qquad + \Bigg ( x \Bigg{ \relax ) }, \qquad + \Big{((} x-z \Big{))} +\end{equation} + +% m:mtext +% m:mspace, @width +\begin{equation} + \mbox{Hello} + y - 1.2345 +\end{equation} +Some spacing \mml{mspace}. +\begin{equation} + xy,\qquad + x \hspace{1em} y,\qquad + x \hspace{2em} y +\end{equation} +% m:mglyph not used +% m:ms not used +Not used: \mml{mglyph}, \mml{ms}. + +\section{General Layout Schemata} +Various layout schemata \mml{mrow}, \mml{mfrac} (with various \attr{linethickness}), +and \mml{mstyle}: +%m:mrow +% m:mfrac, @linethickness +\begin{equation} + \frac{a}{b},\qquad + \tfrac{a}{b},\qquad + \dfrac{a}{b} +\end{equation} +\begin{equation} + \binom{a}{b} + \genfrac{}{}{0.0ex}{}{a}{b},\qquad + \genfrac{}{}{0.01ex}{}{a}{b},\qquad + \genfrac{}{}{0.1ex}{}{a}{b},\qquad + \genfrac{}{}{1ex}{}{a}{b} +\end{equation} +\begin{equation} + \genfrac{(}{)}{}{}{a}{b},\qquad + \genfrac{(}{)}{}{}{a^2}{b^2},\qquad + \genfrac{(}{)}{}{}{\int_a^b f(x)dx}{\int_a^b g(x)dx} +\end{equation} + +Roots \mml{msqrt} and \mml{mroot}, as well as enclosures \mml{menclose}: +% m:msqrt, m:mroot +% m:menclose, @notation +\begin{equation} + \sqrt{x},\qquad + \sqrt[3]{x},\qquad + \root 3 \of {x},\qquad + \boxed{x^2},\qquad + \not{?} +\end{equation} + +% m:mstyle, @displaystyle, @scriptlevel +% m:merror + +More spacing examples with \mml{mpadded}: +% m:mpadded, @lspace, @width +\begin{equation} + a+b, \qquad + a \,+\, b, \qquad + a \>+\> b, \qquad + a \;+\; b, \qquad +\end{equation} +% m:phantom +\begin{eqnarray} + X &=& f(x) + g(x) + h(x) \\ + &=& f(x) + \phantom{g(x)} + h(x) \\ +\end{eqnarray} +%% m:mfenced, @open, @close [not really used] + +Not used: \mml{mfenced}, \mml{mphantom}; +used only for errors: \mml{merror}. + +\section{Script and Limit Schemata} +A variety of sub- and super-scripts (\mml{msub}, \mml{msup}, \mml{msubsup}), +under- and over-scripts (\mml{munder}, \mml{mover}, \mml{munderover}), +some as accents, and pre-scripts (\mml{multiscripts}, \mml{mprescripts}). +% m:sub, m:sup, m:subsup + +\begin{equation} + a^{b},\qquad + a^{b^{c}},\qquad + a^{b^{c^{d}}},\qquad + a_{b},\qquad + a_{b_{c}},\qquad + a_{b_{c_ {d}}},\qquad + a^{b}_{c} +\end{equation} + +% m:under, m:over, m:underover +\begin{equation} + \sum^{b},\qquad + \sum_{b},\qquad + \sum^{b}_{c} +\end{equation} +\begin{equation} +X = \sum_{1\le i \le j \le n} X_{ij},\qquad +X = \sum_{\mathclap{1\le i \le j \le n}} X_{ij},\qquad +%X = \smashoperator{\sum_{1\le i \le j \le n}} X_{ij},\qquad +X = \smashoperator[r]{\sum_{1\le i \le j \le n}} X_{ij},\qquad +X = \smashoperator[l]{\sum_{1\le i \le j \le n}} X_{ij} +\end{equation} + +\begin{equation} + a \overset{\mathrm{def}}{\rightarrow} b, \qquad + a \underset{\mathrm{def}}{\rightarrow} b,\qquad + a \overrightarrow{\mathrm{def}} b,\qquad + a \underrightarrow{\mathrm{def}} b +\end{equation} + +\begin{equation} + \overline{abc}^s \qquad + \overleftarrow{abc}^s \qquad + \overrightarrow{abc}^s \qquad + \overbrace{abc}^s \qquad + \underline{abc}_s \qquad + \underbrace{abc}_s +\end{equation} + +% m:multiscripts, m:prescripts, m:none +\begin{equation} + {}_p F_q,\qquad + \sideset{_a^b}{^c_d}{\sum} +\end{equation} + +\section{Tabular Math} +Some basic tabular math (\mml{mtable}, \mml{mtr}, \mml{mtd}); +many combinations of row and column spacing and spans +(\attr{rowspacing}, \attr{columnspacing}, \attr{columnspan}, \attr{rowspan}) +are not currently tested. +%m:mtable, @rowspacing, @columnspacing, @width +%m:mtr +%m:mtd, @columnalign, @columnspan, @rowspan + +\begin{equation} + \begin{matrix} -1 & 3 \\ 2 & -4 \end{matrix} +,\qquad + \begin{matrix*}[r] -1 & 3 \\ 2 & -4 \end{matrix*} +,\qquad + \begin{Vmatrix} -1 & 3 \\ 2 & -4 \end{Vmatrix} +,\qquad + \begin{Vmatrix*}[r] -1 & 3 \\ 2 & -4 \end{Vmatrix*} +\end{equation} +% m:mlabeledtr, m:maligngroup, m:malignmark not used +Not used: \mml{mlabeledtr}, \mml{maligngroup}, \mml{malignmark}. + +\section{Elementary Math} +% m:mstack, m:mlongdiv, m:msgroup, m:msrow, +% m:mscarries, m:mscarry, m:msline not used +Not currently used: +\mml{mstack}, \mml{mlongdiv}, \mml{msgroup}, \mml{msrow}, +\mml{mscarries}, \mml{mscarry}, \mml{msline}. +\end{document} diff --git a/latex/math/testmath_232f5d.tex b/latex/math/testmath_232f5d.tex new file mode 100644 index 0000000..c0df337 --- /dev/null +++ b/latex/math/testmath_232f5d.tex @@ -0,0 +1,2315 @@ +%%% ==================================================================== +%%% filename = testmath.tex +%%% version = 2.0a +%%% date = 2023/08/24 +%%% author = American Mathematical Society +%%% copyright = Copyright 1995, 1999 American Mathematical Society +%%% 2023 LaTeX Project. +%%% License = https://www.latex-project.org/lppl/lppl-1-3c +%%% keywords = latex, amsmath, examples, documentation +%%% abstract = This is a test file containing extensive examples of +%%% mathematical constructs supported by the amsmath +%%% package." +%%% ==================================================================== +\NeedsTeXFormat{LaTeX2e}% LaTeX 2.09 can't be used (nor non-LaTeX) +[1994/12/01]% LaTeX date must December 1994 or later +\documentclass[draft]{article} +\pagestyle{headings} + +\title{Sample Paper for the \pkg{amsmath} Package\\ +File name: \fn{testmath.tex}} +\author{American Mathematical Society} +\date{Version 2.0a, 2023/08/24} + +\usepackage{amsmath,amsthm} + +% Some definitions useful in producing this sort of documentation: +\chardef\bslash=`\\ % p. 424, TeXbook +% Normalized (nonbold, nonitalic) tt font, to avoid font +% substitution warning messages if tt is used inside section +% headings and other places where odd font combinations might +% result. +\newcommand{\ntt}{\normalfont\ttfamily} +% command name +\newcommand{\cn}[1]{{\protect\ntt\bslash#1}} +% LaTeX package name +\newcommand{\pkg}[1]{{\protect\ntt#1}} +% File name +\newcommand{\fn}[1]{{\protect\ntt#1}} +% environment name +\newcommand{\env}[1]{{\protect\ntt#1}} +\hfuzz1pc % Don't bother to report overfull boxes if overage is < 1pc + +% Theorem environments + +%% \theoremstyle{plain} %% This is the default +\newtheorem{thm}{Theorem}[section] +\newtheorem{cor}[thm]{Corollary} +\newtheorem{lem}[thm]{Lemma} +\newtheorem{prop}[thm]{Proposition} +\newtheorem{ax}{Axiom} + +\theoremstyle{definition} +\newtheorem{defn}{Definition}[section] + +\theoremstyle{remark} +\newtheorem{rem}{Remark}[section] +\newtheorem*{notation}{Notation} + +%\numberwithin{equation}{section} + +\newcommand{\thmref}[1]{Theorem~\ref{#1}} +\newcommand{\secref}[1]{\S\ref{#1}} +\newcommand{\lemref}[1]{Lemma~\ref{#1}} + +\newcommand{\bysame}{\mbox{\rule{3em}{.4pt}}\,} + +% Math definitions + +\newcommand{\A}{\mathcal{A}} +\newcommand{\B}{\mathcal{B}} +\newcommand{\st}{\sigma} +\newcommand{\XcY}{{(X,Y)}} +\newcommand{\SX}{{S_X}} +\newcommand{\SY}{{S_Y}} +\newcommand{\SXY}{{S_{X,Y}}} +\newcommand{\SXgYy}{{S_{X|Y}(y)}} +\newcommand{\Cw}[1]{{\hat C_#1(X|Y)}} +\newcommand{\G}{{G(X|Y)}} +\newcommand{\PY}{{P_{\mathcal{Y}}}} +\newcommand{\X}{\mathcal{X}} +\newcommand{\wt}{\widetilde} +\newcommand{\wh}{\widehat} + +\DeclareMathOperator{\per}{per} +\DeclareMathOperator{\cov}{cov} +\DeclareMathOperator{\non}{non} +\DeclareMathOperator{\cf}{cf} +\DeclareMathOperator{\add}{add} +\DeclareMathOperator{\Cham}{Cham} +\DeclareMathOperator{\IM}{Im} +\DeclareMathOperator{\esssup}{ess\,sup} +\DeclareMathOperator{\meas}{meas} +\DeclareMathOperator{\seg}{seg} + +% \interval is used to provide better spacing after a [ that +% is used as a closing delimiter. +\newcommand{\interval}[1]{\mathinner{#1}} + +% Notation for an expression evaluated at a particular condition. The +% optional argument can be used to override automatic sizing of the +% right vert bar, e.g. \eval[\biggr]{...}_{...} +\newcommand{\eval}[2][\right]{\relax + \ifx#1\right\relax \left.\fi#2#1\rvert} + +% Enclose the argument in vert-bar delimiters: +\newcommand{\envert}[1]{\left\lvert#1\right\rvert} +\let\abs=\envert + +% Enclose the argument in double-vert-bar delimiters: +\newcommand{\enVert}[1]{\left\lVert#1\right\rVert} +\let\norm=\enVert + +\begin{document} +\maketitle +\markboth{Sample paper for the {\protect\ntt\lowercase{amsmath}} package} +{Sample paper for the {\protect\ntt\lowercase{amsmath}} package} +\renewcommand{\sectionmark}[1]{} + +\section{Introduction} + +This paper contains examples of various features from \AmS-\LaTeX{}. + +\section{Enumeration of Hamiltonian paths in a graph} + +Let $\mathbf{A}=(a_{ij})$ be the adjacency matrix of graph $G$. The +corresponding Kirchhoff matrix $\mathbf{K}=(k_{ij})$ is obtained from +$\mathbf{A}$ by replacing in $-\mathbf{A}$ each diagonal entry by the +degree of its corresponding vertex; i.e., the $i$th diagonal entry is +identified with the degree of the $i$th vertex. It is well known that +\begin{equation} +\det\mathbf{K}(i|i)=\text{ the number of spanning trees of $G$}, +\quad i=1,\dots,n +\end{equation} +where $\mathbf{K}(i|i)$ is the $i$th principal submatrix of +$\mathbf{K}$. +\begin{verbatim} +\det\mathbf{K}(i|i)=\text{ the number of spanning trees of $G$}, +\end{verbatim} + +Let $C_{i(j)}$ be the set of graphs obtained from $G$ by attaching edge +$(v_iv_j)$ to each spanning tree of $G$. Denote by $C_i=\bigcup_j +C_{i(j)}$. It is obvious that the collection of Hamiltonian cycles is a +subset of $C_i$. Note that the cardinality of $C_i$ is $k_{ii}\det +\mathbf{K}(i|i)$. Let $\wh X=\{\hat x_1,\dots,\hat x_n\}$. +\begin{verbatim} +$\wh X=\{\hat x_1,\dots,\hat x_n\}$ +\end{verbatim} +Define multiplication for the elements of $\wh X$ by +\begin{equation}\label{multdef} +\hat x_i\hat x_j=\hat x_j\hat x_i,\quad \hat x^2_i=0,\quad +i,j=1,\dots,n. +\end{equation} +Let $\hat k_{ij}=k_{ij}\hat x_j$ and $\hat k_{ij}=-\sum_{j\not=i} \hat +k_{ij}$. Then the number of Hamiltonian cycles $H_c$ is given by the +relation \cite{liuchow:formalsum} +\begin{equation}\label{H-cycles} +\biggl(\prod^n_{\,j=1}\hat x_j\biggr)H_c=\frac{1}{2}\hat k_{ij}\det +\wh{\mathbf{K}}(i|i),\qquad i=1,\dots,n. +\end{equation} +The task here is to express \eqref{H-cycles} +in a form free of any $\hat x_i$, +$i=1,\dots,n$. The result also leads to the resolution of enumeration of +Hamiltonian paths in a graph. + +It is well known that the enumeration of Hamiltonian cycles and paths in +a complete graph $K_n$ and in a complete bipartite graph $K_{n_1n_2}$ +can only be found from \textit{first combinatorial principles} +\cite{hapa:graphenum}. One wonders if there exists a formula which can +be used very efficiently to produce $K_n$ and $K_{n_1n_2}$. Recently, +using Lagrangian methods, Goulden and Jackson have shown that $H_c$ can +be expressed in terms of the determinant and permanent of the adjacency +matrix \cite{gouja:lagrmeth}. However, the formula of Goulden and +Jackson determines neither $K_n$ nor $K_{n_1n_2}$ effectively. In this +paper, using an algebraic method, we parametrize the adjacency matrix. +The resulting formula also involves the determinant and permanent, but +it can easily be applied to $K_n$ and $K_{n_1n_2}$. In addition, we +eliminate the permanent from $H_c$ and show that $H_c$ can be +represented by a determinantal function of multivariables, each variable +with domain $\{0,1\}$. Furthermore, we show that $H_c$ can be written by +number of spanning trees of subgraphs. Finally, we apply the formulas to +a complete multigraph $K_{n_1\dots n_p}$. + +The conditions $a_{ij}=a_{ji}$, $i,j=1,\dots,n$, are not required in +this paper. All formulas can be extended to a digraph simply by +multiplying $H_c$ by 2. + +\section{Main Theorem} +\label{s:mt} + +\begin{notation} For $p,q\in P$ and $n\in\omega$ we write +$(q,n)\le(p,n)$ if $q\le p$ and $A_{q,n}=A_{p,n}$. +\begin{verbatim} +\begin{notation} For $p,q\in P$ and $n\in\omega$ +... +\end{notation} +\end{verbatim} +\end{notation} + +Let $\mathbf{B}=(b_{ij})$ be an $n\times n$ matrix. Let $\mathbf{n}=\{1, +\dots,n\}$. Using the properties of \eqref{multdef}, it is readily seen +that + +\begin{lem}\label{lem-per} +\begin{equation} +\prod_{i\in\mathbf{n}} +\biggl(\sum_{\,j\in\mathbf{n}}b_{ij}\hat x_i\biggr) +=\biggl(\prod_{\,i\in\mathbf{n}}\hat x_i\biggr)\per \mathbf{B} +\end{equation} +where $\per \mathbf{B}$ is the permanent of $\mathbf{B}$. +\end{lem} + +Let $\wh Y=\{\hat y_1,\dots,\hat y_n\}$. Define multiplication +for the elements of $\wh Y$ by +\begin{equation} +\hat y_i\hat y_j+\hat y_j\hat y_i=0,\quad i,j=1,\dots,n. +\end{equation} +Then, it follows that +\begin{lem}\label{lem-det} +\begin{equation}\label{detprod} +\prod_{i\in\mathbf{n}} +\biggl(\sum_{\,j\in\mathbf{n}}b_{ij}\hat y_j\biggr) +=\biggl(\prod_{\,i\in\mathbf{n}}\hat y_i\biggr)\det\mathbf{B}. +\end{equation} +\end{lem} + +Note that all basic properties of determinants are direct consequences +of Lemma~\ref{lem-det}. Write +\begin{equation}\label{sum-bij} +\sum_{j\in\mathbf{n}}b_{ij}\hat y_j=\sum_{j\in\mathbf{n}}b^{(\lambda)} +_{ij}\hat y_j+(b_{ii}-\lambda_i)\hat y_i\hat y +\end{equation} +where +\begin{equation} +b^{(\lambda)}_{ii}=\lambda_i,\quad b^{(\lambda)}_{ij}=b_{ij}, +\quad i\not=j. +\end{equation} +Let $\mathbf{B}^{(\lambda)}=(b^{(\lambda)}_{ij})$. By \eqref{detprod} +and \eqref{sum-bij}, it is +straightforward to show the following +result: +\begin{thm}\label{thm-main} +\begin{equation}\label{detB} +\det\mathbf{B}= +\sum^n_{l =0}\sum_{I_l \subseteq n} +\prod_{i\in I_l}(b_{ii}-\lambda_i) +\det\mathbf{B}^{(\lambda)}(I_l |I_l ), +\end{equation} +where $I_l =\{i_1,\dots,i_l \}$ and $\mathbf{B}^{(\lambda)}(I_l |I_l )$ +is the principal submatrix obtained from $\mathbf{B}^{(\lambda)}$ +by deleting its $i_1,\dots,i_l $ rows and columns. +\end{thm} + +\begin{rem} +Let $\mathbf{M}$ be an $n\times n$ matrix. The convention +$\mathbf{M}(\mathbf{n}|\mathbf{n})=1$ has been used in \eqref{detB} and +hereafter. +\end{rem} + +Before proceeding with our discussion, we pause to note that +\thmref{thm-main} yields immediately a fundamental formula which can be +used to compute the coefficients of a characteristic polynomial +\cite{mami:matrixth}: +\begin{cor}\label{BI} +Write $\det(\mathbf{B}-x\mathbf{I})=\sum^n_{l =0}(-1) +^l b_l x^l $. Then +\begin{equation}\label{bl-sum} +b_l =\sum_{I_l \subseteq\mathbf{n}}\det\mathbf{B}(I_l |I_l ). +\end{equation} +\end{cor} +Let +\begin{equation} +\mathbf{K}(t,t_1,\dots,t_n) +=\begin{pmatrix} D_1t&-a_{12}t_2&\dots&-a_{1n}t_n\\ +-a_{21}t_1&D_2t&\dots&-a_{2n}t_n\\ +\hdotsfor[2]{4}\\ +-a_{n1}t_1&-a_{n2}t_2&\dots&D_nt\end{pmatrix}, +\end{equation} +\begin{verbatim} +\begin{pmatrix} D_1t&-a_{12}t_2&\dots&-a_{1n}t_n\\ +-a_{21}t_1&D_2t&\dots&-a_{2n}t_n\\ +\hdotsfor[2]{4}\\ +-a_{n1}t_1&-a_{n2}t_2&\dots&D_nt\end{pmatrix} +\end{verbatim} +where +\begin{equation} +D_i=\sum_{j\in\mathbf{n}}a_{ij}t_j,\quad i=1,\dots,n. +\end{equation} + +Set +\begin{equation*} +D(t_1,\dots,t_n)=\frac{\delta}{\delta t}\eval{\det\mathbf{K}(t,t_1,\dots,t_n) +}_{t=1}. +\end{equation*} +Then +\begin{equation}\label{sum-Di} +D(t_1,\dots,t_n) +=\sum_{i\in\mathbf{n}}D_i\det\mathbf{K}(t=1,t_1,\dots,t_n; i|i), +\end{equation} +where $\mathbf{K}(t=1,t_1,\dots,t_n; i|i)$ is the $i$th principal +submatrix of $\mathbf{K}(t=1,t_1,\dots,t_n)$. + +Theorem~\ref{thm-main} leads to +\begin{equation}\label{detK1} +\det\mathbf{K}(t_1,t_1,\dots,t_n) +=\sum_{I\in\mathbf{n}}(-1)^{\envert{I}}t^{n-\envert{I}} +\prod_{i\in I}t_i\prod_{j\in I}(D_j+\lambda_jt_j)\det\mathbf{A} +^{(\lambda t)}(\overline{I}|\overline I). +\end{equation} +Note that +\begin{equation}\label{detK2} +\det\mathbf{K}(t=1,t_1,\dots,t_n)=\sum_{I\in\mathbf{n}}(-1)^{\envert{I}} +\prod_{i\in I}t_i\prod_{j\in I}(D_j+\lambda_jt_j)\det\mathbf{A} +^{(\lambda)}(\overline{I}|\overline{I})=0. +\end{equation} + +Let $t_i=\hat x_i,i=1,\dots,n$. Lemma~\ref{lem-per} yields +\begin{multline} +\biggl(\sum_{\,i\in\mathbf{n}}a_{l _i}x_i\biggr) +\det\mathbf{K}(t=1,x_1,\dots,x_n;l |l )\\ +=\biggl(\prod_{\,i\in\mathbf{n}}\hat x_i\biggr) +\sum_{I\subseteq\mathbf{n}-\{l \}} +(-1)^{\envert{I}}\per\mathbf{A}^{(\lambda)}(I|I) +\det\mathbf{A}^{(\lambda)} +(\overline I\cup\{l \}|\overline I\cup\{l \}). +\label{sum-ali} +\end{multline} +\begin{verbatim} +\begin{multline} +\biggl(\sum_{\,i\in\mathbf{n}}a_{l _i}x_i\biggr) +\det\mathbf{K}(t=1,x_1,\dots,x_n;l |l )\\ +=\biggl(\prod_{\,i\in\mathbf{n}}\hat x_i\biggr) +\sum_{I\subseteq\mathbf{n}-\{l \}} +(-1)^{\envert{I}}\per\mathbf{A}^{(\lambda)}(I|I) +\det\mathbf{A}^{(\lambda)} +(\overline I\cup\{l \}|\overline I\cup\{l \}). +\label{sum-ali} +\end{multline} +\end{verbatim} + +By \eqref{H-cycles}, \eqref{detprod}, and \eqref{sum-bij}, we have +\begin{prop}\label{prop:eg} +\begin{equation} +H_c=\frac1{2n}\sum^n_{l =0}(-1)^{l} +D_{l}, +\end{equation} +where +\begin{equation}\label{delta-l} +D_{l}=\eval[2]{\sum_{I_{l}\subseteq \mathbf{n}} +D(t_1,\dots,t_n)}_{t_i=\left\{\begin{smallmatrix} +0,& \text{if }i\in I_{l}\quad\\% \quad added for centering +1,& \text{otherwise}\end{smallmatrix}\right.\;,\;\; i=1,\dots,n}. +\end{equation} +\end{prop} + +\section{Application} +\label{lincomp} + +We consider here the applications of Theorems~\ref{th-info-ow-ow} +and~\ref{th-weak-ske-owf} to a complete +multipartite graph $K_{n_1\dots n_p}$. It can be shown that the +number of spanning trees of $K_{n_1\dots n_p}$ +may be written +\begin{equation}\label{e:st} +T=n^{p-2}\prod^p_{i=1} +(n-n_i)^{n_i-1} +\end{equation} +where +\begin{equation} +n=n_1+\dots+n_p. +\end{equation} + +It follows from Theorems~\ref{th-info-ow-ow} and~\ref{th-weak-ske-owf} that +\begin{equation}\label{e:barwq} +\begin{split} +H_c&=\frac1{2n} +\sum^n_{{l}=0}(-1)^{l}(n-{l})^{p-2} +\sum_{l _1+\dots+l _p=l}\prod^p_{i=1} +\binom{n_i}{l _i}\\ +&\quad\cdot[(n-l )-(n_i-l _i)]^{n_i-l _i}\cdot +\biggl[(n-l )^2-\sum^p_{j=1}(n_i-l _i)^2\biggr].\end{split} +\end{equation} +\begin{verbatim} +... \binom{n_i}{l _i}\\ +\end{verbatim} +and +\begin{equation}\label{joe} +\begin{split} +H_c&=\frac12\sum^{n-1}_{l =0} +(-1)^{l}(n-l )^{p-2} +\sum_{l _1+\dots+l _p=l} +\prod^p_{i=1}\binom{n_i}{l _i}\\ +&\quad\cdot[(n-l )-(n_i-l _i)]^{n_i-l _i} +\left(1-\frac{l _p}{n_p}\right) +[(n-l )-(n_p-l _p)]. +\end{split} +\end{equation} + +The enumeration of $H_c$ in a $K_{n_1\dotsm n_p}$ graph can also be +carried out by Theorem~\ref{thm-H-param} or~\ref{thm-asym} +together with the algebraic method of \eqref{multdef}. +Some elegant representations may be obtained. For example, $H_c$ in +a $K_{n_1n_2n_3}$ graph may be written +\begin{equation}\label{j:mark} +\begin{split} +H_c=& +\frac{n_1!\,n_2!\,n_3!} +{n_1+n_2+n_3}\sum_i\left[\binom{n_1}{i} +\binom{n_2}{n_3-n_1+i}\binom{n_3}{n_3-n_2+i}\right.\\ +&+\left.\binom{n_1-1}{i} +\binom{n_2-1}{n_3-n_1+i} +\binom{n_3-1}{n_3-n_2+i}\right].\end{split} +\end{equation} + +\section{Secret Key Exchanges} +\label{SKE} + +Modern cryptography is fundamentally concerned with the problem of +secure private communication. A Secret Key Exchange is a protocol +where Alice and Bob, having no secret information in common to start, +are able to agree on a common secret key, conversing over a public +channel. The notion of a Secret Key Exchange protocol was first +introduced in the seminal paper of Diffie and Hellman +\cite{dihe:newdir}. \cite{dihe:newdir} presented a concrete +implementation of a Secret Key Exchange protocol, dependent on a +specific assumption (a variant on the discrete log), specially +tailored to yield Secret Key Exchange. Secret Key Exchange is of +course trivial if trapdoor permutations exist. However, there is no +known implementation based on a weaker general assumption. + +The concept of an informationally one-way function was introduced +in \cite{imlelu:oneway}. We give only an informal definition here: + +\begin{defn} A polynomial time +computable function $f = \{f_k\}$ is informationally +one-way if there is no probabilistic polynomial time algorithm which +(with probability of the form $1 - k^{-e}$ for some $e > 0$) +returns on input $y \in \{0,1\}^{k}$ a random element of $f^{-1}(y)$. +\end{defn} +In the non-uniform setting \cite{imlelu:oneway} show that these are not +weaker than one-way functions: +\begin{thm}[\cite{imlelu:oneway} (non-uniform)] +\label{th-info-ow-ow} +The existence of informationally one-way functions +implies the existence of one-way functions. +\end{thm} +We will stick to the convention introduced above of saying +``non-uniform'' before the theorem statement when the theorem +makes use of non-uniformity. It should be understood that +if nothing is said then the result holds for both the uniform and +the non-uniform models. + +It now follows from \thmref{th-info-ow-ow} that + +\begin{thm}[non-uniform]\label{th-weak-ske-owf} Weak SKE +implies the existence of a one-way function. +\end{thm} + +More recently, the polynomial-time, interior point algorithms for linear +programming have been extended to the case of convex quadratic programs +\cite{moad:quadpro,ye:intalg}, certain linear complementarity problems +\cite{komiyo:lincomp,miyoki:lincomp}, and the nonlinear complementarity +problem \cite{komiyo:unipfunc}. The connection between these algorithms +and the classical Newton method for nonlinear equations is well +explained in \cite{komiyo:lincomp}. + +\section{Review} +\label{computation} + +We begin our discussion with the following definition: + +\begin{defn} + +A function $H\colon \Re^n \to \Re^n$ is said to be +\emph{B-differentiable} at the point $z$ if (i)~$H$ is Lipschitz +continuous in a neighborhood of $z$, and (ii)~there exists a positive +homogeneous function $BH(z)\colon \Re^n \to \Re^n$, called the +\emph{B-derivative} of $H$ at $z$, such that +\[ \lim_{v \to 0} \frac{H(z+v) - H(z) - BH(z)v}{\enVert{v}} = 0. \] +The function $H$ is \textit{B-differentiable in set $S$} if it is +B-differentiable at every point in $S$. The B-derivative $BH(z)$ is said +to be \textit{strong} if +\[ \lim_{(v,v') \to (0,0)} \frac{H(z+v) - H(z+v') - BH(z)(v + -v')}{\enVert{v - v'}} = 0. \] +\end{defn} + + +\begin{lem}\label{limbog} There exists a smooth function $\psi_0(z)$ +defined for $\abs{z}>1-2a$ satisfying the following properties\textup{:} +\begin{enumerate} +\renewcommand{\labelenumi}{(\roman{enumi})} +\item $\psi_0(z)$ is bounded above and below by positive constants +$c_1\leq \psi_0(z)\leq c_2$. +\item If $\abs{z}>1$, then $\psi_0(z)=1$. +\item For all $z$ in the domain of $\psi_0$, $\Delta_0\ln \psi_0\geq 0$. +\item If $1-2a<\abs{z}<1-a$, then $\Delta_0\ln \psi_0\geq +c_3>0$. +\end{enumerate} +\end{lem} + +\begin{proof} +We choose $\psi_0(z)$ to be a radial function depending only on $r=\abs{z}$. +Let $h(r)\geq 0$ be a suitable smooth function satisfying $h(r)\geq c_3$ +for $1-2a<\abs{z}<1-a$, and $h(r)=0$ for $\abs{z}>1-\tfrac a2$. The radial +Laplacian +\[\Delta_0\ln\psi_0(r)=\left(\frac {d^2}{dr^2}+\frac +1r\frac d{dr}\right)\ln\psi_0(r)\] +has smooth coefficients for $r>1-2a$. Therefore, we may +apply the existence and uniqueness theory for ordinary differential +equations. Simply let $\ln \psi_0(r)$ be the solution of the differential +equation +\[\left(\frac{d^2}{dr^2}+\frac 1r\frac d{dr}\right)\ln \psi_0(r)=h(r)\] +with initial conditions given by $\ln \psi_0(1)=0$ and +$\ln\psi_0'(1)=0$. + +Next, let $D_\nu$ be a finite collection of pairwise disjoint disks, +all of which are contained in the unit disk centered at the origin in +$C$. We assume that $D_\nu=\{z\mid \abs{z-z_\nu}<\delta\}$. Suppose that +$D_\nu(a)$ denotes the smaller concentric disk $D_\nu(a)=\{z\mid +\abs{z-z_\nu}\leq (1-2a)\delta\}$. We define a smooth weight function +$\Phi_0(z)$ for $z\in C-\bigcup_\nu D_\nu(a)$ by setting $\Phi_ +0(z)=1$ when $z\notin \bigcup_\nu D_\nu$ and $\Phi_ +0(z)=\psi_0((z-z_\nu)/\delta)$ when $z$ is an element of $D_\nu$. It +follows from \lemref{limbog} that $\Phi_ 0$ satisfies the properties: +\begin{enumerate} +\renewcommand{\labelenumi}{(\roman{enumi})} +\item \label{boundab}$\Phi_ 0(z)$ is bounded above and below by +positive constants $c_1\leq \Phi_ 0(z)\leq c_2$. +\item \label{d:over}$\Delta_0\ln\Phi_ 0\geq 0$ for all +$z\in C-\bigcup_\nu D_\nu(a)$, +the domain where the function $\Phi_ 0$ is defined. +\item \label{d:ad}$\Delta_0\ln\Phi_ 0\geq c_3\delta^{-2}$ +when $(1-2a)\delta<\abs{z-z_\nu}<(1-a)\delta$. +\end{enumerate} +Let $A_\nu$ denote the annulus $A_\nu=\{(1-2a)\delta<\abs{z-z_\nu}<(1-a) +\delta \}$, and set $A=\bigcup_\nu A_\nu$. The +properties (\ref{d:over}) and (\ref{d:ad}) of $\Phi_ 0$ +may be summarized as $\Delta_0\ln \Phi_ 0\geq c_3\delta^{-2}\chi_A$, +where $\chi _A$ is the characteristic function of $A$. +\end{proof} + +Suppose that $\alpha$ is a nonnegative real constant. We apply +Proposition~\ref{prop:eg} with $\Phi(z)=\Phi_ 0(z) e^{\alpha\abs{z}^2}$. If +$u\in C^\infty_0(R^2-\bigcup_\nu D_\nu(a))$, assume that $\mathcal{D}$ +is a bounded domain containing the support of $u$ and $A\subset +\mathcal{D}\subset R^2-\bigcup_\nu D_\nu(a)$. A calculation gives +\[\int_{\mathcal{D}}\abs{\overline\partial u}^2\Phi_ 0(z) e^{\alpha\abs{z}^2} +\geq c_4\alpha\int_{\mathcal{D}}\abs{u}^2\Phi_ 0e^{\alpha\abs{z}^2} ++c_5\delta^{-2}\int_ A\abs{u}^2\Phi_ 0e^{\alpha\abs{z}^2}.\] + +The boundedness, property (\ref{boundab}) of $\Phi_ 0$, then yields +\[\int_{\mathcal{D}}\abs{\overline\partial u}^2e^{\alpha\abs{z}^2}\geq c_6\alpha +\int_{\mathcal{D}}\abs{u}^2e^{\alpha\abs{z}^2} ++c_7\delta^{-2}\int_ A\abs{u}^2e^{\alpha\abs{z}^2}.\] + +Let $B(X)$ be the set of blocks of $\Lambda_{X}$ +and let $b(X) = \abs{B(X)}$. If $\phi \in Q_{X}$ then +$\phi$ is constant on the blocks of $\Lambda_{X}$. +\begin{equation}\label{far-d} + P_{X} = \{ \phi \in M \mid \Lambda_{\phi} = \Lambda_{X} \}, +\qquad +Q_{X} = \{\phi \in M \mid \Lambda_{\phi} \geq \Lambda_{X} \}. +\end{equation} +If $\Lambda_{\phi} \geq \Lambda_{X}$ then +$\Lambda_{\phi} = \Lambda_{Y}$ for some $Y \geq X$ so that +\[ Q_{X} = \bigcup_{Y \geq X} P_{Y}. \] +Thus by M\"obius inversion +\[ \abs{P_{Y}}= \sum_{X\geq Y} \mu (Y,X)\abs{Q_{X}}.\] +Thus there is a bijection from $Q_{X}$ to $W^{B(X)}$. +In particular $\abs{Q_{X}} = w^{b(X)}$. + +Next note that $b(X)=\dim X$. We see this by choosing a +basis for $X$ consisting of vectors $v^{k}$ defined by +\[v^{k}_{i}= +\begin{cases} 1 & \text{if $i \in \Lambda_{k}$},\\ +0 &\text{otherwise.} \end{cases} +\] +\begin{verbatim} +\[v^{k}_{i}= +\begin{cases} 1 & \text{if $i \in \Lambda_{k}$},\\ +0 &\text{otherwise.} \end{cases} +\] +\end{verbatim} + +\begin{lem}\label{p0201} +Let $\A$ be an arrangement. Then +\[ \chi (\A,t) = \sum_{\B \subseteq \A} +(-1)^{\abs{\B}} t^{\dim T(\B)}. \] +\end{lem} + +In order to compute $R''$ recall the definition +of $S(X,Y)$ from \lemref{lem-per}. Since $H \in \B$, +$\A_{H} \subseteq \B$. Thus if $T(\B) = Y$ then +$\B \in S(H,Y)$. Let $L'' = L(\A'')$. Then +\begin{equation}\label{E_SXgYy} +\begin{split} +R''&= \sum_{H\in \B \subseteq \A} (-1)^{\abs{\B}} +t^{\dim T(\B)}\\ +&= \sum_{Y \in L''} \sum_{\B \in S(H,Y)} +(-1)^{\abs{\B}}t^{\dim Y} \\ +&= -\sum_{Y \in L''} \sum_{\B \in S(H,Y)} (-1)^ +{\abs{\B - \A_{H}}} t^{\dim Y} \\ +&= -\sum_{Y \in L''} \mu (H,Y)t^{\dim Y} \\ +&= -\chi (\A '',t). +\end{split} +\end{equation} + +\begin{cor}\label{tripleA} +Let $(\A,\A',\A'')$ be a triple of arrangements. Then +\[ \pi (\A,t) = \pi (\A',t) + t \pi (\A'',t). \] +\end{cor} + +\begin{defn} +Let $(\A,\A',\A'')$ be a triple with respect to +the hyperplane $H \in \A$. Call $H$ a \textit{separator} +if $T(\A) \not\in L(\A')$. +\end{defn} + +\begin{cor}\label{nsep} +Let $(\A,\A',\A'')$ be a triple with respect to $H \in \A$. +\begin{enumerate} +\renewcommand{\labelenumi}{(\roman{enumi})} +\item +If $H$ is a separator then +\[ \mu (\A) = - \mu (\A'') \] +and hence +\[ \abs{\mu (\A)} = \abs{ \mu (\A'')}. \] + +\item If $H$ is not a separator then +\[\mu (\A) = \mu (\A') - \mu (\A'') \] +and +\[ \abs{\mu (\A)} = \abs{\mu (\A')} + \abs{\mu (\A'')}. \] +\end{enumerate} +\end{cor} + +\begin{proof} +It follows from \thmref{th-info-ow-ow} that $\pi(\A,t)$ +has leading term +\[(-1)^{r(\A)}\mu (\A)t^{r(\A)}.\] +The conclusion +follows by comparing coefficients of the leading +terms on both sides of the equation in +Corollary~\ref{tripleA}. If $H$ is a separator then +$r(\A') < r(\A)$ and there is no contribution +from $\pi (\A',t)$. +\end{proof} + +The Poincar\'e polynomial of an arrangement +will appear repeatedly +in these notes. It will be shown to equal the +Poincar\'e polynomial +of the graded algebras which we are going to +associate with $\A$. It is also the Poincar\'e +polynomial of the complement $M(\A)$ for a +complex arrangement. Here we prove +that the Poincar\'e polynomial is the chamber +counting function for a real arrangement. The +complement $M(\A)$ is a disjoint union of chambers +\[M(\A) = \bigcup_{C \in \Cham(\A)} C.\] +The number +of chambers is determined by the Poincar\'e +polynomial as follows. + +\begin{thm}\label{th-realarr} +Let $\A_{\mathbf{R}}$ be a real arrangement. Then +\[ \abs{\Cham(\A_{\mathbf{R}})} = \pi (\A_{\mathbf{R}},1). \] +\end{thm} + +\begin{proof} +We check the properties required in Corollary~\ref{nsep}: +(i) follows from $\pi (\Phi_{ l},t) = 1$, and (ii) is a +consequence of Corollary~\ref{BI}. +\end{proof} + +\begin{figure} +\vspace{5cm} +\caption[]{$Q(\A_{1}) = xyz(x-z)(x+z)(y-z)(y+z)$} +\end{figure} + +\begin{figure} +\vspace{5cm} +\caption[]{$Q(\A_{2})= xyz(x+y+z)(x+y-z)(x-y+z)(x-y-z)$} +\end{figure} + + +\begin{thm} +\label{T_first_the_int} +Let $\phi$ be a protocol for a random pair $\XcY$. +If one of $\st_\phi(x',y)$ and $\st_\phi(x,y')$ is a prefix of the other +and $(x,y)\in\SXY$, then +\[ +\langle \st_j(x',y)\rangle_{j=1}^\infty +=\langle \st_j(x,y)\rangle_{j=1}^\infty +=\langle \st_j(x,y')\rangle_{j=1}^\infty . +\] +\end{thm} +\begin{proof} +We show by induction on $i$ that +\[ +\langle \st_j(x',y)\rangle_{j=1}^i +=\langle \st_j(x,y)\rangle_{j=1}^i +=\langle \st_j(x,y')\rangle_{j=1}^i. +\] +The induction hypothesis holds vacuously for $i=0$. Assume it holds for +$i-1$, in particular +$[\st_j(x',y)]_{j=1}^{i-1}=[\st_j(x,y')]_{j=1}^{i-1}$. Then one of +$[\st_j(x',y)]_{j=i}^{\infty}$ and $[\st_j(x,y')]_{j=i}^{\infty}$ is a +prefix of the other which implies that one of $\st_i(x',y)$ and +$\st_i(x,y')$ is a prefix of the other. If the $i$th message is +transmitted by $P_\X$ then, by the separate-transmissions property and +the induction hypothesis, $\st_i(x,y)=\st_i(x,y')$, hence one of +$\st_i(x,y)$ and $\st_i(x',y)$ is a prefix of the other. By the +implicit-termination property, neither $\st_i(x,y)$ nor $\st_i(x',y)$ +can be a proper prefix of the other, hence they must be the same and +$\st_i(x',y)=\st_i(x,y)=\st_i(x,y')$. If the $i$th message is +transmitted by $\PY$ then, symmetrically, $\st_i(x,y)=\st_i(x',y)$ by +the induction hypothesis and the separate-transmissions property, and, +then, $\st_i(x,y)=\st_i(x,y')$ by the implicit-termination property, +proving the induction step. +\end{proof} + +If $\phi$ is a protocol for $(X,Y)$, and $(x,y)$, $(x',y)$ are distinct +inputs in $\SXY$, then, by the correct-decision property, +$\langle\st_j(x,y)\rangle_{j=1}^\infty\ne\langle +\st_j(x',y)\rangle_{j=1}^\infty$. + +Equation~(\ref{E_SXgYy}) defined $\PY$'s ambiguity set $\SXgYy$ +to be the set of possible $X$ values when $Y=y$. +The last corollary implies that for all $y\in\SY$, +the multiset% +\footnote{A multiset allows multiplicity of elements. +Hence, $\{0,01,01\}$ is prefix free as a set, but not as a multiset.} +of codewords $\{\st_\phi(x,y):x\in\SXgYy\}$ is prefix free. + +\section{One-Way Complexity} +\label{S_Cp1} + +$\Cw1$, the one-way complexity of a random pair $\XcY$, +is the number of bits $P_\X$ must transmit in the worst case +when $\PY$ is not permitted to transmit any feedback messages. +Starting with $\SXY$, the support set of $\XcY$, we define $\G$, +the \textit{characteristic hypergraph} of $\XcY$, and show that +\[ +\Cw1=\lceil\,\log\chi(\G)\rceil\ . +\] + +Let $\XcY$ be a random pair. For each $y$ in $\SY$, the support set of +$Y$, Equation~(\ref{E_SXgYy}) defined $\SXgYy$ to be the set of possible +$x$ values when $Y=y$. The \textit{characteristic hypergraph} $\G$ of +$\XcY$ has $\SX$ as its vertex set and the hyperedge $\SXgYy$ for each +$y\in\SY$. + + +We can now prove a continuity theorem. +\begin{thm}\label{t:conl} +Let $\Omega \subset\mathbf{R}^n$ be an open set, let +$u\in BV(\Omega ;\mathbf{R}^m)$, and let +\begin{equation}\label{quts} +T^u_x=\left\{y\in\mathbf{R}^m: + y=\tilde u(x)+\left\langle \frac{Du}{\abs{Du}}(x),z +\right\rangle \text{ for some }z\in\mathbf{R}^n\right\} +\end{equation} +for every $x\in\Omega \backslash S_u$. Let $f\colon \mathbf{R}^m\to +\mathbf{R}^k$ be a Lipschitz continuous function such that $f(0)=0$, and +let $v=f(u)\colon \Omega \to \mathbf{R}^k$. Then $v\in BV(\Omega +;\mathbf{R}^k)$ and +\begin{equation} +Jv=\eval{(f(u^+)-f(u^-))\otimes \nu_u\cdot\, +\mathcal{H}_{n-1}}_{S_u}. +\end{equation} +In addition, for $\abs{\wt{D}u}$-almost every $x\in\Omega $ the +restriction of the function $f$ to $T^u_x$ is differentiable at $\tilde +u(x)$ and +\begin{equation} +\wt{D}v=\nabla (\eval{f}_{T^u_x})(\tilde u) +\frac{\wt{D}u}{\abs{\wt{D}u}}\cdot\abs{\wt{D}u}.\end{equation} +\end{thm} + +Before proving the theorem, we state without proof three elementary +remarks which will be useful in the sequel. +\begin{rem}\label{r:omb} +Let $\omega\colon \left]0,+\infty\right[\to \left]0,+\infty\right[$ +be a continuous function such that $\omega (t)\to 0$ as $t\to +0$. Then +\[\lim_{h\to 0^+}g(\omega(h))=L\Leftrightarrow\lim_{h\to +0^+}g(h)=L\] +for any function $g\colon \left]0,+\infty\right[\to \mathbf{R}$. +\end{rem} +\begin{rem}\label{r:dif} +Let $g \colon \mathbf{R}^n\to \mathbf{R}$ be a Lipschitz +continuous function and assume that +\[L(z)=\lim_{h\to 0^+}\frac{g(hz)-g(0)}h\] +exists for every $z\in\mathbf{Q}^n$ and that $L$ is a linear function of +$z$. Then $g$ is differentiable at 0. +\end{rem} +\begin{rem}\label{r:dif0} +Let $A \colon \mathbf{R}^n\to \mathbf{R}^m$ be a linear function, and +let $f \colon \mathbf{R}^m\to \mathbf{R}$ be a function. Then the +restriction of $f$ to the range of $A$ is differentiable at 0 if and +only if $f(A)\colon \mathbf{R}^n\to \mathbf{R}$ is differentiable at 0 +and +\[\nabla(\eval{f}_{\IM(A)})(0)A=\nabla (f(A))(0).\] +\end{rem} + +\begin{proof} + We begin by showing that $v\in BV(\Omega;\mathbf{R}^k)$ and +\begin{equation}\label{e:bomb} +\abs{Dv}(B)\le K\abs{Du}(B)\qquad\forall B\in\mathbf{B}(\Omega ), +\end{equation} +where $K>0$ is the Lipschitz constant of $f$. By \eqref{sum-Di} and by +the approximation result quoted in \secref{s:mt}, it is possible to find +a sequence $(u_h)\subset C^1(\Omega ;\mathbf{R}^m)$ converging to $u$ in +$L^1(\Omega ;\mathbf{R}^m)$ and such that +\[\lim_{h\to +\infty}\int_\Omega \abs{\nabla u_h}\,dx=\abs{Du}(\Omega ).\] +The functions $v_h=f(u_h)$ are locally Lipschitz continuous in $\Omega +$, and the definition of differential implies that $\abs{\nabla v_h}\le +K\abs{\nabla u_h}$ almost everywhere in $\Omega $. The lower semicontinuity +of the total variation and \eqref{sum-Di} yield +\begin{equation} +\begin{split} +\abs{Dv}(\Omega )\le\liminf_{h\to +\infty}\abs{Dv_h}(\Omega) & +=\liminf_{h\to +\infty}\int_\Omega \abs{\nabla v_h}\,dx\\ +&\le K\liminf_{h\to +\infty}\int_\Omega +\abs{\nabla u_h}\,dx=K\abs{Du}(\Omega). +\end{split}\end{equation} +Since $f(0)=0$, we have also +\[\int_\Omega \abs{v}\,dx\le K\int_\Omega \abs{u}\,dx;\] +therefore $u\in BV(\Omega ;\mathbf{R}^k)$. Repeating the same argument +for every open set $A\subset\Omega $, we get \eqref{e:bomb} for every +$B\in\mathbf{B}(\Omega)$, because $\abs{Dv}$, $\abs{Du}$ are Radon measures. To +prove \lemref{limbog}, first we observe that +\begin{equation}\label{e:SS} +S_v\subset S_u,\qquad\tilde v(x)=f(\tilde u(x))\qquad \forall x\in\Omega +\backslash S_u.\end{equation} +In fact, for every $\varepsilon >0$ we have +\[\{y\in B_\rho(x): \abs{v(y)-f(\tilde u(x))}>\varepsilon \}\subset \{y\in +B_\rho(x): \abs{u(y)-\tilde u(x)}>\varepsilon /K\},\] +hence +\[\lim_{\rho\to 0^+}\frac{\abs{\{y\in B_\rho(x): \abs{v(y)-f(\tilde u(x))}> +\varepsilon \}}}{\rho^n}=0\] +whenever $x\in\Omega \backslash S_u$. By a similar argument, if $x\in +S_u$ is a point such that there exists a triplet $(u^+,u^-,\nu_u)$ +satisfying \eqref{detK1}, \eqref{detK2}, then +\[ +(v^+(x)-v^-(x))\otimes \nu_v=(f(u^+(x))-f(u^-(x)))\otimes\nu_u\quad +\text{if }x\in S_v +\] +and $f(u^-(x))=f(u^+(x))$ if $x\in S_u\backslash S_v$. Hence, by (1.8) +we get +\begin{equation*}\begin{split} +Jv(B)=\int_{B\cap S_v}(v^+-v^-)\otimes \nu_v\,d\mathcal{H}_{n-1}&= +\int_{B\cap S_v}(f(u^+)-f(u^-))\otimes \nu_u\,d\mathcal{H}_{n-1}\\ +&=\int_{B\cap S_u}(f(u^+)-f(u^-))\otimes \nu_u\,d\mathcal{H}_{n-1} +\end{split}\end{equation*} +and \lemref{limbog} is proved. +\end{proof} + +To prove \eqref{e:SS}, it is not restrictive to assume that $k=1$. +Moreover, to simplify our notation, from now on we shall assume that +$\Omega = \mathbf{R}^n$. The proof of \eqref{e:SS} is divided into two +steps. In the first step we prove the statement in the one-dimensional +case $(n=1)$, using \thmref{th-weak-ske-owf}. In the second step we +achieve the general result using \thmref{t:conl}. + +\subsection*{Step 1} +Assume that $n=1$. Since $S_u$ is at most countable, \eqref{sum-bij} +yields that $\abs{\wt{D}v}(S_u\backslash S_v)=0$, so that +\eqref{e:st} and \eqref{e:barwq} imply that $Dv=\wt{D}v+Jv$ is +the Radon-Nikod\'ym decomposition of $Dv$ in absolutely continuous and +singular part with respect to $\abs{\wt{D} u}$. By +\thmref{th-weak-ske-owf}, we have +\begin{equation*} +\frac{\wt{D}v}{\abs{\wt{D}u}}(t)=\lim_{s\to t^+} +\frac{Dv(\interval{\left[t,s\right[})} +{\abs{\wt{D}u}(\interval{\left[t,s\right[})},\qquad +\frac{\wt{D}u}{\abs{\wt{D}u}}(t)=\lim_{s\to t^+} +\frac{Du(\interval{\left[t,s\right[})} +{\abs{\wt{D}u}(\interval{\left[t,s\right[})} +\end{equation*} +$\abs{\wt{D}u}$-almost everywhere in $\mathbf{R}$. It is well known +(see, for instance, \cite[2.5.16]{ste:sint}) that every one-dimensional +function of bounded variation $w$ has a unique left continuous +representative, i.e., a function $\hat w$ such that $\hat w=w$ almost +everywhere and $\lim_{s\to t^-}\hat w(s)=\hat w(t)$ for every $t\in +\mathbf{R}$. These conditions imply +\begin{equation} +\hat u(t)=Du(\interval{\left]-\infty,t\right[}), +\qquad \hat v(t)=Dv(\interval{\left]-\infty,t\right[})\qquad +\forall t\in\mathbf{R} +\end{equation} +and +\begin{equation}\label{alimo} +\hat v(t)=f(\hat u(t))\qquad\forall t\in\mathbf{R}.\end{equation} +Let $t\in\mathbf{R}$ be such that +$\abs{\wt{D}u}(\interval{\left[t,s\right[})>0$ for every $s>t$ and +assume that the limits in \eqref{joe} exist. By \eqref{j:mark} and +\eqref{far-d} we get +\begin{equation*}\begin{split} +\frac{\hat v(s)-\hat +v(t)}{\abs{\wt{D}u}(\interval{\left[t,s\right[})}&=\frac {f(\hat +u(s))-f(\hat u(t))}{\abs{\wt{D}u}(\interval{\left[t,s\right[})}\\ +&=\frac{f(\hat u(s))-f(\hat +u(t)+\dfrac{\wt{D}u}{\abs{\wt{D}u}}(t)\abs{\wt{D}u +}(\interval{\left[t,s\right[}))}% +{\abs{\wt{D}u}(\interval{\left[t,s\right[})}\\ +&+\frac +{f(\hat u(t)+\dfrac{\wt{D}u}{\abs{\wt{D}u}}(t)\abs{\wt{D} +u}(\interval{\left[t,s\right[}))-f(\hat +u(t))}{\abs{\wt{D}u}(\interval{\left[t,s\right[})} +\end{split}\end{equation*} +for every $s>t$. Using the Lipschitz condition on $f$ we find +{\setlength{\multlinegap}{0pt} +\begin{multline*} +\left\lvert\frac{\hat v(s)-\hat +v(t)}{\abs{\wt{D}u}(\interval{\left[t,s\right[})} -\frac{f(\hat +u(t)+\dfrac{\wt{D}u}{\abs{\wt{D}u}}(t) +\abs{\wt{D}u}(\interval{\left[t,s\right[}))-f(\hat +u(t))}{\abs{\wt{D}u}(\interval{\left[t,s\right[})}\right\rvert\\ +\le K\left\lvert +\frac{\hat u(s)-\hat u(t)} + {\abs{\wt{D}u}(\interval{\left[t,s\right[})} +-\frac{\wt{D}u}{\abs{ +\wt{D}u}}(t)\right\rvert.\end{multline*} +}% end of group with \multlinegap=0pt +By \eqref{e:bomb}, the function $s\to +\abs{\wt{D}u}(\interval{\left[t,s\right[})$ is continuous and +converges to 0 as $s\downarrow t$. Therefore Remark~\ref{r:omb} and the +previous inequality imply +\[\frac{\wt{D}v}{\abs{\wt{D}u}}(t)=\lim_{h\to 0^+} +\frac{f(\hat u(t)+h\dfrac{\wt{D}u}{\abs{\wt{D}u}} +(t))-f(\hat u(t))}h\quad\abs{\wt{D}u}\text{-a.e. in }\mathbf{R}.\] +By \eqref{joe}, $\hat u(x)=\tilde u(x)$ for every +$x\in\mathbf{R}\backslash S_u$; moreover, applying the same argument to +the functions $u'(t)=u(-t)$, $v'(t)=f(u'(t))=v(-t)$, we get +\[\frac{\wt{D}v}{\abs{\wt{D}u}}(t)=\lim_{h\to 0} +\frac{f(\tilde u(t) ++h\dfrac{\wt{D}u}{\abs{\wt{D}u}}(t))-f(\tilde u(t))}{h} +\qquad\abs{\wt{D}u}\text{-a.e. in }\mathbf{R}\] +and our statement is proved. + +\subsection*{Step 2} + +Let us consider now the general case $n>1$. Let $\nu\in \mathbf{R}^n$ be +such that $\abs{\nu}=1$, and let $\pi_\nu=\{y\in\mathbf{R}^n: \langle +y,\nu\rangle =0\}$. In the following, we shall identify $\mathbf{R}^n$ +with $\pi_\nu\times\mathbf{R}$, and we shall denote by $y$ the variable +ranging in $\pi_\nu$ and by $t$ the variable ranging in $\mathbf{R}$. By +the just proven one-dimensional result, and by \thmref{thm-main}, we get +\[\lim_{h\to 0}\frac{f(\tilde u(y+t\nu)+h\dfrac{\wt{D}u_y}{\abs{ +\wt{D}u_y}}(t))-f(\tilde u(y+t\nu))}h=\frac{\wt{D}v_y}{\abs{ +\wt{D}u_y}}(t)\qquad\abs{\wt{D}u_y}\text{-a.e. in }\mathbf{R}\] +for $\mathcal{H}_{n-1}$-almost every $y\in \pi_\nu$. We claim that +\begin{equation} +\frac{\langle \wt{D}u,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle +}}(y+t\nu)=\frac{\wt{D}u_y} +{\abs{\wt{D}u_y}}(t)\qquad\abs{\wt{D}u_y}\text{-a.e. in }\mathbf{R} +\end{equation} +for $\mathcal{H}_{n-1}$-almost every $y\in\pi_\nu$. In fact, by +\eqref{sum-ali} and \eqref{delta-l} we get +\begin{multline*} +\int_{\pi_\nu}\frac{\wt{D}u_y}{\abs{\wt{D}u_y}}\cdot\abs{\wt{D}u_y +}\,d\mathcal{H}_{n-1}(y)=\int_{\pi_\nu}\wt{D}u_y\,d\mathcal{H}_{n-1}(y)\\ +=\langle \wt{D}u,\nu\rangle =\frac +{\langle \wt{D}u,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle}}\cdot +\abs{\langle \wt{D}u,\nu\rangle }=\int_{\pi_\nu}\frac{ +\langle \wt{D}u,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle }} +(y+\cdot \nu)\cdot\abs{\wt{D}u_y}\,d\mathcal{H}_{n-1}(y) +\end{multline*} +and \eqref{far-d} follows from \eqref{sum-Di}. By the same argument it +is possible to prove that +\begin{equation} +\frac{\langle \wt{D}v,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle +}}(y+t\nu)=\frac{\wt{D}v_y}{\abs{\wt{D}u_y}}(t)\qquad\abs{ +\wt{D}u_y}\text{-a.e. in }\mathbf{R}\end{equation} +for $\mathcal{H}_{n-1}$-almost every $y\in \pi_\nu$. By \eqref{far-d} +and \eqref{E_SXgYy} we get +\[ +\lim_{h\to 0}\frac{f(\tilde u(y+t\nu)+h\dfrac{\langle \wt{D} +u,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle }}(y+t\nu))-f(\tilde +u(y+t\nu))}{h} +=\frac{\langle \wt{D}v,\nu\rangle }{\abs{\langle +\wt{D}u,\nu\rangle }}(y+t\nu)\] +for $\mathcal{H}_{n-1}$-almost every $y\in\pi_\nu$, and using again +\eqref{detK1}, \eqref{detK2} we get +\[ +\lim_{h\to 0}\frac{f(\tilde u(x)+h\dfrac{\langle +\wt{D}u,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle }}(x))-f(\tilde +u(x))}{h}=\frac{\langle \wt{D}v,\nu\rangle }{\abs{\langle \wt{D}u,\nu +\rangle }}(x) +\] +$\abs{\langle \wt{D}u,\nu\rangle}$-a.e. in $\mathbf{R}^n$. + +Since the function $\abs{\langle \wt{D}u,\nu\rangle }/\abs{\wt{D}u}$ +is strictly positive $\abs{\langle \wt{D}u,\nu\rangle }$-almost everywhere, +we obtain also +\begin{multline*} +\lim_{h\to 0}\frac{f(\tilde u(x)+h\dfrac{\abs{\langle +\wt{D}u,\nu\rangle }}{\abs{\wt{D}u}}(x)\dfrac{\langle \wt{D} +u,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle }}(x))-f(\tilde u(x))}{h}\\ +=\frac{\abs{\langle \wt{D}u,\nu\rangle }}{\abs{\wt{D}u}}(x)\frac +{\langle \wt{D}v,\nu\rangle }{\abs{\langle +\wt{D}u,\nu\rangle }}(x) +\end{multline*} +$\abs{\langle \wt{D}u,\nu\rangle }$-almost everywhere in $\mathbf{R}^n$. + +Finally, since +\begin{align*} +&\frac{\abs{\langle \wt{D}u,\nu\rangle }}{\abs{\wt{D}u}} +\frac{\langle \wt{D}u,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle}} +=\frac{\langle \wt{D}u,\nu\rangle }{\abs{\wt{D}u}} +=\left\langle \frac{\wt{D}u}{\abs{\wt{D}u}},\nu\right\rangle + \qquad\abs{\wt{D}u}\text{-a.e. in }\mathbf{R}^n\\ +&\frac{\abs{\langle \wt{D}u,\nu\rangle }}{\abs{\wt{D}u}} +\frac{\langle \wt{D}v,\nu\rangle }{\abs{\langle \wt{D}u,\nu\rangle}} +=\frac{\langle \wt{D}v,\nu\rangle }{\abs{\wt{D}u}} +=\left\langle \frac{\wt{D}v}{\abs{\wt{D}u}},\nu\right\rangle + \qquad\abs{\wt{D}u}\text{-a.e. in }\mathbf{R}^n +\end{align*} +and since both sides of \eqref{alimo} +are zero $\abs{\wt{D}u}$-almost everywhere +on $\abs{\langle \wt{D}u,\nu\rangle }$-negligible sets, we conclude that +\[ +\lim_{h\to 0}\frac{f\left( +\tilde u(x)+h\left\langle \dfrac{\wt{D} +u}{\abs{\wt{D}u}}(x),\nu\right\rangle \right)-f(\tilde u(x))}h +=\left\langle \frac{\wt{D}v}{\abs{\wt{D}u}}(x),\nu\right\rangle, +\] +$\abs{\wt{D}u}$-a.e. in $\mathbf{R}^n$. +Since $\nu$ is arbitrary, by Remarks \ref{r:dif} and~\ref{r:dif0} +the restriction of $f$ to +the affine space $T^u_x$ is differentiable at $\tilde u(x)$ for $\abs{\wt{D} +u}$-almost every $x\in \mathbf{R}^n$ and \eqref{quts} holds.\qed + +It follows from \eqref{sum-Di}, \eqref{detK1}, and \eqref{detK2} that +\begin{equation}\label{Dt} +D(t_1,\dots,t_n)=\sum_{I\in\mathbf{n}}(-1)^{\abs{I}-1}\abs{I} +\prod_{i\in I}t_i\prod_{j\in I}(D_j+\lambda_jt_j)\det\mathbf{A}^{(\lambda)} +(\overline I|\overline I). +\end{equation} +Let $t_i=\hat x_i$, $i=1,\dots,n$. Lemma 1 leads to +\begin{equation}\label{Dx} +D(\hat x_1,\dots,\hat x_n)=\prod_{i\in\mathbf{n}}\hat x_i +\sum_{I\in\mathbf{n}}(-1)^{\abs{I}-1}\abs{I}\per \mathbf{A} +^{(\lambda)}(I|I)\det\mathbf{A}^{(\lambda)}(\overline I|\overline I). +\end{equation} +By \eqref{H-cycles}, \eqref{sum-Di}, and \eqref{Dx}, +we have the following result: +\begin{thm}\label{thm-H-param} +\begin{equation}\label{H-param} +H_c=\frac{1}{2n}\sum^n_{l =1}l (-1)^{l -1}A_{l} +^{(\lambda)}, +\end{equation} +where +\begin{equation}\label{A-l-lambda} +A^{(\lambda)}_l =\sum_{I_l \subseteq\mathbf{n}}\per \mathbf{A} +^{(\lambda)}(I_l |I_l )\det\mathbf{A}^{(\lambda)} +(\overline I_{l}|\overline I_l ),\abs{I_{l}}=l . +\end{equation} +\end{thm} + +It is worth noting that $A_l ^{(\lambda)}$ of \eqref{A-l-lambda} is +similar to the coefficients $b_l $ of the characteristic polynomial of +\eqref{bl-sum}. It is well known in graph theory that the coefficients +$b_l $ can be expressed as a sum over certain subgraphs. It is +interesting to see whether $A_l $, $\lambda=0$, structural properties +of a graph. + +We may call \eqref{H-param} a parametric representation of $H_c$. In +computation, the parameter $\lambda_i$ plays very important roles. The +choice of the parameter usually depends on the properties of the given +graph. For a complete graph $K_n$, let $\lambda_i=1$, $i=1,\dots,n$. +It follows from \eqref{A-l-lambda} that +\begin{equation}\label{compl-gr} +A^{(1)}_l =\begin{cases} n!,&\text{if }l =1\\ +0,&\text{otherwise}.\end{cases} +\end{equation} +By \eqref{H-param} +\begin{equation} +H_c=\frac 12(n-1)!. +\end{equation} +For a complete bipartite graph $K_{n_1n_2}$, let $\lambda_i=0$, $i=1,\dots,n$. +By \eqref{A-l-lambda}, +\begin{equation} +A_l = +\begin{cases} -n_1!n_2!\delta_{n_1n_2},&\text{if }l =2\\ +0,&\text{otherwise }.\end{cases} +\label{compl-bip-gr} +\end{equation} +Theorem~\ref{thm-H-param} +leads to +\begin{equation} +H_c=\frac1{n_1+n_2}n_1!n_2!\delta_{n_1n_2}. +\end{equation} + +Now, we consider an asymmetrical approach. Theorem \ref{thm-main} leads to +\begin{multline} +\det\mathbf{K}(t=1,t_1,\dots,t_n;l |l )\\ +=\sum_{I\subseteq\mathbf{n}-\{l \}} +(-1)^{\abs{I}}\prod_{i\in I}t_i\prod_{j\in I} +(D_j+\lambda_jt_j)\det\mathbf{A}^{(\lambda)} +(\overline I\cup\{l \}|\overline I\cup\{l \}). +\end{multline} + +By \eqref{H-cycles} and \eqref{sum-ali} we have the following asymmetrical +result: +\begin{thm}\label{thm-asym} +\begin{equation} +H_c=\frac12\sum_{I\subseteq\mathbf{n}-\{l \}} +(-1)^{\abs{I}}\per\mathbf{A}^{(\lambda)}(I|I)\det +\mathbf{A}^{(\lambda)} +(\overline I\cup\{l \}|\overline I\cup\{l \}) +\end{equation} +which reduces to Goulden--Jackson's formula when $\lambda_i=0,i=1,\dots,n$ +\cite{mami:matrixth}. +\end{thm} + +\section{Various font features of the \pkg{amsmath} package} +\label{s:font} +\subsection{Bold versions of special symbols} + +In the \pkg{amsmath} package \cn{boldsymbol} is used for getting +individual bold math symbols and bold Greek letters---everything in +math except for letters of the Latin alphabet, +where you'd use \cn{mathbf}. For example, +\begin{verbatim} +A_\infty + \pi A_0 \sim +\mathbf{A}_{\boldsymbol{\infty}} \boldsymbol{+} +\boldsymbol{\pi} \mathbf{A}_{\boldsymbol{0}} +\end{verbatim} +looks like this: +\[A_\infty + \pi A_0 \sim \mathbf{A}_{\boldsymbol{\infty}} +\boldsymbol{+} \boldsymbol{\pi} \mathbf{A}_{\boldsymbol{0}}\] + +\subsection{``Poor man's bold''} +If a bold version of a particular symbol doesn't exist in the +available fonts, +then \cn{boldsymbol} can't be used to make that symbol bold. +At the present time, this means that +\cn{boldsymbol} can't be used with symbols from +the \fn{msam} and \fn{msbm} fonts, among others. +In some cases, poor man's bold (\cn{pmb}) can be used instead +of \cn{boldsymbol}: +% Can't show example from msam or msbm because this document is +% supposed to be TeXable even if the user doesn't have +% AMSFonts. MJD 5-JUL-1990 +\[\frac{\partial x}{\partial y} +\pmb{\bigg\vert} +\frac{\partial y}{\partial z}\] +\begin{verbatim} +\[\frac{\partial x}{\partial y} +\pmb{\bigg\vert} +\frac{\partial y}{\partial z}\] +\end{verbatim} +So-called ``large operator'' symbols such as $\sum$ and $\prod$ +require an additional command, \cn{mathop}, +to produce proper spacing and limits when \cn{pmb} is used. +For further details see \textit{The \TeX book}. +\[\sum_{\substack{i\alpha\} +=\meas_n\{x\in R^n\colon \abs{f(x)}\geq\alpha\} +\quad \forall\alpha>0.\] +\begin{verbatim} +\[\meas_1\{u\in R_+^1\colon f^*(u)>\alpha\} +=\meas_n\{x\in R^n\colon \abs{f(x)}\geq\alpha\} +\quad \forall\alpha>0.\] +\end{verbatim} +\cn{esssup} and \cn{meas} would be defined in the document preamble as +\begin{verbatim} +\DeclareMathOperator*{\esssup}{ess\,sup} +\DeclareMathOperator{\meas}{meas} +\end{verbatim} + +The following special operator names are predefined in the \pkg{amsmath} +package: \cn{varlimsup}, \cn{varliminf}, \cn{varinjlim}, and +\cn{varprojlim}. Here's what they look like in use: +\begin{align} +&\varlimsup_{n\rightarrow\infty} + \mathcal{Q}(u_n,u_n-u^{\#})\le0\\ +&\varliminf_{n\rightarrow\infty} + \left\lvert a_{n+1}\right\rvert/\left\lvert a_n\right\rvert=0\\ +&\varinjlim (m_i^\lambda\cdot)^*\le0\\ +&\varprojlim_{p\in S(A)}A_p\le0 +\end{align} +\begin{verbatim} +\begin{align} +&\varlimsup_{n\rightarrow\infty} + \mathcal{Q}(u_n,u_n-u^{\#})\le0\\ +&\varliminf_{n\rightarrow\infty} + \left\lvert a_{n+1}\right\rvert/\left\lvert a_n\right\rvert=0\\ +&\varinjlim (m_i^\lambda\cdot)^*\le0\\ +&\varprojlim_{p\in S(A)}A_p\le0 +\end{align} +\end{verbatim} + +\subsection{\cn{mod} and its relatives} +The commands \cn{mod} and \cn{pod} are variants of +\cn{pmod} preferred by some authors; \cn{mod} omits the parentheses, +whereas \cn{pod} omits the `mod' and retains the parentheses. +Examples: +\begin{align} +x&\equiv y+1\pmod{m^2}\\ +x&\equiv y+1\mod{m^2}\\ +x&\equiv y+1\pod{m^2} +\end{align} +\begin{verbatim} +\begin{align} +x&\equiv y+1\pmod{m^2}\\ +x&\equiv y+1\mod{m^2}\\ +x&\equiv y+1\pod{m^2} +\end{align} +\end{verbatim} + +\subsection{Fractions and related constructions} +\label{fracs} + +The usual notation for binomials is similar to the fraction concept, +so it has a similar command \cn{binom} with two arguments. Example: +\begin{equation} +\begin{split} +\sum_{\gamma\in\Gamma_C} I_\gamma& +=2^k-\binom{k}{1}2^{k-1}+\binom{k}{2}2^{k-2}\\ +&\quad+\dots+(-1)^l\binom{k}{l}2^{k-l} ++\dots+(-1)^k\\ +&=(2-1)^k=1 +\end{split} +\end{equation} +\begin{verbatim} +\begin{equation} +\begin{split} +[\sum_{\gamma\in\Gamma_C} I_\gamma& +=2^k-\binom{k}{1}2^{k-1}+\binom{k}{2}2^{k-2}\\ +&\quad+\dots+(-1)^l\binom{k}{l}2^{k-l} ++\dots+(-1)^k\\ +&=(2-1)^k=1 +\end{split} +\end{equation} +\end{verbatim} +There are also abbreviations +\begin{verbatim} +\dfrac \dbinom +\tfrac \tbinom +\end{verbatim} +for the commonly needed constructions +\begin{verbatim} +{\displaystyle\frac ... } {\displaystyle\binom ... } +{\textstyle\frac ... } {\textstyle\binom ... } +\end{verbatim} + +The generalized fraction command \cn{genfrac} provides full access to +the six \TeX{} fraction primitives: +\begin{align} +\text{\cn{over}: }&\genfrac{}{}{}{}{n+1}{2}& +\text{\cn{overwithdelims}: }& + \genfrac{\langle}{\rangle}{}{}{n+1}{2}\\ +\text{\cn{atop}: }&\genfrac{}{}{0pt}{}{n+1}{2}& +\text{\cn{atopwithdelims}: }& + \genfrac{(}{)}{0pt}{}{n+1}{2}\\ +\text{\cn{above}: }&\genfrac{}{}{1pt}{}{n+1}{2}& +\text{\cn{abovewithdelims}: }& + \genfrac{[}{]}{1pt}{}{n+1}{2} +\end{align} +\begin{verbatim} +\text{\cn{over}: }&\genfrac{}{}{}{}{n+1}{2}& +\text{\cn{overwithdelims}: }& + \genfrac{\langle}{\rangle}{}{}{n+1}{2}\\ +\text{\cn{atop}: }&\genfrac{}{}{0pt}{}{n+1}{2}& +\text{\cn{atopwithdelims}: }& + \genfrac{(}{)}{0pt}{}{n+1}{2}\\ +\text{\cn{above}: }&\genfrac{}{}{1pt}{}{n+1}{2}& +\text{\cn{abovewithdelims}: }& + \genfrac{[}{]}{1pt}{}{n+1}{2} +\end{verbatim} + +\subsection{Continued fractions} +The continued fraction +\begin{equation} +\cfrac{1}{\sqrt{2}+ + \cfrac{1}{\sqrt{2}+ + \cfrac{1}{\sqrt{2}+ + \cfrac{1}{\sqrt{2}+ + \cfrac{1}{\sqrt{2}+\dotsb +}}}}} +\end{equation} +can be obtained by typing +\begin{verbatim} +\cfrac{1}{\sqrt{2}+ + \cfrac{1}{\sqrt{2}+ + \cfrac{1}{\sqrt{2}+ + \cfrac{1}{\sqrt{2}+ + \cfrac{1}{\sqrt{2}+\dotsb +}}}}} +\end{verbatim} +Left or right placement of any of the numerators is accomplished by using +\cn{cfrac[l]} or \cn{cfrac[r]} instead of \cn{cfrac}. + +\subsection{Smash} + +In \pkg{amsmath} there are optional arguments \verb"t" and \verb"b" for +the plain \TeX\ command \cn{smash}, because sometimes it is advantageous +to be able to `smash' only the top or only the bottom of something while +retaining the natural depth or height. In the formula +$X_j=(1/\sqrt{\smash[b]{\lambda_j}})X_j'$ \cn{smash}\verb=[b]= has been +used to limit the size of the radical symbol. +\begin{verbatim} +$X_j=(1/\sqrt{\smash[b]{\lambda_j}})X_j'$ +\end{verbatim} +Without the use of \cn{smash}\verb=[b]= the formula would have appeared +thus: $X_j=(1/\sqrt{\lambda_j})X_j'$, with the radical extending to +encompass the depth of the subscript $j$. + +\subsection{The `cases' environment} +`Cases' constructions like the following can be produced using +the \env{cases} environment. +\begin{equation} +P_{r-j}= + \begin{cases} + 0& \text{if $r-j$ is odd},\\ + r!\,(-1)^{(r-j)/2}& \text{if $r-j$ is even}. + \end{cases} +\end{equation} +\begin{verbatim} +\begin{equation} P_{r-j}= + \begin{cases} + 0& \text{if $r-j$ is odd},\\ + r!\,(-1)^{(r-j)/2}& \text{if $r-j$ is even}. + \end{cases} +\end{equation} +\end{verbatim} +Notice the use of \cn{text} and the embedded math. + +\subsection{Matrix} + +Here are samples of the matrix environments, +\cn{matrix}, \cn{pmatrix}, \cn{bmatrix}, \cn{Bmatrix}, \cn{vmatrix} +and \cn{Vmatrix}: +\begin{equation} +\begin{matrix} +\vartheta& \varrho\\\varphi& \varpi +\end{matrix}\quad +\begin{pmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{pmatrix}\quad +\begin{bmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{bmatrix}\quad +\begin{Bmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{Bmatrix}\quad +\begin{vmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{vmatrix}\quad +\begin{Vmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{Vmatrix} +\end{equation} +% +\begin{verbatim} +\begin{matrix} +\vartheta& \varrho\\\varphi& \varpi +\end{matrix}\quad +\begin{pmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{pmatrix}\quad +\begin{bmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{bmatrix}\quad +\begin{Bmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{Bmatrix}\quad +\begin{vmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{vmatrix}\quad +\begin{Vmatrix} +\vartheta& \varrho\\\varphi& \varpi +\end{Vmatrix} +\end{verbatim} + +To produce a small matrix suitable for use in text, use the +\env{smallmatrix} environment. +\begin{verbatim} +\begin{math} + \bigl( \begin{smallmatrix} + a&b\\ c&d + \end{smallmatrix} \bigr) +\end{math} +\end{verbatim} +To show +the effect of the matrix on the surrounding lines of +a paragraph, we put it here: \begin{math} + \bigl( \begin{smallmatrix} + a&b\\ c&d + \end{smallmatrix} \bigr) +\end{math} +and follow it with enough text to ensure that there will +be at least one full line below the matrix. + +\cn{hdotsfor}\verb"{"\textit{number}\verb"}" produces a row of dots in a matrix +spanning the given number of columns: +\[W(\Phi)= \begin{Vmatrix} +\dfrac\varphi{(\varphi_1,\varepsilon_1)}&0&\dots&0\\ +\dfrac{\varphi k_{n2}}{(\varphi_2,\varepsilon_1)}& +\dfrac\varphi{(\varphi_2,\varepsilon_2)}&\dots&0\\ +\hdotsfor{5}\\ +\dfrac{\varphi k_{n1}}{(\varphi_n,\varepsilon_1)}& +\dfrac{\varphi k_{n2}}{(\varphi_n,\varepsilon_2)}&\dots& +\dfrac{\varphi k_{n\,n-1}}{(\varphi_n,\varepsilon_{n-1})}& +\dfrac{\varphi}{(\varphi_n,\varepsilon_n)} +\end{Vmatrix}\] +\begin{verbatim} +\[W(\Phi)= \begin{Vmatrix} +\dfrac\varphi{(\varphi_1,\varepsilon_1)}&0&\dots&0\\ +\dfrac{\varphi k_{n2}}{(\varphi_2,\varepsilon_1)}& +\dfrac\varphi{(\varphi_2,\varepsilon_2)}&\dots&0\\ +\hdotsfor{5}\\ +\dfrac{\varphi k_{n1}}{(\varphi_n,\varepsilon_1)}& +\dfrac{\varphi k_{n2}}{(\varphi_n,\varepsilon_2)}&\dots& +\dfrac{\varphi k_{n\,n-1}}{(\varphi_n,\varepsilon_{n-1})}& +\dfrac{\varphi}{(\varphi_n,\varepsilon_n)} +\end{Vmatrix}\] +\end{verbatim} +The spacing of the dots can be varied through use of a square-bracket +option, for example, \verb"\hdotsfor[1.5]{3}". The number in square brackets +will be used as a multiplier; the normal value is 1. + +\subsection{The \cn{substack} command} + +The \cn{substack} command can be used to produce a multiline +subscript or superscript: +for example +\begin{verbatim} +\sum_{\substack{0\le i\le m\\ 0 + +Let $f\colon[a,b] \to \R$ be Riemann integrable. Let $F\colon[a,b]\to\R$ be $F(x)= +\int_{a}^{x} f(t)\,dt$. Then $F$ is continuous, and at all $x$ such that $f$ is continuous at $x$, $F$ is differentiable at $x$ with $F'(x)=f(x)$. + + + +### Blocks {/* #blocks */} + +For equation block or display mode, use ```math fenced code blocks. + +````latex +```math +I = \int_0^{2\pi} \sin(x)\,dx +``` +```` + +You can also use line breaks and `$$`, although this syntax relies on a [Markdown syntax extension](https://github.com/micromark/micromark-extension-math) and is less portable: + +```latex +$$ +I = \int_0^{2\pi} \sin(x)\,dx +$$ +``` + + + +```math +I = \int_0^{2\pi} \sin(x)\,dx +``` + + + +## Enabling math equations {/* #configuration */} + +Enable KaTeX: + +1. Install the `remark-math` and `rehype-katex` plugins: + + ```bash npm2yarn + npm install --save remark-math@6 rehype-katex@7 + ``` + + :::warning + + Make sure to use `remark-math 6` and `rehype-katex 7` for Docusaurus v3 (using MDX v3). We can't guarantee other versions will work. + + ::: + +2. These 2 plugins are [**only available as ES Modules**](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). We recommended to use an [**ES Modules**](https://flaviocopes.com/es-modules/) config file: + + ```js title="ES module docusaurus.config.js" + // highlight-start + import remarkMath from 'remark-math'; + import rehypeKatex from 'rehype-katex'; + // highlight-end + + // highlight-start + export default { + presets: [ + [ + '@docusaurus/preset-classic', + { + docs: { + path: 'docs', + // highlight-start + remarkPlugins: [remarkMath], + rehypePlugins: [rehypeKatex], + // highlight-end + }, + }, + ], + ], + }; + ``` + +
+ + + Using a + [**CommonJS**](https://nodejs.org/api/modules.html#modules-commonjs-modules) + config file? + + + If you decide to use a CommonJS config file, it is possible to load those ES module plugins thanks to dynamic imports and an async config creator function: + + ```js title="CommonJS module docusaurus.config.js" + // highlight-start + module.exports = async function createConfigAsync() { + // highlight-end + return { + presets: [ + [ + '@docusaurus/preset-classic', + { + docs: { + path: 'docs', + // highlight-start + remarkPlugins: [(await import('remark-math')).default], + rehypePlugins: [(await import('rehype-katex')).default], + // highlight-end + }, + }, + ], + ], + }; + }; + ``` + +
+ +3. Include the KaTeX CSS in your config under `stylesheets`: + + ```js + export default { + //... + stylesheets: [ + { + href: 'https://cdn.jsdelivr.net/npm/katex@0.13.24/dist/katex.min.css', + type: 'text/css', + integrity: + 'sha384-odtC+0UGzzFL/6PNoE8rX/SPcQDXBJ+uRepguP4QkPCm2LBxH3FA3y+fKSiJ+AmM', + crossorigin: 'anonymous', + }, + ], + }; + ``` + +
+See a config file example + +```js title="docusaurus.config.js" +// highlight-start +import remarkMath from 'remark-math'; +import rehypeKatex from 'rehype-katex'; +// highlight-end + +export default { + title: 'Docusaurus', + tagline: 'Build optimized websites quickly, focus on your content', + presets: [ + [ + '@docusaurus/preset-classic', + { + docs: { + path: 'docs', + // highlight-start + remarkPlugins: [remarkMath], + rehypePlugins: [rehypeKatex], + // highlight-end + }, + }, + ], + ], + // highlight-start + stylesheets: [ + { + href: 'https://cdn.jsdelivr.net/npm/katex@0.13.24/dist/katex.min.css', + type: 'text/css', + integrity: + 'sha384-odtC+0UGzzFL/6PNoE8rX/SPcQDXBJ+uRepguP4QkPCm2LBxH3FA3y+fKSiJ+AmM', + crossorigin: 'anonymous', + }, + ], + // highlight-end +}; +``` + +
+ +## Self-hosting KaTeX assets {/* #self-hosting-katex-assets */} + +Loading stylesheets, fonts, and JavaScript libraries from CDN sources is a good practice for popular libraries and assets, since it reduces the amount of assets you have to host. In case you prefer to self-host the `katex.min.css` (along with required KaTeX fonts), you can download the latest version from [KaTeX GitHub releases](https://github.com/KaTeX/KaTeX/releases), extract and copy `katex.min.css` and `fonts` directory (only `.woff2` font types should be enough) to your site's `static` directory, and in `docusaurus.config.js`, replace the stylesheet's `href` from the CDN URL to your local path (say, `/katex/katex.min.css`). + +```js title="docusaurus.config.js" +export default { + stylesheets: [ + { + href: '/katex/katex.min.css', + type: 'text/css', + }, + ], +}; +``` diff --git a/markdown/math/mathjax_49c700.md b/markdown/math/mathjax_49c700.md new file mode 100644 index 0000000..d60ed0a --- /dev/null +++ b/markdown/math/mathjax_49c700.md @@ -0,0 +1,43 @@ +# MathJax support + +mdBook has optional support for math equations through +[MathJax](https://www.mathjax.org/). + +To enable MathJax, you need to add the `mathjax-support` key to your `book.toml` +under the `output.html` section. + +```toml +[output.html] +mathjax-support = true +``` + +>**Note:** The usual delimiters MathJax uses are not yet supported. You can't +currently use `$$ ... $$` as delimiters and the `\[ ... \]` delimiters need an +extra backslash to work. Hopefully this limitation will be lifted soon. + +>**Note:** When you use double backslashes in MathJax blocks (for example in +> commands such as `\begin{cases} \frac 1 2 \\ \frac 3 4 \end{cases}`) you need +> to add _two extra_ backslashes (e.g., `\begin{cases} \frac 1 2 \\\\ \frac 3 4 +> \end{cases}`). + + +### Inline equations +Inline equations are delimited by `\\(` and `\\)`. So for example, to render the +following inline equation \\( \int x dx = \frac{x^2}{2} + C \\) you would write +the following: +``` +\\( \int x dx = \frac{x^2}{2} + C \\) +``` + +### Block equations +Block equations are delimited by `\\[` and `\\]`. To render the following +equation + +\\[ \mu = \frac{1}{N} \sum_{i=0} x_i \\] + + +you would write: + +```bash +\\[ \mu = \frac{1}{N} \sum_{i=0} x_i \\] +``` diff --git a/markdown/math/neural_networks_case_study_aeb5f4.md b/markdown/math/neural_networks_case_study_aeb5f4.md new file mode 100644 index 0000000..132624a --- /dev/null +++ b/markdown/math/neural_networks_case_study_aeb5f4.md @@ -0,0 +1,429 @@ +--- +layout: page +permalink: /neural-networks-case-study/ +--- + +Table of Contents: + +- [Generating some data](#data) +- [Training a Softmax Linear Classifier](#linear) + - [Initialize the parameters](#init) + - [Compute the class scores](#scores) + - [Compute the loss](#loss) + - [Computing the analytic gradient with backpropagation](#grad) + - [Performing a parameter update](#update) + - [Putting it all together: Training a Softmax Classifier](#together) +- [Training a Neural Network](#net) +- [Summary](#summary) + +In this section we'll walk through a complete implementation of a toy Neural Network in 2 dimensions. We'll first implement a simple linear classifier and then extend the code to a 2-layer Neural Network. As we'll see, this extension is surprisingly simple and very few changes are necessary. + + + +## Generating some data + +Lets generate a classification dataset that is not easily linearly separable. Our favorite example is the spiral dataset, which can be generated as follows: + +```python +N = 100 # number of points per class +D = 2 # dimensionality +K = 3 # number of classes +X = np.zeros((N*K,D)) # data matrix (each row = single example) +y = np.zeros(N*K, dtype='uint8') # class labels +for j in range(K): + ix = range(N*j,N*(j+1)) + r = np.linspace(0.0,1,N) # radius + t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta + X[ix] = np.c_[r*np.sin(t), r*np.cos(t)] + y[ix] = j +# lets visualize the data: +plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral) +plt.show() +``` + +
+ +
+ The toy spiral data consists of three classes (blue, red, yellow) that are not linearly separable. +
+
+ +Normally we would want to preprocess the dataset so that each feature has zero mean and unit standard deviation, but in this case the features are already in a nice range from -1 to 1, so we skip this step. + + + +## Training a Softmax Linear Classifier + + + +### Initialize the parameters + +Lets first train a Softmax classifier on this classification dataset. As we saw in the previous sections, the Softmax classifier has a linear score function and uses the cross-entropy loss. The parameters of the linear classifier consist of a weight matrix `W` and a bias vector `b` for each class. Lets first initialize these parameters to be random numbers: + +```python +# initialize parameters randomly +W = 0.01 * np.random.randn(D,K) +b = np.zeros((1,K)) +``` + +Recall that we `D = 2` is the dimensionality and `K = 3` is the number of classes. + + + +### Compute the class scores + +Since this is a linear classifier, we can compute all class scores very simply in parallel with a single matrix multiplication: + +```python +# compute class scores for a linear classifier +scores = np.dot(X, W) + b +``` + +In this example we have 300 2-D points, so after this multiplication the array `scores` will have size [300 x 3], where each row gives the class scores corresponding to the 3 classes (blue, red, yellow). + + + +### Compute the loss + +The second key ingredient we need is a loss function, which is a differentiable objective that quantifies our unhappiness with the computed class scores. Intuitively, we want the correct class to have a higher score than the other classes. When this is the case, the loss should be low and otherwise the loss should be high. There are many ways to quantify this intuition, but in this example lets use the cross-entropy loss that is associated with the Softmax classifier. Recall that if \\(f\\) is the array of class scores for a single example (e.g. array of 3 numbers here), then the Softmax classifier computes the loss for that example as: + +$$ +L_i = -\log\left(\frac{e^{f_{y_i}}}{ \sum_j e^{f_j} }\right) +$$ + +We can see that the Softmax classifier interprets every element of \\(f\\) as holding the (unnormalized) log probabilities of the three classes. We exponentiate these to get (unnormalized) probabilities, and then normalize them to get probabilites. Therefore, the expression inside the log is the normalized probability of the correct class. Note how this expression works: this quantity is always between 0 and 1. When the probability of the correct class is very small (near 0), the loss will go towards (positive) infinity. Conversely, when the correct class probability goes towards 1, the loss will go towards zero because \\(log(1) = 0\\). Hence, the expression for \\(L_i\\) is low when the correct class probability is high, and it's very high when it is low. + +Recall also that the full Softmax classifier loss is then defined as the average cross-entropy loss over the training examples and the regularization: + +$$ +L = \underbrace{ \frac{1}{N} \sum_i L_i }_\text{data loss} + \underbrace{ \frac{1}{2} \lambda \sum_k\sum_l W_{k,l}^2 }_\text{regularization loss} \\\\ +$$ + +Given the array of `scores` we've computed above, we can compute the loss. First, the way to obtain the probabilities is straight forward: + +```python +num_examples = X.shape[0] +# get unnormalized probabilities +exp_scores = np.exp(scores) +# normalize them for each example +probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) +``` + +We now have an array `probs` of size [300 x 3], where each row now contains the class probabilities. In particular, since we've normalized them every row now sums to one. We can now query for the log probabilities assigned to the correct classes in each example: + +```python +correct_logprobs = -np.log(probs[range(num_examples),y]) +``` + +The array `correct_logprobs` is a 1D array of just the probabilities assigned to the correct classes for each example. The full loss is then the average of these log probabilities and the regularization loss: + +```python +# compute the loss: average cross-entropy loss and regularization +data_loss = np.sum(correct_logprobs)/num_examples +reg_loss = 0.5*reg*np.sum(W*W) +loss = data_loss + reg_loss +``` + +In this code, the regularization strength \\(\lambda\\) is stored inside the `reg`. The convenience factor of `0.5` multiplying the regularization will become clear in a second. Evaluating this in the beginning (with random parameters) might give us `loss = 1.1`, which is `-np.log(1.0/3)`, since with small initial random weights all probabilities assigned to all classes are about one third. We now want to make the loss as low as possible, with `loss = 0` as the absolute lower bound. But the lower the loss is, the higher are the probabilities assigned to the correct classes for all examples. + + + +### Computing the Analytic Gradient with Backpropagation + +We have a way of evaluating the loss, and now we have to minimize it. We'll do so with gradient descent. That is, we start with random parameters (as shown above), and evaluate the gradient of the loss function with respect to the parameters, so that we know how we should change the parameters to decrease the loss. Lets introduce the intermediate variable \\(p\\), which is a vector of the (normalized) probabilities. The loss for one example is: + +$$ +p_k = \frac{e^{f_k}}{ \sum_j e^{f_j} } \hspace{1in} L_i =-\log\left(p_{y_i}\right) +$$ + +We now wish to understand how the computed scores inside \\(f\\) should change to decrease the loss \\(L_i\\) that this example contributes to the full objective. In other words, we want to derive the gradient \\( \partial L_i / \partial f_k \\). The loss \\(L_i\\) is computed from \\(p\\), which in turn depends on \\(f\\). It's a fun exercise to the reader to use the chain rule to derive the gradient, but it turns out to be extremely simple and interpretible in the end, after a lot of things cancel out: + +$$ +\frac{\partial L_i }{ \partial f_k } = p_k - \mathbb{1}(y_i = k) +$$ + +Notice how elegant and simple this expression is. Suppose the probabilities we computed were `p = [0.2, 0.3, 0.5]`, and that the correct class was the middle one (with probability 0.3). According to this derivation the gradient on the scores would be `df = [0.2, -0.7, 0.5]`. Recalling what the interpretation of the gradient, we see that this result is highly intuitive: increasing the first or last element of the score vector `f` (the scores of the incorrect classes) leads to an *increased* loss (due to the positive signs +0.2 and +0.5) - and increasing the loss is bad, as expected. However, increasing the score of the correct class has *negative* influence on the loss. The gradient of -0.7 is telling us that increasing the correct class score would lead to a decrease of the loss \\(L_i\\), which makes sense. + +All of this boils down to the following code. Recall that `probs` stores the probabilities of all classes (as rows) for each example. To get the gradient on the scores, which we call `dscores`, we proceed as follows: + +```python +dscores = probs +dscores[range(num_examples),y] -= 1 +dscores /= num_examples +``` + +Lastly, we had that `scores = np.dot(X, W) + b`, so armed with the gradient on `scores` (stored in `dscores`), we can now backpropagate into `W` and `b`: + +```python +dW = np.dot(X.T, dscores) +db = np.sum(dscores, axis=0, keepdims=True) +dW += reg*W # don't forget the regularization gradient +``` + +Where we see that we have backpropped through the matrix multiply operation, and also added the contribution from the regularization. Note that the regularization gradient has the very simple form `reg*W` since we used the constant `0.5` for its loss contribution (i.e. \\(\frac{d}{dw} ( \frac{1}{2} \lambda w^2) = \lambda w\\). This is a common convenience trick that simplifies the gradient expression. + + + +### Performing a parameter update + +Now that we've evaluated the gradient we know how every parameter influences the loss function. We will now perform a parameter update in the *negative* gradient direction to *decrease* the loss: + +```python +# perform a parameter update +W += -step_size * dW +b += -step_size * db +``` + + + +### Putting it all together: Training a Softmax Classifier + +Putting all of this together, here is the full code for training a Softmax classifier with Gradient descent: + +```python +#Train a Linear Classifier + +# initialize parameters randomly +W = 0.01 * np.random.randn(D,K) +b = np.zeros((1,K)) + +# some hyperparameters +step_size = 1e-0 +reg = 1e-3 # regularization strength + +# gradient descent loop +num_examples = X.shape[0] +for i in range(200): + + # evaluate class scores, [N x K] + scores = np.dot(X, W) + b + + # compute the class probabilities + exp_scores = np.exp(scores) + probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K] + + # compute the loss: average cross-entropy loss and regularization + correct_logprobs = -np.log(probs[range(num_examples),y]) + data_loss = np.sum(correct_logprobs)/num_examples + reg_loss = 0.5*reg*np.sum(W*W) + loss = data_loss + reg_loss + if i % 10 == 0: + print "iteration %d: loss %f" % (i, loss) + + # compute the gradient on scores + dscores = probs + dscores[range(num_examples),y] -= 1 + dscores /= num_examples + + # backpropate the gradient to the parameters (W,b) + dW = np.dot(X.T, dscores) + db = np.sum(dscores, axis=0, keepdims=True) + + dW += reg*W # regularization gradient + + # perform a parameter update + W += -step_size * dW + b += -step_size * db +``` + +Running this prints the output: + +``` +iteration 0: loss 1.096956 +iteration 10: loss 0.917265 +iteration 20: loss 0.851503 +iteration 30: loss 0.822336 +iteration 40: loss 0.807586 +iteration 50: loss 0.799448 +iteration 60: loss 0.794681 +iteration 70: loss 0.791764 +iteration 80: loss 0.789920 +iteration 90: loss 0.788726 +iteration 100: loss 0.787938 +iteration 110: loss 0.787409 +iteration 120: loss 0.787049 +iteration 130: loss 0.786803 +iteration 140: loss 0.786633 +iteration 150: loss 0.786514 +iteration 160: loss 0.786431 +iteration 170: loss 0.786373 +iteration 180: loss 0.786331 +iteration 190: loss 0.786302 +``` + +We see that we've converged to something after about 190 iterations. We can evaluate the training set accuracy: + +```python +# evaluate training set accuracy +scores = np.dot(X, W) + b +predicted_class = np.argmax(scores, axis=1) +print 'training accuracy: %.2f' % (np.mean(predicted_class == y)) +``` + +This prints **49%**. Not very good at all, but also not surprising given that the dataset is constructed so it is not linearly separable. We can also plot the learned decision boundaries: + +
+ +
+ Linear classifier fails to learn the toy spiral dataset. +
+
+ + + +## Training a Neural Network + +Clearly, a linear classifier is inadequate for this dataset and we would like to use a Neural Network. One additional hidden layer will suffice for this toy data. We will now need two sets of weights and biases (for the first and second layers): + +```python +# initialize parameters randomly +h = 100 # size of hidden layer +W = 0.01 * np.random.randn(D,h) +b = np.zeros((1,h)) +W2 = 0.01 * np.random.randn(h,K) +b2 = np.zeros((1,K)) +``` + +The forward pass to compute scores now changes form: + +```python +# evaluate class scores with a 2-layer Neural Network +hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation +scores = np.dot(hidden_layer, W2) + b2 +``` + +Notice that the only change from before is one extra line of code, where we first compute the hidden layer representation and then the scores based on this hidden layer. Crucially, we've also added a non-linearity, which in this case is simple ReLU that thresholds the activations on the hidden layer at zero. + +Everything else remains the same. We compute the loss based on the scores exactly as before, and get the gradient for the scores `dscores` exactly as before. However, the way we backpropagate that gradient into the model parameters now changes form, of course. First lets backpropagate the second layer of the Neural Network. This looks identical to the code we had for the Softmax classifier, except we're replacing `X` (the raw data), with the variable `hidden_layer`): + +```python +# backpropate the gradient to the parameters +# first backprop into parameters W2 and b2 +dW2 = np.dot(hidden_layer.T, dscores) +db2 = np.sum(dscores, axis=0, keepdims=True) +``` + +However, unlike before we are not yet done, because `hidden_layer` is itself a function of other parameters and the data! We need to continue backpropagation through this variable. Its gradient can be computed as: + +```python +dhidden = np.dot(dscores, W2.T) +``` + +Now we have the gradient on the outputs of the hidden layer. Next, we have to backpropagate the ReLU non-linearity. This turns out to be easy because ReLU during the backward pass is effectively a switch. Since \\(r = max(0, x)\\), we have that \\(\frac{dr}{dx} = 1(x > 0) \\). Combined with the chain rule, we see that the ReLU unit lets the gradient pass through unchanged if its input was greater than 0, but *kills it* if its input was less than zero during the forward pass. Hence, we can backpropagate the ReLU in place simply with: + +```python +# backprop the ReLU non-linearity +dhidden[hidden_layer <= 0] = 0 +``` + +And now we finally continue to the first layer weights and biases: + +```python +# finally into W,b +dW = np.dot(X.T, dhidden) +db = np.sum(dhidden, axis=0, keepdims=True) +``` + +We're done! We have the gradients `dW,db,dW2,db2` and can perform the parameter update. Everything else remains unchanged. The full code looks very similar: + +```python +# initialize parameters randomly +h = 100 # size of hidden layer +W = 0.01 * np.random.randn(D,h) +b = np.zeros((1,h)) +W2 = 0.01 * np.random.randn(h,K) +b2 = np.zeros((1,K)) + +# some hyperparameters +step_size = 1e-0 +reg = 1e-3 # regularization strength + +# gradient descent loop +num_examples = X.shape[0] +for i in range(10000): + + # evaluate class scores, [N x K] + hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation + scores = np.dot(hidden_layer, W2) + b2 + + # compute the class probabilities + exp_scores = np.exp(scores) + probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K] + + # compute the loss: average cross-entropy loss and regularization + correct_logprobs = -np.log(probs[range(num_examples),y]) + data_loss = np.sum(correct_logprobs)/num_examples + reg_loss = 0.5*reg*np.sum(W*W) + 0.5*reg*np.sum(W2*W2) + loss = data_loss + reg_loss + if i % 1000 == 0: + print "iteration %d: loss %f" % (i, loss) + + # compute the gradient on scores + dscores = probs + dscores[range(num_examples),y] -= 1 + dscores /= num_examples + + # backpropate the gradient to the parameters + # first backprop into parameters W2 and b2 + dW2 = np.dot(hidden_layer.T, dscores) + db2 = np.sum(dscores, axis=0, keepdims=True) + # next backprop into hidden layer + dhidden = np.dot(dscores, W2.T) + # backprop the ReLU non-linearity + dhidden[hidden_layer <= 0] = 0 + # finally into W,b + dW = np.dot(X.T, dhidden) + db = np.sum(dhidden, axis=0, keepdims=True) + + # add regularization gradient contribution + dW2 += reg * W2 + dW += reg * W + + # perform a parameter update + W += -step_size * dW + b += -step_size * db + W2 += -step_size * dW2 + b2 += -step_size * db2 +``` + +This prints: + +``` +iteration 0: loss 1.098744 +iteration 1000: loss 0.294946 +iteration 2000: loss 0.259301 +iteration 3000: loss 0.248310 +iteration 4000: loss 0.246170 +iteration 5000: loss 0.245649 +iteration 6000: loss 0.245491 +iteration 7000: loss 0.245400 +iteration 8000: loss 0.245335 +iteration 9000: loss 0.245292 +``` + +The training accuracy is now: + +```python +# evaluate training set accuracy +hidden_layer = np.maximum(0, np.dot(X, W) + b) +scores = np.dot(hidden_layer, W2) + b2 +predicted_class = np.argmax(scores, axis=1) +print 'training accuracy: %.2f' % (np.mean(predicted_class == y)) +``` + +Which prints **98%**!. We can also visualize the decision boundaries: + +
+ +
+ Neural Network classifier crushes the spiral dataset. +
+
+ +## Summary + +We've worked with a toy 2D dataset and trained both a linear network and a 2-layer Neural Network. We saw that the change from a linear classifier to a Neural Network involves very few changes in the code. The score function changes its form (1 line of code difference), and the backpropagation changes its form (we have to perform one more round of backprop through the hidden layer to the first layer of the network). + +- You may want to look at this IPython Notebook code [rendered as HTML](http://cs.stanford.edu/people/karpathy/cs231nfiles/minimal_net.html). +- Or download the [ipynb file](http://cs.stanford.edu/people/karpathy/cs231nfiles/minimal_net.ipynb) + diff --git a/markdown/math/spe_67468e.markdown b/markdown/math/spe_67468e.markdown new file mode 100644 index 0000000..a221f2b --- /dev/null +++ b/markdown/math/spe_67468e.markdown @@ -0,0 +1,26 @@ +Stochastic Proximity Embedding +------------------------------ + +Stochastic Proximity Embedding (SPE) acts on a set of $ N $ vectors $Y = \{ y\_1, y\_2, \dots y\_N \} $ with corresponding symmetric distance matrix $ D\_{ij} $ in the following manner: + +1. Choose an initial learning rate $ \lambda$. + +2. Initialize randomly the point coordinates in the embedded space $X = \{ x\_1, x\_2, \dots x\_N \} $. + +3. Select at random a pair of points with indices $ i $ and $ j $. For a prescribed number of iterations $ S $, + compute their distances in the embedded space, + $$ d\_{i,j} = \| x\_i - x\_j \| $$; + if $ d\_{i,j} \neq D\_{i,j} $ then update the coordinates of the selected points by + $$ x\_i \leftarrow x\_i + \lambda \frac{1}{2} \frac{D\_{ij} - d\_{ij}}{d\_{ij} + \epsilon} (x\_i - x\_j), $$ + $$ x\_j \leftarrow x\_j + \lambda \frac{1}{2} \frac{D\_{ij} - d\_{ij}}{d\_{ij} + \epsilon} (x\_j - x\_i). $$ + +4. Decrease the learning rate $ \lambda $ by $ \delta \lambda | 0 < \delta < 1 $. $ \lambda $ is decreased to avoid oscillatory behaviour. + +5. Repeat steps 3 and 4 for a predetermined number of iterations $ C $. + +SPE is an interesting method because of its simplicity and efficiency, as it scales linearly with the sample size $ N $. + +Reference +--------- + +* D. K. Agrafiotis. "Stochastic Proximity Embedding," *Journal of Computational Chemistry*, 2003. diff --git a/markdown/math/supported_b0c613.md b/markdown/math/supported_b0c613.md new file mode 100644 index 0000000..af59238 --- /dev/null +++ b/markdown/math/supported_b0c613.md @@ -0,0 +1,732 @@ +--- +id: supported +title: Supported Functions +--- +This is a list of TeX functions supported by KaTeX. It is sorted into logical groups. + +There is a similar [Support Table](support_table.md), sorted alphabetically, that lists both supported and un-supported functions. + + + + +
+ +## Accents + +|||| +|:----------------------------|:----------------------------------------------------|:------ +|$a'$ `a'` |$\tilde{a}$ `\tilde{a}`|$\mathring{g}$ `\mathring{g}` +|$a''$ `a''`|$\widetilde{ac}$ `\widetilde{ac}` |$\overgroup{AB}$ `\overgroup{AB}` +|$a^{\prime}$ `a^{\prime}` |$\utilde{AB}$ `\utilde{AB}` |$\undergroup{AB}$ `\undergroup{AB}` +|$\acute{a}$ `\acute{a}`|$\vec{F}$ `\vec{F}` |$\Overrightarrow{AB}$ `\Overrightarrow{AB}` +|$\bar{y}$ `\bar{y}` |$\overleftarrow{AB}$ `\overleftarrow{AB}`|$\overrightarrow{AB}$ `\overrightarrow{AB}` +|$\breve{a}$ `\breve{a}`|$\underleftarrow{AB}$ `\underleftarrow{AB}` |$\underrightarrow{AB}$ `\underrightarrow{AB}` +|$\check{a}$ `\check{a}`|$\overleftharpoon{ac}$ `\overleftharpoon{ac}` |$\overrightharpoon{ac}$ `\overrightharpoon{ac}` +|$\dot{a}$ `\dot{a}` |$\overleftrightarrow{AB}$ `\overleftrightarrow{AB}` |$\overbrace{AB}$ `\overbrace{AB}` +|$\ddot{a}$ `\ddot{a}` |$\underleftrightarrow{AB}$ `\underleftrightarrow{AB}`|$\underbrace{AB}$ `\underbrace{AB}` +|$\dddot{a}$ `\dddot{a}`|$\overline{AB}$ `\overline{AB}` |$\overbracket{AB}$ `\overbracket{AB}` +|$\ddddot{a}$ `\ddddot{a}`|$\underline{AB}$ `\underline{AB}` |$\underbracket{AB}$ `\underbracket{AB}` +|$\grave{a}$ `\grave{a}`|$\underbar{X}$ `\underbar{X}`|$\overlinesegment{AB}$ `\overlinesegment{AB}` +|$\hat{\theta}$ `\hat{\theta}`|$\widecheck{ac}$ `\widecheck{ac}` |$\underlinesegment{AB}$ `\underlinesegment{AB}` +||$\widehat{ac}$ `\widehat{ac}`| + +***Accent functions inside \\text{…}*** + +||||| +|:---------------------|:---------------------|:---------------------|:----- +|$\text{\'{a}}$ `\'{a}`|$\text{\~{a}}$ `\~{a}`|$\text{\.{a}}$ `\.{a}`|$\text{\H{a}}$ `\H{a}` +|$\text{\`{a}}$ \\`{a}|$\text{\={a}}$ `\={a}`|$\text{\"{a}}$ `\"{a}`|$\text{\v{a}}$ `\v{a}` +|$\text{\^{a}}$ `\^{a}`|$\text{\u{a}}$ `\u{a}`|$\text{\r{a}}$ `\r{a}`| + +See also [letters and unicode](#letters-and-unicode). + +## Delimiters + +|||||| +|:-----------------------------------|:---------------------------------------|:----------|:-------------------------------------------------------|:----- +|$(~)$ `( )` |$\lparen~\rparen$ `\lparen`
$~~~~$`\rparen`|$⌈~⌉$ `⌈ ⌉`|$\lceil~\rceil$ `\lceil`
$~~~~~$`\rceil` |$\uparrow$ `\uparrow` +|$[~]$ `[ ]` |$\lbrack~\rbrack$ `\lbrack`
$~~~~$`\rbrack`|$⌊~⌋$ `⌊ ⌋`|$\lfloor~\rfloor$ `\lfloor`
$~~~~~$`\rfloor` |$\downarrow$ `\downarrow` +|$\{ \}$ `\{ \}`|$\lbrace \rbrace$ `\lbrace`
$~~~~$`\rbrace`|$⎰⎱$ `⎰⎱` |$\lmoustache \rmoustache$ `\lmoustache`
$~~~~$`\rmoustache`|$\updownarrow$ `\updownarrow` +|$⟨~⟩$ `⟨ ⟩` |$\langle~\rangle$ `\langle`
$~~~~$`\rangle`|$⟮~⟯$ `⟮ ⟯`|$\lgroup~\rgroup$ `\lgroup`
$~~~~~$`\rgroup` |$\Uparrow$ `\Uparrow` +|$\vert$ | |$\vert$ `\vert` |$┌ ┐$ `┌ ┐`|$\ulcorner \urcorner$ `\ulcorner`
$~~~~$`\urcorner` |$\Downarrow$ `\Downarrow` +|$\Vert$ \| |$\Vert$ `\Vert` |$└ ┘$ `└ ┘`|$\llcorner \lrcorner$ `\llcorner`
$~~~~$`\lrcorner` |$\Updownarrow$ `\Updownarrow` +|$\lvert~\rvert$ `\lvert`
$~~~~$`\rvert`|$\lVert~\rVert$ `\lVert`
$~~~~~$`\rVert` |`\left.`| `\right.` |$\backslash$ `\backslash` +|$\lang~\rang$ `\lang`
$~~~~$`\rang`|$\left\lt~\right\gt$ `\lt \gt`|$⟦~⟧$ `⟦ ⟧`|$\llbracket~\rrbracket$ `\llbracket`
$~~~~$`\rrbracket`|$/$ `/` +|$\lBrace~\rBrace$ `\lBrace \rBrace` + +**Delimiter Sizing** + +$\left(\LARGE{AB}\right)$ `\left(\LARGE{AB}\right)` + +$( \big( \Big( \bigg( \Bigg($ `( \big( \Big( \bigg( \Bigg(` + +|||||| +|:--------|:------|:--------|:-------|:------| +|`\left` |`\big` |`\bigl` |`\bigm` |`\bigr` +|`\middle`|`\Big` |`\Bigl` |`\Bigm` | `\Bigr` +|`\right` |`\bigg`|`\biggl` |`\biggm`|`\biggr` +| |`\Bigg`|`\Biggl` |`\Biggm`|`\Biggr` + +
+ +## Environments + +
+ +||||| +|:---------------------|:---------------------|:---------------------|:-------- +|$\begin{matrix} a & b \\ c & d \end{matrix}$ | `\begin{matrix}`
   `a & b \\`
   `c & d`
`\end{matrix}` |$\begin{array}{cc}a & b\\c & d\end{array}$ | `\begin{array}{cc}`
   `a & b \\`
   `c & d`
`\end{array}` +|$\begin{pmatrix} a & b \\ c & d \end{pmatrix}$ |`\begin{pmatrix}`
   `a & b \\`
   `c & d`
`\end{pmatrix}` |$\begin{bmatrix} a & b \\ c & d \end{bmatrix}$ | `\begin{bmatrix}`
   `a & b \\`
   `c & d`
`\end{bmatrix}` +|$\begin{vmatrix} a & b \\ c & d \end{vmatrix}$ |`\begin{vmatrix}`
   `a & b \\`
   `c & d`
`\end{vmatrix}` |$\begin{Vmatrix} a & b \\ c & d \end{Vmatrix}$ |`\begin{Vmatrix}`
   `a & b \\`
   `c & d`
`\end{Vmatrix}` +|$\begin{Bmatrix} a & b \\ c & d \end{Bmatrix}$ |`\begin{Bmatrix}`
   `a & b \\`
   `c & d`
`\end{Bmatrix}`|$\def\arraystretch{1.5}\begin{array}{c:c:c} a & b & c \\ \hline d & e & f \\ \hdashline g & h & i \end{array}$|`\def\arraystretch{1.5}`
   `\begin{array}{c:c:c}`
   `a & b & c \\ \hline`
   `d & e & f \\`
   `\hdashline`
   `g & h & i`
`\end{array}` +|$x = \begin{cases} a &\text{if } b \\ c &\text{if } d \end{cases}$ |`x = \begin{cases}`
   `a &\text{if } b \\`
   `c &\text{if } d`
`\end{cases}`|$\begin{rcases} a &\text{if } b \\ c &\text{if } d \end{rcases}⇒…$ |`\begin{rcases}`
   `a &\text{if } b \\`
   `c &\text{if } d`
`\end{rcases}⇒…`| +|$\begin{smallmatrix} a & b \\ c & d \end{smallmatrix}$ | `\begin{smallmatrix}`
   `a & b \\`
   `c & d`
`\end{smallmatrix}` |$$\sum_{\begin{subarray}{l} i\in\Lambda\\  0`\begin{subarray}{l}`
   `i\in\Lambda\\`
   `0`\end{subarray}}`| + +The auto-render extension will render the following environments even if they are not inside math delimiters such as `$$…$$`. They are display-mode only. + + +
+ +||||| +|:---------------------|:---------------------|:---------------------|:-------- +|$$\begin{equation}\begin{split}a &=b+c\\&=e+f\end{split}\end{equation}$$ |`\begin{equation}`
`\begin{split}`   `a &=b+c\\`
      `&=e+f`
`\end{split}`
`\end{equation}` |$$\begin{align} a&=b+c \\ d+e&=f \end{align}$$ |`\begin{align}`
   `a&=b+c \\`
   `d+e&=f`
`\end{align}` | +|$$\begin{gather} a=b \\ e=b+c \end{gather}$$ |`\begin{gather}`
   `a=b \\ `
   `e=b+c`
`\end{gather}`|$$\begin{alignat}{2}10&x+&3&y=2\\3&x+&13&y=4\end{alignat}$$ | `\begin{alignat}{2}`
   `10&x+&3&y=2\\`
   `3&x+&13&y=4`
`\end{alignat}` +|$$\begin{CD}A @>a>> B \\@VbVV @AAcA\\C @= D\end{CD}$$ | `\begin{CD}`
   `A @>a>> B \\`
`@VbVV @AAcA \\`
   `C @= D`
`\end{CD}` + +#### Other KaTeX Environments + +| Environments | How they differ from those shown above | +|:-----------------------------------------------|:------------------| +| `darray`, `dcases`, `drcases` | … apply `displaystyle` | +| `matrix*`, `pmatrix*`, `bmatrix*`
`Bmatrix*`, `vmatrix*`, `Vmatrix*` | … take an optional argument to set column
alignment, as in `\begin{matrix*}[r]` +| `equation*`, `gather*`
`align*`, `alignat*` | … have no automatic numbering. Alternatively, you can use `\nonumber` or `\notag` to omit the numbering for a specific row of the equation. | +| `gathered`, `aligned`, `alignedat` | … do not need to be in display mode.
… have no automatic numbering.
… must be inside math delimiters in
order to be rendered by the auto-render
extension. | + +
+ +Acceptable line separators include: `\\`, `\cr`, `\\[distance]`, and `\cr[distance]`. *Distance* can be written with any of the [KaTeX units](#units). + +The `{array}` environment supports `|` and `:` vertical separators. + +The `{array}` environment does not yet support `\cline` or `\multicolumn`. + +`\tag` can be applied to individual rows of top-level environments +(`align`, `align*`, `alignat`, `alignat*`, `gather`, `gather*`). + +
+ +## HTML + +The following "raw HTML" features are potentially dangerous for untrusted +inputs, so they are disabled by default, and attempting to use them produces +the command names in red (which you can configure via the `errorColor` +[option](options.md)). To fully trust your LaTeX input, you need to pass +an option of `trust: true`; you can also enable just some of the commands +or for just some URLs via the `trust` [option](options.md). + +||| +|:----------------|:-------------------| +| $\href{https://katex.org/}{\KaTeX}$ | `\href{https://katex.org/}{\KaTeX}` | +| $\url{https://katex.org/}$ | `\url{https://katex.org/}` | +| $\includegraphics[height=0.8em, totalheight=0.9em, width=0.9em, alt=KA logo]{https://katex.org/img/khan-academy.png}$ | `\includegraphics[height=0.8em, totalheight=0.9em, width=0.9em, alt=KA logo]{https://katex.org/img/khan-academy.png}` | +| $\htmlId{bar}{x}$ …<span id="bar" class="enclosing">…x…</span>… | `\htmlId{bar}{x}` | +| $\htmlClass{foo}{x}$ …<span class="enclosing foo">…x…</span>… | `\htmlClass{foo}{x}` | +| $\htmlStyle{color: red;}{x}$ …<span style="color: red;" class="enclosing">…x…</span>… | `\htmlStyle{color: red;}{x}` | +| $\htmlData{foo=a, bar=b}{x}$ …<span data-foo="a" data-bar="b" class="enclosing">…x…</span>… | `\htmlData{foo=a, bar=b}{x}` | + +`\includegraphics` supports `height`, `width`, `totalheight`, and `alt` in its first argument. `height` is required. + +HTML extension (`\html`-prefixed) commands are non-standard, so loosening `strict` option for `htmlExtension` is required. + + +## Letters and Unicode + +**Greek Letters** + +Direct Input: $Α Β Γ Δ Ε Ζ Η Θ Ι \allowbreak Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω$ +$\allowbreak α β γ δ ϵ ζ η θ ι κ λ μ ν ξ o π \allowbreak ρ σ τ υ ϕ χ ψ ω ε ϑ ϖ ϱ ς φ ϝ$ + +||||| +|---------------|-------------|-------------|---------------| +| $\Alpha$ `\Alpha` | $\Beta$ `\Beta` | $\Gamma$ `\Gamma`| $\Delta$ `\Delta` +| $\Epsilon$ `\Epsilon` | $\Zeta$ `\Zeta` | $\Eta$ `\Eta` | $\Theta$ `\Theta` +| $\Iota$ `\Iota` | $\Kappa$ `\Kappa` | $\Lambda$ `\Lambda` | $\Mu$ `\Mu` +| $\Nu$ `\Nu` | $\Xi$ `\Xi` | $\Omicron$ `\Omicron` | $\Pi$ `\Pi` +| $\Rho$ `\Rho` | $\Sigma$ `\Sigma` | $\Tau$ `\Tau` | $\Upsilon$ `\Upsilon` +| $\Phi$ `\Phi` | $\Chi$ `\Chi` | $\Psi$ `\Psi` | $\Omega$ `\Omega` +| $\varGamma$ `\varGamma`| $\varDelta$ `\varDelta` | $\varTheta$ `\varTheta` | $\varLambda$ `\varLambda` | +| $\varXi$ `\varXi`| $\varPi$ `\varPi` | $\varSigma$ `\varSigma` | $\varUpsilon$ `\varUpsilon` | +| $\varPhi$ `\varPhi` | $\varPsi$ `\varPsi`| $\varOmega$ `\varOmega` || +| $\alpha$ `\alpha`| $\beta$ `\beta` | $\gamma$ `\gamma` | $\delta$ `\delta`| +| $\epsilon$ `\epsilon` | $\zeta$ `\zeta` | $\eta$ `\eta`| $\theta$ `\theta`| +| $\iota$ `\iota` | $\kappa$ `\kappa` | $\lambda$ `\lambda`| $\mu$ `\mu`| +| $\nu$ `\nu`| $\xi$ `\xi` | $\omicron$ `\omicron` | $\pi$ `\pi`| +| $\rho$ `\rho` | $\sigma$ `\sigma` | $\tau$ `\tau`| $\upsilon$ `\upsilon` | +| $\phi$ `\phi` | $\chi$ `\chi`| $\psi$ `\psi`| $\omega$ `\omega`| +| $\varepsilon$ `\varepsilon` | $\varkappa$ `\varkappa` | $\vartheta$ `\vartheta` | $\thetasym$ `\thetasym` +| $\varpi$ `\varpi`| $\varrho$ `\varrho` | $\varsigma$ `\varsigma` | $\varphi$ `\varphi` +| $\digamma $ `\digamma` + +**Other Letters** + +|||||| +|:----------|:----------|:----------|:----------|:----------| +|$\imath$ `\imath`|$\nabla$ `\nabla`|$\Im$ `\Im`|$\Reals$ `\Reals`|$\text{\OE}$ `\text{\OE}` +|$\jmath$ `\jmath`|$\partial$ `\partial`|$\image$ `\image`|$\wp$ `\wp`|$\text{\o}$ `\text{\o}` +|$\aleph$ `\aleph`|$\Game$ `\Game`|$\Bbbk$ `\Bbbk`|$\weierp$ `\weierp`|$\text{\O}$ `\text{\O}` +|$\alef$ `\alef`|$\Finv$ `\Finv`|$\N$ `\N`|$\Z$ `\Z`|$\text{\ss}$ `\text{\ss}` +|$\alefsym$ `\alefsym`|$\cnums$ `\cnums`|$\natnums$ `\natnums`|$\text{\aa}$ `\text{\aa}`|$\text{\i}$ `\text{\i}` +|$\beth$ `\beth`|$\Complex$ `\Complex`|$\R$ `\R`|$\text{\AA}$ `\text{\AA}`|$\text{\j}$ `\text{\j}` +|$\gimel$ `\gimel`|$\ell$ `\ell`|$\Re$ `\Re`|$\text{\ae}$ `\text{\ae}` +|$\daleth$ `\daleth`|$\hbar$ `\hbar`|$\real$ `\real`|$\text{\AE}$ `\text{\AE}` +|$\eth$ `\eth`|$\hslash$ `\hslash`|$\reals$ `\reals`|$\text{\oe}$ `\text{\oe}` + +Direct Input: $∂ ∇ ℑ Ⅎ ℵ ℶ ℷ ℸ ⅁ ℏ ð − ∗$ +ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝÞßàáâãäåçèéêëìíîïðñòóôöùúûüýþÿ +₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ⁺⁻⁼⁽⁾⁰¹²³⁴⁵⁶⁷⁸⁹ᵃᵇᶜᵈᵉᵍʰⁱʲᵏˡᵐⁿᵒᵖʳˢᵗᵘʷˣʸᶻᵛᵝᵞᵟᵠᵡ + +Math-mode Unicode (sub|super)script characters will render as if you had written regular characters in a subscript or superscript. For instance, `A²⁺³` will render the same as `A^{2+3}`. + +**Persian/Arabic Numerals** +For support of Persian/Arabic numerals, try the third-party [persian-katex-plugin](https://github.com/HosseinAgha/persian-katex-plugin). + +
+
+ +**Unicode Mathematical Alphanumeric Symbols** + +| Item | Range | Item | Range | +|-------------|---------------------|-------------------|---------------| +| Bold | $\text{𝐀-𝐙 𝐚-𝐳 𝟎-𝟗}$ | Double-struck | $\text{𝔸-}ℤ\ 𝕜$ +| Italic | $\text{𝐴-𝑍 𝑎-𝑧}$ | Sans serif | $\text{𝖠-𝖹 𝖺-𝗓 𝟢-𝟫}$ +| Bold Italic | $\text{𝑨-𝒁 𝒂-𝒛}$ | Sans serif bold | $\text{𝗔-𝗭 𝗮-𝘇 𝟬-𝟵}$ +| Script | $\text{𝒜-𝒵}$ | Sans serif italic | $\text{𝘈-𝘡 𝘢-𝘻}$ +| Fraktur | $\text{$𝔄$-$ℨ$}\text{ $𝔞$-$𝔷$}$| Monospace | $\text{𝙰-𝚉 𝚊-𝚣 𝟶-𝟿}$ +| Bold Fraktur | $\text{𝕬-𝖅 𝖆-𝖟}$ | | + +
+
+ +**Unicode** + +The letters listed above will render properly in any KaTeX rendering mode. + +In addition, Armenian, Brahmic, Georgian, Chinese, Japanese, and Korean glyphs are always accepted in text mode. However, these glyphs will be rendered from system fonts (not KaTeX-supplied fonts) so their typography may clash. +You can provide rules for CSS classes `.latin_fallback`, `.cyrillic_fallback`, `.brahmic_fallback`, `.georgian_fallback`, `.cjk_fallback`, and `.hangul_fallback` to provide fallback fonts for these languages. +Use of these glyphs may cause small vertical alignment issues: KaTeX has detailed metrics for listed symbols and most Latin, Greek, and Cyrillic letters, but other accepted glyphs are treated as if they are each as tall as the letter M in the current KaTeX font. + +If the KaTeX rendering mode is set to `strict: false` or `strict: "warn"` (default), then KaTeX will accept all Unicode letters in both text and math mode. +All unrecognized characters will be treated as if they appeared in text mode, and are subject to the same issues of using system fonts and possibly using incorrect vertical alignment. + +For Persian composite characters, a user-supplied [plug-in](https://github.com/HosseinAgha/persian-katex-plugin) is under development. + +Any character can be written with the `\char` function and the Unicode code in hex. For example `\char"263a` will render as $\char"263a$. + +## Layout + +### Annotation + +| | | +|:------------------------------------------------------------------------|:--------------------------------------------------------------------------| +| $\cancel{5}$ `\cancel{5}` | $\overbrace{a+b+c}^{\text{note}}$ `\overbrace{a+b+c}^{\text{note}}` | +| $\bcancel{5}$ `\bcancel{5}` | $\underbrace{a+b+c}_{\text{note}}$ `\underbrace{a+b+c}_{\text{note}}` | +| $\xcancel{ABC}$ `\xcancel{ABC}` | $\not =$ `\not =` | +| $\text{\sout{abc}}$ `\text{\sout{abc}}` | $\boxed{\pi=\frac c d}$ `\boxed{\pi=\frac c d}` | +| $a_{\angl n}$ `$a_{\angl n}` | $a_\angln$ `a_\angln` | +| $\overbracket{a+b+c}^{\text{note}}$ `\overbracket{a+b+c}^{\text{note}}` | $\underbracket{a+b+c}_{\text{note}}$ `\underbracket{a+b+c}_{\text{note}}` | +| $\phase{-78^\circ}$`\phase{-78^\circ}` | | + + +`\tag{hi} x+y^{2x}` +$$\tag{hi} x+y^{2x}$$ + +`\tag*{hi} x+y^{2x}` +$$\tag*{hi} x+y^{2x}$$ + +### Line Breaks + +KaTeX 0.10.0+ will insert automatic line breaks in inline math after relations or binary operators such as “=” or “+”. These can be suppressed by `\nobreak` or by placing math inside a pair of braces, as in `{F=ma}`. `\allowbreak` will allow automatic line breaks at locations other than relations or operators. + +Hard line breaks are `\\` and `\newline`. + +In display math, KaTeX does not insert automatic line breaks. It ignores display math hard line breaks when rendering option `strict: true`. + +### Vertical Layout + +|||| +|:--------------|:----------------------------------------|:----- +|$x_n$ `x_n` |$\stackrel{!}{=}$ `\stackrel{!}{=}`| $a \atop b$ `a \atop b` +|$e^x$ `e^x` |$\overset{!}{=}$ `\overset{!}{=}` | $a\raisebox{0.25em}{$b$}c$ `a\raisebox{0.25em}{$b$}c` +|$_u^o $ `_u^o `| $\underset{!}{=}$ `\underset{!}{=}` | $a+\left(\vcenter{\frac{\frac a b}c}\right)$ `a+\left(\vcenter{\hbox{$\frac{\frac a b}c$}}\right)` +||| $$\sum_{\substack{0 +
+ +**Spacing** + +| Function | Produces | Function | Produces| +|:----------------|:-------------------|:---------------------|:--------------------------------------| +| `\,` | ³∕₁₈ em space | `\kern{distance}` | space, width = *distance* +| `\thinspace` | ³∕₁₈ em space | `\mkern{distance}` | space, width = *distance* +| `\>` | ⁴∕₁₈ em space | `\mskip{distance}` | space, width = *distance* +| `\:` | ⁴∕₁₈ em space | `\hskip{distance}` | space, width = *distance* +| `\medspace` | ⁴∕₁₈ em space | `\hspace{distance}` | space, width = *distance* +| `\;` | ⁵∕₁₈ em space | `\hspace*{distance}` | space, width = *distance* +| `\thickspace` | ⁵∕₁₈ em space | `\phantom{content}` | space the width and height of content +| `\enspace` | ½ em space | `\hphantom{content}` | space the width of content +| `\quad` | 1 em space | `\vphantom{content}` | a strut the height of content +| `\qquad` | 2 em space | `\!` | – ³∕₁₈ em space +| `~` | non-breaking space | `\negthinspace` | – ³∕₁₈ em space +| `\` | space | `\negmedspace` | – ⁴∕₁₈ em space +| `\nobreakspace` | non-breaking space | `\negthickspace` | – ⁵∕₁₈ em space +| `\space` | space | `\mathstrut` | `\vphantom{(}` + +
+ +**Notes:** + +`distance` will accept any of the [KaTeX units](#units). + +`\kern`, `\mkern`, `\mskip`, and `\hspace` accept unbraced distances, as in: `\kern1em`. + +`\mkern` and `\mskip` will not work in text mode and both will write a console warning for any unit except `mu`. + +
+ +## Logic and Set Theory + +$\gdef\VERT{|}$ + +||||| +|:--------------------|:--------------------------|:----------------------------|:----- +|$\forall$ `\forall` |$\complement$ `\complement`|$\therefore$ `\therefore` |$\emptyset$ `\emptyset` +|$\exists$ `\exists` |$\subset$ `\subset` |$\because$ `\because` |$\empty$ `\empty` +|$\exist$ `\exist` |$\supset$ `\supset` |$\mapsto$ `\mapsto` |$\varnothing$ `\varnothing` +|$\nexists$ `\nexists`|$\mid$ `\mid` |$\to$ `\to` |$\implies$ `\implies` +|$\in$ `\in` |$\land$ `\land` |$\gets$ `\gets` |$\impliedby$ `\impliedby` +|$\isin$ `\isin` |$\lor$ `\lor` |$\leftrightarrow$ `\leftrightarrow`|$\iff$ `\iff` +|$\notin$ `\notin` |$\ni$ `\ni` |$\notni$ `\notni` |$\neg$ `\neg` or `\lnot` +| | $\Set{ x \VERT x<\frac 1 2 }$
\Set{ x | x<\frac 1 2 } | $\set{x\VERT x<5}$
\set{x|x<5} || + +Direct Input: $∀ ∴ ∁ ∵ ∃ ∣ ∈ ∉ ∋ ⊂ ⊃ ∧ ∨ ↦ → ← ↔ ¬$ ℂ ℍ ℕ ℙ ℚ ℝ + +## Macros + +||| +|:-------------------------------------|:------ +|$\def\foo{x^2} \foo + \foo$ | `\def\foo{x^2} \foo + \foo` +|$\gdef\foo#1{#1^2} \foo{y} + \foo{y}$ | `\gdef\foo#1{#1^2} \foo{y} + \foo{y}` +| | `\edef\macroname#1#2…{definition to be expanded}` +| | `\xdef\macroname#1#2…{definition to be expanded}` +| | `\let\foo=\bar` +| | `\futurelet\foo\bar x` +| | `\global\def\macroname#1#2…{definition}` +| | `\newcommand\macroname[numargs]{definition}` +| | `\renewcommand\macroname[numargs]{definition}` +| | `\providecommand\macroname[numargs]{definition}` + +Macros can also be defined in the KaTeX [rendering options](options.md). + +Macros accept up to nine arguments: #1, #2, etc. + +
+ +
+ +Macros defined by `\gdef`, `\xdef`, `\global\def`, `\global\edef`, `\global\let`, and `\global\futurelet` will persist between math expressions. (Exception: macro persistence may be disabled. There are legitimate security reasons for that.) + +KaTeX has no `\par`, so all macros are long by default and `\long` will be ignored. + +Available functions include: + +`\char` `\mathchoice` `\TextOrMath` `\@ifstar` `\@ifnextchar` `\@firstoftwo` `\@secondoftwo` `\relax` `\expandafter` `\noexpand` + +@ is a valid character for commands, as if `\makeatletter` were in effect. + +## Operators + +### Big Operators + +||||| +|------------------|-------------------------|--------------------------|--------------| +| $\sum$ `\sum` | $\prod$ `\prod` | $\bigotimes$ `\bigotimes`| $\bigvee$ `\bigvee` +| $\int$ `\int` | $\coprod$ `\coprod` | $\bigoplus$ `\bigoplus` | $\bigwedge$ `\bigwedge` +| $\iint$ `\iint` | $\intop$ `\intop` | $\bigodot$ `\bigodot` | $\bigcap$ `\bigcap` +| $\iiint$ `\iiint`| $\smallint$ `\smallint` | $\biguplus$ `\biguplus` | $\bigcup$ `\bigcup` +| $\oint$ `\oint` | $\oiint$ `\oiint` | $\oiiint$ `\oiiint` | $\bigsqcup$ `\bigsqcup` + +Direct Input: $∫ ∬ ∭ ∮ ∏ ∐ ∑ ⋀ ⋁ ⋂ ⋃ ⨀ ⨁ ⨂ ⨄ ⨆$ ∯ ∰ + +### Binary Operators + +||||| +|-------------|-------------------|-------------------|--------------------| +| $+$ `+`| $\cdot$ `\cdot` | $\gtrdot$ `\gtrdot`| $x \pmod a$ `x \pmod a`| +| $-$ `-`| $\cdotp$ `\cdotp` | $\intercal$ `\intercal` | $x \pod a$ `x \pod a` | +| $/$ `/`| $\centerdot$ `\centerdot`| $\land$ `\land` | $\rhd$ `\rhd` | +| $*$ `*`| $\circ$ `\circ` | $\leftthreetimes$ `\leftthreetimes` | $\rightthreetimes$ `\rightthreetimes` | +| $\amalg$ `\amalg` | $\circledast$ `\circledast` | $\ldotp$ `\ldotp` | $\rtimes$ `\rtimes` | +| $\And$ `\And`| $\circledcirc$ `\circledcirc` | $\lor$ `\lor`| $\setminus$ `\setminus` | +| $\ast$ `\ast`| $\circleddash$ `\circleddash` | $\lessdot$ `\lessdot` | $\smallsetminus$ `\smallsetminus`| +| $\barwedge$ `\barwedge` | $\Cup$ `\Cup`| $\lhd$ `\lhd`| $\sqcap$ `\sqcap` | +| $\bigcirc$ `\bigcirc` | $\cup$ `\cup`| $\ltimes$ `\ltimes`| $\sqcup$ `\sqcup` | +| $\bmod$ `\bmod` | $\curlyvee$ `\curlyvee` | $x \mod a$ `x\mod a`| $\times$ `\times` | +| $\boxdot$ `\boxdot`| $\curlywedge$ `\curlywedge` | $\mp$ `\mp` | $\unlhd$ `\unlhd` | +| $\boxminus$ `\boxminus` | $\div$ `\div`| $\odot$ `\odot` | $\unrhd$ `\unrhd` | +| $\boxplus$ `\boxplus` | $\divideontimes$ `\divideontimes` | $\ominus$ `\ominus`| $\uplus$ `\uplus` | +| $\boxtimes$ `\boxtimes` | $\dotplus$ `\dotplus` | $\oplus$ `\oplus` | $\vee$ `\vee` | +| $\bullet$ `\bullet`| $\doublebarwedge$ `\doublebarwedge` | $\otimes$ `\otimes`| $\veebar$ `\veebar` | +| $\Cap$ `\Cap`| $\doublecap$ `\doublecap`| $\oslash$ `\oslash`| $\wedge$ `\wedge` | +| $\cap$ `\cap`| $\doublecup$ `\doublecup`| $\pm$ `\pm` or `\plusmn` | $\wr$ `\wr` | + +Direct Input: $+ - / * ⋅ ∘ ∙ ± × ÷ ∓ ∔ ∧ ∨ ∩ ∪ ≀ ⊎ ⊓ ⊔ ⊕ ⊖ ⊗ ⊘ ⊙ ⊚ ⊛ ⊝ ◯ ∖ {}$ + +### Fractions and Binomials + +|||| +|:--------------------------|:----------------------------|:----- +|$\frac{a}{b}$ `\frac{a}{b}`|$\tfrac{a}{b}$ `\tfrac{a}{b}`|$\genfrac ( ] {2pt}{1}a{a+1}$ `\genfrac ( ] {2pt}{1}a{a+1}` +|${a \over b}$ `{a \over b}`|$\dfrac{a}{b}$ `\dfrac{a}{b}`|${a \above{2pt} b+1}$ `{a \above{2pt} b+1}` +|$a/b$ `a/b` | |$\cfrac{a}{1 + \cfrac{1}{b}}$ `\cfrac{a}{1 + \cfrac{1}{b}}` + +|||| +|:------------------------------|:------------------------------|:-------- +|$\binom{n}{k}$ `\binom{n}{k}` |$\dbinom{n}{k}$ `\dbinom{n}{k}`|${n\brace k}$ `{n\brace k}` +|${n \choose k}$ `{n \choose k}`|$\tbinom{n}{k}$ `\tbinom{n}{k}`|${n\brack k}$ `{n\brack k}` + +### Math Operators + +||||| +|:--------------------|:--------------------|:----------------|:--------------| +| $\arcsin$ `\arcsin` | $\cosec$ `\cosec` | $\deg$ `\deg` | $\sec$ `\sec` | +| $\arccos$ `\arccos` | $\cosh$ `\cosh` | $\dim$ `\dim` | $\sin$ `\sin` | +| $\arctan$ `\arctan` | $\cot$ `\cot` | $\exp$ `\exp` | $\sinh$ `\sinh` | +| $\arctg$ `\arctg` | $\cotg$ `\cotg` | $\hom$ `\hom` | $\sh$ `\sh` | +| $\arcctg$ `\arcctg` | $\coth$ `\coth` | $\ker$ `\ker` | $\tan$ `\tan` | +| $\arg$ `\arg` | $\csc$ `\csc` | $\lg$ `\lg` | $\tanh$ `\tanh` | +| $\ch$ `\ch` | $\ctg$ `\ctg` | $\ln$ `\ln` | $\tg$ `\tg` | +| $\cos$ `\cos` | $\cth$ `\cth` | $\log$ `\log` | $\th$ `\th` | +| $\operatorname{f}$ `\operatorname{f}` | ||| +| $\argmax$ `\argmax` | $\injlim$ `\injlim` | $\min$ `\min` | $\varinjlim$ `\varinjlim` | +| $\argmin$ `\argmin` | $\lim$ `\lim` | $\plim$ `\plim` | $\varliminf$ `\varliminf` | +| $\det$ `\det` | $\liminf$ `\liminf` | $\Pr$ `\Pr` | $\varlimsup$ `\varlimsup` | +| $\gcd$ `\gcd` | $\limsup$ `\limsup` | $\projlim$ `\projlim` | $\varprojlim$ `\varprojlim` | +| $\inf$ `\inf` | $\max$ `\max` | $\sup$ `\sup` || +| $\operatorname*{f}$ `\operatorname*{f}` | $\operatornamewithlimits{f}$ `\operatornamewithlimits{f}` ||| + +Functions in the bottom six rows of this table can take `\limits`. + +### \sqrt + +$\sqrt{x}$ `\sqrt{x}` + +$\sqrt[3]{x}$ `\sqrt[3]{x}` + +## Relations + +$\stackrel{!}{=}$ `\stackrel{!}{=}` + +||||| +|:--------|:------------------------|:----------------------------|:------------------| +| $=$ `=` | $\doteqdot$ `\doteqdot` | $\lessapprox$ `\lessapprox` | $\smile$ `\smile` | +| $<$ `<` | $\eqcirc$ `\eqcirc` | $\lesseqgtr$ `\lesseqgtr` | $\sqsubset$ `\sqsubset` | +| $>$ `>` | $\eqcolon$ `\eqcolon` or
    `\minuscolon` | $\lesseqqgtr$ `\lesseqqgtr` | $\sqsubseteq$ `\sqsubseteq` | +| $:$ `:` | $\Eqcolon$ `\Eqcolon` or
    `\minuscoloncolon` | $\lessgtr$ `\lessgtr` | $\sqsupset$ `\sqsupset` | +| $\approx$ `\approx` | $\eqqcolon$ `\eqqcolon` or
    `\equalscolon` | $\lesssim$ `\lesssim` | $\sqsupseteq$ `\sqsupseteq` | +| $\approxcolon$ `\approxcolon` | $\Eqqcolon$ `\Eqqcolon` or
    `\equalscoloncolon` | $\ll$ `\ll` | $\Subset$ `\Subset` | +| $\approxcoloncolon$ `\approxcoloncolon` | $\eqsim$ `\eqsim` | $\lll$ `\lll` | $\subset$ `\subset` or `\sub` | +| $\approxeq$ `\approxeq` | $\eqslantgtr$ `\eqslantgtr` | $\llless$ `\llless` | $\subseteq$ `\subseteq` or `\sube` | +| $\asymp$ `\asymp` | $\eqslantless$ `\eqslantless` | $\lt$ `\lt` | $\subseteqq$ `\subseteqq` | +| $\backepsilon$ `\backepsilon` | $\equiv$ `\equiv` | $\mid$ `\mid` | $\succ$ `\succ` | +| $\backsim$ `\backsim` | $\fallingdotseq$ `\fallingdotseq` | $\models$ `\models` | $\succapprox$ `\succapprox` | +| $\backsimeq$ `\backsimeq` | $\frown$ `\frown` | $\multimap$ `\multimap` | $\succcurlyeq$ `\succcurlyeq` | +| $\between$ `\between` | $\ge$ `\ge` | $\origof$ `\origof` | $\succeq$ `\succeq` | +| $\bowtie$ `\bowtie` | $\geq$ `\geq` | $\owns$ `\owns` | $\succsim$ `\succsim` | +| $\bumpeq$ `\bumpeq` | $\geqq$ `\geqq` | $\parallel$ `\parallel` | $\Supset$ `\Supset` | +| $\Bumpeq$ `\Bumpeq` | $\geqslant$ `\geqslant` | $\perp$ `\perp` | $\supset$ `\supset` | +| $\circeq$ `\circeq` | $\gg$ `\gg` | $\pitchfork$ `\pitchfork` | $\supseteq$ `\supseteq` or `\supe` | +| $\colonapprox$ `\colonapprox` | $\ggg$ `\ggg` | $\prec$ `\prec` | $\supseteqq$ `\supseteqq` | +| $\Colonapprox$ `\Colonapprox` or
    `\coloncolonapprox` | $\gggtr$ `\gggtr` | $\precapprox$ `\precapprox` | $\thickapprox$ `\thickapprox` | +| $\coloneq$ `\coloneq` or
    `\colonminus` | $\gt$ `\gt` | $\preccurlyeq$ `\preccurlyeq` | $\thicksim$ `\thicksim` | +| $\Coloneq$ `\Coloneq` or
    `\coloncolonminus` | $\gtrapprox$ `\gtrapprox` | $\preceq$ `\preceq` | $\trianglelefteq$ `\trianglelefteq` | +| $\coloneqq$ `\coloneqq` or
   `\colonequals` | $\gtreqless$ `\gtreqless` | $\precsim$ `\precsim` | $\triangleq$ `\triangleq` | +| $\Coloneqq$ `\Coloneqq` or
    `\coloncolonequals` | $\gtreqqless$ `\gtreqqless` | $\propto$ `\propto` | $\trianglerighteq$ `\trianglerighteq` | +| $\colonsim$ `\colonsim` | $\gtrless$ `\gtrless` | $\risingdotseq$ `\risingdotseq` | $\varpropto$ `\varpropto` | +| $\Colonsim$ `\Colonsim` or
    `\coloncolonsim` | $\gtrsim$ `\gtrsim` | $\shortmid$ `\shortmid` | $\vartriangle$ `\vartriangle` | +| $\cong$ `\cong` | $\imageof$ `\imageof` | $\shortparallel$ `\shortparallel` | $\vartriangleleft$ `\vartriangleleft` | +| $\curlyeqprec$ `\curlyeqprec` | $\in$ `\in` or `\isin` | $\sim$ `\sim` | $\vartriangleright$ `\vartriangleright` | +| $\curlyeqsucc$ `\curlyeqsucc` | $\Join$ `\Join` | $\simcolon$ `\simcolon` | $\vcentcolon$ `\vcentcolon` or
   `\ratio` | +| $\dashv$ `\dashv` | $\le$ `\le` | $\simcoloncolon$ `\simcoloncolon` | $\vdash$ `\vdash` | +| $\dblcolon$ `\dblcolon` or
   `\coloncolon` | $\leq$ `\leq` | $\simeq$ `\simeq` | $\vDash$ `\vDash` | +| $\doteq$ `\doteq` | $\leqq$ `\leqq` | $\smallfrown$ `\smallfrown` | $\Vdash$ `\Vdash` | +| $\Doteq$ `\Doteq` | $\leqslant$ `\leqslant` | $\smallsmile$ `\smallsmile` | $\Vvdash$ `\Vvdash` | + +Direct Input: $= < > : ∈ ∋ ∝ ∼ ∽ ≂ ≃ ≅ ≈ ≊ ≍ ≎ ≏ ≐ ≑ ≒ ≓ ≖ ≗ ≜ ≡ ≤ ≥ ≦ ≧ ≫ ≬ ≳ ≷ ≺ ≻ ≼ ≽ ≾ ≿ ⊂ ⊃ ⊆ ⊇ ⊏ ⊐ ⊑ ⊒ ⊢ ⊣ ⊩ ⊪ ⊸ ⋈ ⋍ ⋐ ⋑ ⋔ ⋙ ⋛ ⋞ ⋟ ⌢ ⌣ ⩾ ⪆ ⪌ ⪕ ⪖ ⪯ ⪰ ⪷ ⪸ ⫅ ⫆ ≲ ⩽ ⪅ ≶ ⋚ ⪋ ⟂ ⊨ ⊶ ⊷$ `≔ ≕ ⩴` + +### Negated Relations + +$\not =$ `\not =` + +||||| +|--------------|-------------------|---------------------|------------------| +| $\gnapprox$ `\gnapprox` | $\ngeqslant$ `\ngeqslant`| $\nsubseteq$ `\nsubseteq` | $\precneqq$ `\precneqq`| +| $\gneq$ `\gneq`| $\ngtr$ `\ngtr` | $\nsubseteqq$ `\nsubseteqq` | $\precnsim$ `\precnsim`| +| $\gneqq$ `\gneqq` | $\nleq$ `\nleq` | $\nsucc$ `\nsucc`| $\subsetneq$ `\subsetneq` | +| $\gnsim$ `\gnsim` | $\nleqq$ `\nleqq` | $\nsucceq$ `\nsucceq` | $\subsetneqq$ `\subsetneqq` | +| $\gvertneqq$ `\gvertneqq` | $\nleqslant$ `\nleqslant`| $\nsupseteq$ `\nsupseteq` | $\succnapprox$ `\succnapprox`| +| $\lnapprox$ `\lnapprox` | $\nless$ `\nless` | $\nsupseteqq$ `\nsupseteqq` | $\succneqq$ `\succneqq`| +| $\lneq$ `\lneq`| $\nmid$ `\nmid` | $\ntriangleleft$ `\ntriangleleft` | $\succnsim$ `\succnsim`| +| $\lneqq$ `\lneqq` | $\notin$ `\notin` | $\ntrianglelefteq$ `\ntrianglelefteq` | $\supsetneq$ `\supsetneq` | +| $\lnsim$ `\lnsim` | $\notni$ `\notni` | $\ntriangleright$ `\ntriangleright`| $\supsetneqq$ `\supsetneqq` | +| $\lvertneqq$ `\lvertneqq` | $\nparallel$ `\nparallel`| $\ntrianglerighteq$ `\ntrianglerighteq` | $\varsubsetneq$ `\varsubsetneq` | +| $\ncong$ `\ncong` | $\nprec$ `\nprec` | $\nvdash$ `\nvdash` | $\varsubsetneqq$ `\varsubsetneqq` | +| $\ne$ `\ne` | $\npreceq$ `\npreceq` | $\nvDash$ `\nvDash` | $\varsupsetneq$ `\varsupsetneq` | +| $\neq$ `\neq` | $\nshortmid$ `\nshortmid`| $\nVDash$ `\nVDash` | $\varsupsetneqq$ `\varsupsetneqq` | +| $\ngeq$ `\ngeq`| $\nshortparallel$ `\nshortparallel` | $\nVdash$ `\nVdash` | +| $\ngeqq$ `\ngeqq` | $\nsim$ `\nsim` | $\precnapprox$ `\precnapprox`| + +Direct Input: $∉ ∌ ∤ ∦ ≁ ≆ ≠ ≨ ≩ ≮ ≯ ≰ ≱ ⊀ ⊁ ⊈ ⊉ ⊊ ⊋ ⊬ ⊭ ⊮ ⊯ ⋠ ⋡ ⋦ ⋧ ⋨ ⋩ ⋬ ⋭ ⪇ ⪈ ⪉ ⪊ ⪵ ⪶ ⪹ ⪺ ⫋ ⫌$ + +### Arrows + +|||| +|:----------|:----------|:----------| +|$\circlearrowleft$ `\circlearrowleft`|$\leftharpoonup$ `\leftharpoonup`|$\rArr$ `\rArr` +|$\circlearrowright$ `\circlearrowright`|$\leftleftarrows$ `\leftleftarrows`|$\rarr$ `\rarr` +|$\curvearrowleft$ `\curvearrowleft`|$\leftrightarrow$ `\leftrightarrow`|$\restriction$ `\restriction` +|$\curvearrowright$ `\curvearrowright`|$\Leftrightarrow$ `\Leftrightarrow`|$\rightarrow$ `\rightarrow` +|$\Darr$ `\Darr`|$\leftrightarrows$ `\leftrightarrows`|$\Rightarrow$ `\Rightarrow` +|$\dArr$ `\dArr`|$\leftrightharpoons$ `\leftrightharpoons`|$\rightarrowtail$ `\rightarrowtail` +|$\darr$ `\darr`|$\leftrightsquigarrow$ `\leftrightsquigarrow`|$\rightharpoondown$ `\rightharpoondown` +|$\dashleftarrow$ `\dashleftarrow`|$\Lleftarrow$ `\Lleftarrow`|$\rightharpoonup$ `\rightharpoonup` +|$\dashrightarrow$ `\dashrightarrow`|$\longleftarrow$ `\longleftarrow`|$\rightleftarrows$ `\rightleftarrows` +|$\downarrow$ `\downarrow`|$\Longleftarrow$ `\Longleftarrow`|$\rightleftharpoons$ `\rightleftharpoons` +|$\Downarrow$ `\Downarrow`|$\longleftrightarrow$ `\longleftrightarrow`|$\rightrightarrows$ `\rightrightarrows` +|$\downdownarrows$ `\downdownarrows`|$\Longleftrightarrow$ `\Longleftrightarrow`|$\rightsquigarrow$ `\rightsquigarrow` +|$\downharpoonleft$ `\downharpoonleft`|$\longmapsto$ `\longmapsto`|$\Rrightarrow$ `\Rrightarrow` +|$\downharpoonright$ `\downharpoonright`|$\longrightarrow$ `\longrightarrow`|$\Rsh$ `\Rsh` +|$\gets$ `\gets`|$\Longrightarrow$ `\Longrightarrow`|$\searrow$ `\searrow` +|$\Harr$ `\Harr`|$\looparrowleft$ `\looparrowleft`|$\swarrow$ `\swarrow` +|$\hArr$ `\hArr`|$\looparrowright$ `\looparrowright`|$\to$ `\to` +|$\harr$ `\harr`|$\Lrarr$ `\Lrarr`|$\twoheadleftarrow$ `\twoheadleftarrow` +|$\hookleftarrow$ `\hookleftarrow`|$\lrArr$ `\lrArr`|$\twoheadrightarrow$ `\twoheadrightarrow` +|$\hookrightarrow$ `\hookrightarrow`|$\lrarr$ `\lrarr`|$\Uarr$ `\Uarr` +|$\iff$ `\iff`|$\Lsh$ `\Lsh`|$\uArr$ `\uArr` +|$\impliedby$ `\impliedby`|$\mapsto$ `\mapsto`|$\uarr$ `\uarr` +|$\implies$ `\implies`|$\nearrow$ `\nearrow`|$\uparrow$ `\uparrow` +|$\Larr$ `\Larr`|$\nleftarrow$ `\nleftarrow`|$\Uparrow$ `\Uparrow` +|$\lArr$ `\lArr`|$\nLeftarrow$ `\nLeftarrow`|$\updownarrow$ `\updownarrow` +|$\larr$ `\larr`|$\nleftrightarrow$ `\nleftrightarrow`|$\Updownarrow$ `\Updownarrow` +|$\leadsto$ `\leadsto`|$\nLeftrightarrow$ `\nLeftrightarrow`|$\upharpoonleft$ `\upharpoonleft` +|$\leftarrow$ `\leftarrow`|$\nrightarrow$ `\nrightarrow`|$\upharpoonright$ `\upharpoonright` +|$\Leftarrow$ `\Leftarrow`|$\nRightarrow$ `\nRightarrow`|$\upuparrows$ `\upuparrows` +|$\leftarrowtail$ `\leftarrowtail`|$\nwarrow$ `\nwarrow` +|$\leftharpoondown$ `\leftharpoondown`|$\Rarr$ `\Rarr` + +Direct Input: $← ↑ → ↓ ↔ ↕ ↖ ↗ ↘ ↙ ↚ ↛ ↞ ↠ ↢ ↣ ↦ ↩ ↪ ↫ ↬ ↭ ↮ ↰ ↱↶ ↷ ↺ ↻ ↼ ↽ ↾ ↾ ↿ ⇀ ⇁ ⇂ ⇃ ⇄ ⇆ ⇇ ⇈ ⇉ ⇊ ⇋ ⇌⇍ ⇎ ⇏ ⇐ ⇑ ⇒ ⇓ ⇔ ⇕ ⇚ ⇛ ⇝ ⇠ ⇢ ⟵ ⟶ ⟷ ⟸ ⟹ ⟺ ⟼$ ↽ + +**Extensible Arrows** + +||| +|:----------------------------------------------------|:----- +|$\xleftarrow{abc}$ `\xleftarrow{abc}` |$\xrightarrow[under]{over}$ `\xrightarrow[under]{over}` +|$\xLeftarrow{abc}$ `\xLeftarrow{abc}` |$\xRightarrow{abc}$ `\xRightarrow{abc}` +|$\xleftrightarrow{abc}$ `\xleftrightarrow{abc}` |$\xLeftrightarrow{abc}$ `\xLeftrightarrow{abc}` +|$\xhookleftarrow{abc}$ `\xhookleftarrow{abc}` |$\xhookrightarrow{abc}$ `\xhookrightarrow{abc}` +|$\xtwoheadleftarrow{abc}$ `\xtwoheadleftarrow{abc}` |$\xtwoheadrightarrow{abc}$ `\xtwoheadrightarrow{abc}` +|$\xleftharpoonup{abc}$ `\xleftharpoonup{abc}` |$\xrightharpoonup{abc}$ `\xrightharpoonup{abc}` +|$\xleftharpoondown{abc}$ `\xleftharpoondown{abc}` |$\xrightharpoondown{abc}$ `\xrightharpoondown{abc}` +|$\xleftrightharpoons{abc}$ `\xleftrightharpoons{abc}`|$\xrightleftharpoons{abc}$ `\xrightleftharpoons{abc}` +|$\xtofrom{abc}$ `\xtofrom{abc}` |$\xmapsto{abc}$ `\xmapsto{abc}` +|$\xlongequal{abc}$ `\xlongequal{abc}` + +Extensible arrows all can take an optional argument in the same manner
as `\xrightarrow[under]{over}`. + +## Special Notation + +**Bra-ket Notation** + +|||| +|:----------|:----------|:----------| +|$\bra{\phi}$ `\bra{\phi}` |$\ket{\psi}$ `\ket{\psi}` |$\braket{\phi\VERT\psi}$ \braket{\phi|\psi} | +|$\Bra{\phi}$ `\Bra{\phi}` |$\Ket{\psi}$ `\Ket{\psi}` |$\Braket{ ϕ \VERT \frac{∂^2}{∂ t^2} \VERT ψ }$ \Braket{ ϕ | \frac{∂^2}{∂ t^2} | ψ }| + +## Style, Color, Size, and Font + +**Class Assignment** + +`\mathbin` `\mathclose` `\mathinner` `\mathop`
+`\mathopen` `\mathord` `\mathpunct` `\mathrel` + +**Color** + +$\color{blue} F=ma$ `\color{blue} F=ma` + +Note that `\color` acts like a switch. Other color functions expect the content to be a function argument: + +$\textcolor{blue}{F=ma}$ `\textcolor{blue}{F=ma}`
+$\textcolor{#228B22}{F=ma}$ `\textcolor{#228B22}{F=ma}`
+$\colorbox{aqua}{$F=ma$}$ `\colorbox{aqua}{$F=ma$}`
+$\fcolorbox{red}{aqua}{$F=ma$}$ `\fcolorbox{red}{aqua}{$F=ma$}` + +Note that, as in LaTeX, `\colorbox` & `\fcolorbox` renders its third argument as text, so you may want to switch back to math mode with `$` as in the examples above. + +For color definition, KaTeX color functions will accept the standard HTML [predefined color names](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#Color_keywords). They will also accept an RGB argument in CSS hexa­decimal style. The "#" is optional before a six-digit specification. + +**Font** + +|||| +|:------------------------------------|:------------------------------------|:--------------------------------| +|$\mathrm{Ab0}$ `\mathrm{Ab0}` |$\mathbf{Ab0}$ `\mathbf{Ab0}` |$\mathsf{Ab0}$ `\mathsf{Ab0}` | +|$\mathnormal{Ab0}$ `\mathnormal{Ab0}`|$\textbf{Ab0}$ `\textbf{Ab0}` |$\textsf{Ab0}$ `\textsf{Ab0}` | +|$\textrm{Ab0}$ `\textrm{Ab0}` |$\bf Ab0$ `\bf Ab0` |$\sf Ab0$ `\sf Ab0` | +|$\rm Ab0$ `\rm Ab0` |$\bold{Ab0}$ `\bold{Ab0}` |$\mathsfit{Ab0}$ `\mathsfit{Ab0}`| +|$\textnormal{Ab0}$ `\textnormal{Ab0}`|$\boldsymbol{Ab0}$ `\boldsymbol{Ab0}`|$\Bbb{AB}$ `\Bbb{AB}` | +|$\text{Ab0}$ `\text{Ab0}` |$\bm{Ab0}$ `\bm{Ab0}` |$\mathbb{AB}$ `\mathbb{AB}` | +|$\textup{Ab0}$ `\textup{Ab0}` |$\textmd{Ab0}$ `\textmd{Ab0}` |$\frak{Ab0}$ `\frak{Ab0}` | +|$\mathit{Ab0}$ `\mathit{Ab0}` |$\mathtt{Ab0}$ `\mathtt{Ab0}` |$\mathfrak{Ab0}$ `\mathfrak{Ab0}`| +|$\textit{Ab0}$ `\textit{Ab0}` |$\texttt{Ab0}$ `\texttt{Ab0}` |$\mathcal{AB0}$ `\mathcal{AB0}` | +|$\it Ab0$ `\it Ab0` |$\tt Ab0$ `\tt Ab0` |$\cal AB0$ `\cal AB0` | +|$\emph{Ab0}$ `\emph{Ab0}` | |$\mathscr{AB}$ `\mathscr{AB}` | + +One can stack font family, font weight, and font shape by using the `\textXX` versions of the font functions. So `\textsf{\textbf{H}}` will produce $\textsf{\textbf{H}}$. The other versions do not stack, e.g., `\mathsf{\mathbf{H}}` will produce $\mathsf{\mathbf{H}}$. + +In cases where KaTeX fonts do not have a bold glyph, `\pmb` can simulate one. For example, `\pmb{\mu}` renders as : $\pmb{\mu}$ + +**Size** + +||| +|:----------------------|:----- +|$\Huge AB$ `\Huge AB` |$\normalsize AB$ `\normalsize AB` +|$\huge AB$ `\huge AB` |$\small AB$ `\small AB` +|$\LARGE AB$ `\LARGE AB`|$\footnotesize AB$ `\footnotesize AB` +|$\Large AB$ `\Large AB`|$\scriptsize AB$ `\scriptsize AB` +|$\large AB$ `\large AB`|$\tiny AB$ `\tiny AB` + + +**Style** + +|| +|:-------------------------------------------------------| +|$\displaystyle\sum_{i=1}^n$ `\displaystyle\sum_{i=1}^n` +|$\textstyle\sum_{i=1}^n$ `\textstyle\sum_{i=1}^n` +|$\scriptstyle x$ `\scriptstyle x`         (The size of a first sub/superscript) +|$\scriptscriptstyle x$ `\scriptscriptstyle x` (The size of subsequent sub/superscripts) +|$\lim\limits_x$ `\lim\limits_x` +|$\lim\nolimits_x$ `\lim\nolimits_x` +|$\verb!x^2!$ `\verb!x^2!` + +`\text{…}` will accept nested `$…$` fragments and render them in math mode. + +## Symbols and Punctuation + +|||| +|:----------|:----------|:----------| +|`% comment`|$\dots$ `\dots`|$\KaTeX$ `\KaTeX` +|$\%$ `\%`|$\cdots$ `\cdots`|$\LaTeX$ `\LaTeX` +|$\#$ `\#`|$\ddots$ `\ddots`|$\TeX$ `\TeX` +|$\&$ `\&`|$\ldots$ `\ldots`|$\nabla$ `\nabla` +|$\_$ `\_`|$\vdots$ `\vdots`|$\infty$ `\infty` +|$\text{\textunderscore}$ `\text{\textunderscore}`|$\dotsb$ `\dotsb`|$\infin$ `\infin` +|$\text{--}$ `\text{--}`|$\dotsc$ `\dotsc`|$\checkmark$ `\checkmark` +|$\text{\textendash}$ `\text{\textendash}`|$\dotsi$ `\dotsi`|$\dag$ `\dag` +|$\text{---}$ `\text{---}`|$\dotsm$ `\dotsm`|$\dagger$ `\dagger` +|$\text{\textemdash}$ `\text{\textemdash}`|$\dotso$ `\dotso`|$\text{\textdagger}$ `\text{\textdagger}` +|$\text{\textasciitilde}$ `\text{\textasciitilde}`|$\sdot$ `\sdot`|$\ddag$ `\ddag` +|$\text{\textasciicircum}$ `\text{\textasciicircum}`|$\mathellipsis$ `\mathellipsis`|$\ddagger$ `\ddagger` +|$`$ `|$\text{\textellipsis}$ `\text{\textellipsis}`|$\text{\textdaggerdbl}$ `\text{\textdaggerdbl}` +|$\text{\textquoteleft}$ `\text{\textquoteleft}`|$\Box$ `\Box`|$\Dagger$ `\Dagger` +|$\lq$ `\lq`|$\square$ `\square`|$\angle$ `\angle` +|$\text{\textquoteright}$ `\text{\textquoteright}`|$\blacksquare$ `\blacksquare`|$\measuredangle$ `\measuredangle` +|$\rq$ `\rq`|$\triangle$ `\triangle`|$\sphericalangle$ `\sphericalangle` +|$\text{\textquotedblleft}$ `\text{\textquotedblleft}`|$\triangledown$ `\triangledown`|$\top$ `\top` +|$"$ `"`|$\triangleleft$ `\triangleleft`|$\bot$ `\bot` +|$\text{\textquotedblright}$ `\text{\textquotedblright}`|$\triangleright$ `\triangleright`|$\$$ `\$` +|$\colon$ `\colon`|$\bigtriangledown$ `\bigtriangledown`|$\text{\textdollar}$ `\text{\textdollar}` +|$\backprime$ `\backprime`|$\bigtriangleup$ `\bigtriangleup`|$\pounds$ `\pounds` +|$\prime$ `\prime`|$\blacktriangle$ `\blacktriangle`|$\mathsterling$ `\mathsterling` +|$\text{\textless}$ `\text{\textless}`|$\blacktriangledown$ `\blacktriangledown`|$\text{\textsterling}$ `\text{\textsterling}` +|$\text{\textgreater}$ `\text{\textgreater}`|$\blacktriangleleft$ `\blacktriangleleft`|$\yen$ `\yen` +|$\text{\textbar}$ `\text{\textbar}`|$\blacktriangleright$ `\blacktriangleright`|$\surd$ `\surd` +|$\text{\textbardbl}$ `\text{\textbardbl}`|$\diamond$ `\diamond`|$\degree$ `\degree` +|$\text{\textbraceleft}$ `\text{\textbraceleft}`|$\Diamond$ `\Diamond`|$\text{\textdegree}$ `\text{\textdegree}` +|$\text{\textbraceright}$ `\text{\textbraceright}`|$\lozenge$ `\lozenge`|$\mho$ `\mho` +|$\text{\textbackslash}$ `\text{\textbackslash}`|$\blacklozenge$ `\blacklozenge`|$\diagdown$ `\diagdown` +|$\text{\P}$ `\text{\P}` or `\P`|$\star$ `\star`|$\diagup$ `\diagup` +|$\text{\S}$ `\text{\S}` or `\S`|$\bigstar$ `\bigstar`|$\flat$ `\flat` +|$\text{\sect}$ `\text{\sect}`|$\clubsuit$ `\clubsuit`|$\natural$ `\natural` +|$\copyright$ `\copyright`|$\clubs$ `\clubs`|$\sharp$ `\sharp` +|$\circledR$ `\circledR`|$\diamondsuit$ `\diamondsuit`|$\heartsuit$ `\heartsuit` +|$\text{\textregistered}$ `\text{\textregistered}`|$\diamonds$ `\diamonds`|$\hearts$ `\hearts` +|$\circledS$ `\circledS`|$\spadesuit$ `\spadesuit`|$\spades$ `\spades` +|$\text{\textcircled a}$ `\text{\textcircled a}`|$\maltese$ `\maltese`|$\minuso$ `\minuso`| + +Direct Input: § ¶ $ £ ¥ ∇ ∞ · ∠ ∡ ∢ ♠ ♡ ♢ ♣ ♭ ♮ ♯ ✓ … ⋮ ⋯ ⋱ !$ ‼ ⦵ + +## Units + +In KaTeX, units are proportioned as they are in TeX.
+KaTeX units are different than CSS units. + +
+
+ +| KaTeX Unit | Value | KaTeX Unit | Value | +|:---|:---------------------|:---|:----------------| +| em | CSS em | bp | 1/72​ inch × F × G| +| ex | CSS ex | pc | 12 KaTeX pt| +| mu | 1/18 CSS em | dd | 1238/1157​ KaTeX pt | +| pt | 1/72.27 inch × F × G | cc | 14856/1157 KaTeX pt | +| mm | 1 mm × F × G | nd | 685/642 KaTeX pt | +| cm | 1 cm × F × G | nc | 1370/107​ KaTeX pt| +| in | 1 inch × F × G | sp | 1/65536 KaTeX pt | + +
+ +where: + +
+ +F = (font size of surrounding HTML text)/(10 pt) + +G = 1.21 by default, because KaTeX font-size is normally 1.21 × the surrounding font size. This value [can be overridden](font.md#font-size-and-lengths) by the CSS of an HTML page. + +
+ +The effect of style and size: + +
+ +| Unit | textstyle | scriptscript | huge | +|:------:|:-----------------:|:------------:|:------:| +|em or ex|$\rule{1em}{1em}$ |$\scriptscriptstyle\rule{1em}{1em}$ |$\huge\rule{1em}{1em}$ +| mu |$\rule{18mu}{18mu}$|$\scriptscriptstyle\rule{18mu}{18mu}$|$\huge\rule{18mu}{18mu}$ +| others |$\rule{10pt}{10pt}$|$\scriptscriptstyle\rule{10pt}{10pt}$|$\huge\rule{10pt}{10pt}$ + +
diff --git a/markup/math/SimpleFormula_a6349f.odf b/markup/math/SimpleFormula_a6349f.odf new file mode 100644 index 0000000..0e10240 Binary files /dev/null and b/markup/math/SimpleFormula_a6349f.odf differ diff --git a/markup/math/aGHQ_b16faa.qmd b/markup/math/aGHQ_b16faa.qmd new file mode 100644 index 0000000..1c7dc9d --- /dev/null +++ b/markup/math/aGHQ_b16faa.qmd @@ -0,0 +1,1452 @@ +--- +fig-width: 4 +fig-height: 3 +fig-dpi: 192 +fig-format: png +engine: julia +execute: + cache: true +julia: + exeflags: ["--project"] +--- + +# GLMM log-likelihood {#sec-GLMMdeviance} + +\newcommand\bbb{{\mathbf{b}}} +\newcommand\bbg{{\mathbf{g}}} +\newcommand\bbI{{\mathbf{I}}} +\newcommand\bbL{{\mathbf{L}}} +\newcommand\bbo{{\mathbf{o}}} +\newcommand\bbr{{\mathbf{r}}} +\newcommand\bbu{{\mathbf{u}}} +\newcommand\bbW{{\mathbf{W}}} +\newcommand\bbX{{\mathbf{X}}} +\newcommand\bby{{\mathbf{y}}} +\newcommand\bbZ{{\mathbf{Z}}} +\newcommand\bbzero{{\mathbf{0}}} +\newcommand\bbbeta{{\boldsymbol{\beta}}} +\newcommand\bbeta{{\boldsymbol{\eta}}} +\newcommand\bbLambda{{\boldsymbol{\Lambda}}} +\newcommand\bbmu{{\boldsymbol{\mu}}} +\newcommand\bbtheta{{\boldsymbol{\theta}}} +\newcommand\mcB{{\mathcal{B}}} +\newcommand\mcD{{\mathcal{D}}} +\newcommand\mcI{{\mathcal{I}}} +\newcommand\mcL{{\mathcal{L}}} +\newcommand\mcN{{\mathcal{N}}} +\newcommand\mcU{{\mathcal{U}}} +\newcommand\mcX{{\mathcal{X}}} +\newcommand\mcY{{\mathcal{Y}}} + +The log-likelihood for a linear mixed model (LMM) was derived in @sec-lmmtheory, where some computational methods for fitting such models with [MixedModels.jl](https://github.com/JuliaStats/MixedModels.jl), by optimizing a *profiled log-likelihood*, were illustrated. + +In this appendix we outline the evaluation of the log-likelihood for a generalized linear mixed model (GLMM) with a binary response, which is modelled using the [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution). + +## The Bernoulli GLMM + +The Bernoulli GLMM model defines the conditional distribution $({\mcY}|{\mcB}={\bbb})$ as independent Bernoulli random variables with expected values ${\bbmu}={\bbg}^{-1}({\bbeta})$, where ${\bbeta}={\bbX}{\bbbeta}+{\bbZ}{\bbb}$ is the *linear predictor* and $\bbg^{-1}$ is an *inverse link function*. + +We will use the *logit link function*, $\bbeta=\bbg(\bbmu)$, defined component-wise from the scalar logit link, $g$, as +$$ +\eta_i=g(\mu_i)=\mathrm{logit}(\mu_i)=\log\left(\frac{\mu_i}{1-\mu_i}\right)\quad i=1,\dots,n . +$$ +The inverse link, $\bbmu=\bbg^{-1}(\bbeta)$, is similarly defined component-wise from the inverse of the scalar logit, which is the scalar *logistic* function, +$$ +\mu_i=g^{-1}(\eta_i)=\mathrm{logistic}(\eta_i)=\frac{1}{1+e^{-\eta_i}}\quad i=1,\dots,n . +$$ {#eq-scalarlogistic} +The logit is the *canonical link function* (@sec-logitlink) for the Bernoulli distribution. + +As in the linear mixed model discussed in @sec-lmmtheory, the $q$-dimensional random effects, $\mcB$, are expressed as $\mcB=\bbLambda_{\bbtheta}\,\mcU$ where $\mcU$ has a standard, multivariate Gaussian distribution (@sec-multivariateGaussian) +$$ +\mcU\sim\mcN(\bbzero,\bbI_q) , +$$ {#eq-MVNUdistGLMM} +with probability density function +$$ +f_{\mcU}(\bbu)=\frac{1}{\sqrt{2\pi}^q}e^{-\|\bbu\|^2/2} . +$$ {#eq-uunconddense} + +For a linear mixed model the distribution of these *spherical random effects* was given as $\mcU\sim(\bbzero,\sigma^2\bbI_q)$ (@eq-sphericalre). +A dispersion parameter like $\sigma^2$ is not present in @eq-MVNUdistGLMM because the Bernoulli distribution does not have a separate dispersion parameter --- it is entirely determined by its mean. + +As is the case for the linear mixed model, the *covariance factor*, $\bbLambda_{\bbtheta}$, is sparse and patterned. +It is not uncommon in practical examples, such as the one in @sec-PIRLS, for +$\bbtheta$ to be one-dimensional and $\bbLambda_{\bbtheta}=\theta\,\bbI_q$, to be a scalar multiple of the $q\times q$ identity matrix. + +### Log-likelihood for a Bernoulli GLMM + +The likelihood for the parameters, $\bbtheta$ and $\bbbeta$, given the observed data, $\bby$, is the value of the marginal probability mass function for the response, $\mcY$, evaluated at $\bby$, the observed vector of {0,1} responses. +We obtain this value by integrating the product of the probability mass function for the conditional distribution, $(\mcY|\mcU=\bbu)$, and unconditional density of $\mcU$ (@eq-uunconddense), with respect to $\bbu$. + +Recall that the probability mass for a single Bernoulli response can be written as $(1-\mu)^{1-y}\mu^y$, which is the specialization to $n=1$ of the probability mass function for the [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) +$$ +\binom{n}{y}(1-\mu)^{n-y}\mu^y ,\quad 0\le\mu\le 1, \quad y\in\{0,\dots,n\} . +$$ +Because the components of the vector-valued conditional distribution, $(\mcY|\mcU=\bbu)$, are assumed to be independent, its probability mass function can be written as the product of the probability masses for each component +$$ +f_{\mcY|\mcU=\bbu}(\bby|\bbu)=\prod_{i=1}^n \left[(1-\mu_i)^{1-y_i}\mu_i^{y_i}\right] +\quad\mathrm{where}\quad +\bbmu=\bbg^{-1}(\bbX\bbbeta+\bbZ\bbLambda_{\bbtheta}\bbu) , +$$ +providing the likelihood as +$$ +\begin{aligned} +L(\bbeta,\bbtheta|\bby)&= +\int_{\bbu}f_{\mcY,\mcU=\bbu}(\bby,\bbu)f_{\mcU}(\bbu)\,d\bbu\\ +&=\int_{\bbu}\frac{1}{\sqrt{2\pi}^q}e^{\sum_{i=1}^n(1-y_i)\log(1-\mu_i)+y_i\,\log(\mu_i)} +e^{-\left\|\bbu\right\|^2/2}\,d\bbu\\ +&=\int_{\bbu}\frac{1}{\sqrt{2\pi}^q}\exp\left(\frac{\left\|\bbu\right\|^2+\sum_{i=1}^n d(y_i,\mu_i)}{-2}\right)\,d\bbu +\end{aligned} +$$ {#eq-GLMMlikelihood} +where the *unit deviances*, $d(y_i,\mu_i)$, are +$$ +d(y_i,\mu_i)=-2\left[(1-y_i)\log(1-\mu_i)+y_i\log(\mu_i)\right]\quad i=1,\dots,n . +$$ {#eq-unitdeviances} + +By converting from the logarithm of the probability mass function to the [deviance](https://en.wikipedia.org/wiki/Deviance_(statistics)) scale, which is negative twice the log-probability, we get a quantity, $\sum_{i=1}^n d(y_i,\mu_i)$, which is on the same scale as the squared length, $\|\bbu\|^2$, of a standard multivariate Gaussian. +The sum of the unit deviances is analogous to the sum of squared residuals, $\|\bby-\bbX\bbbeta\|^2$, in a linear model. + +In @sec-lmmtheory we showed that the integral defining the likelihood for a linear mixed model, @eq-likelihood-integral, has an analytic solution. +In general, the integral in @eq-GLMMlikelihood does not. +We will approximate the value of this integral using a quadratic approximation to the argument of the exponential function in @eq-GLMMlikelihood at the value of $\bbu$ that maximizes the integrand, which is the density of the conditional distribution, $(\mcU|\mcY=\bby)$, up to a scale factor. +Because the scale factor does not affect the location of the maximum, the value of $\bbu$ that maximizes the integrand, +$$ +\begin{aligned} +\tilde{\bbu}(\bby|\bbtheta,\bbbeta) +&=\arg\max_{\bbu}\exp\left(\frac{\left\|\bbu\right\|^2 + \sum_{i=1}^n d(y_i,\mu_i)}{-2}\right)\\ +&=\arg\min_{\bbu}\left(\left\|\bbu\right\|^2 + \sum_{i=1}^n d(y_i,\mu_i)\right) +\end{aligned} , +$$ {#eq-condmode} +is also the *conditional mode* --- the value of $\bbu$ that maximizes the conditional density. +The expression being minimized in @eq-condmode, $\left\|\bbu\right\|^2 + \sum_{i=1}^n d(y_i,\mu_i)$, is called the *penalized deviance*. + +Using a quadratic approximation to the penalized deviance at this conditional mode (i.e. the mode of the conditional distribution of $\mcU$ given $\mcY=\bby$) is equivalent to using a multivariate Gaussian approximation to this conditional distribution. +Approximating an integral like @eq-GLMMlikelihood by approximating the integrand as a scaled multivariate Gaussian distribution at its mode is called [Laplace's approximation](https://en.wikipedia.org/wiki/Laplace%27s_approximation) (@TierneyKadane1986). + +The *penalized iteratively re-weighted least squares* (PIRLS) algorithm (@sec-PIRLS) provides a fast and stable method of determining the conditional mode, $\tilde{\bbu}(\bby|\bbtheta,\bbbeta)$ (@eq-condmode), thereby making it feasible to use Laplace's approximation at scale. + +Before discussing PIRLS, however, we will describe generalized linear models (GLMs) without random effects (@sec-BernoulliGLM), for which the *deviance* is defined as the sum of the unit deviances and the maximum likelihood estimate of the coefficient vector, $\widehat{\bbbeta}$, is the value that minimizes the deviance. +In @sec-IRLS we describe the *iteratively re-weighted least squares* (IRLS) algorithm, which is a stable, fast algorithm to minimize the deviance. + +We will illustrate the IRLS algorithm with the `contra` data discussed in @sec-glmmbinomial and a model like `com05`, which was fit in that chapter, but without the random effects. Later we will use the full `com05` model to illustrate some of the computations for GLMMs. + +Although 0/1 responses and the Bernoulli distribution are easy to describe, the theory of the generalized linear mixed model (GLMM) and the details of the implementation are not. Readers who wish to focus on practical applications more than on the theory should feel free to skim this appendix. + +Load the packages to be used + +```{julia} +#| code-fold: true +#| output: false +#| label: packagesA03 +using AlgebraOfGraphics +using BenchmarkTools +using CairoMakie +using EmbraceUncertainty: dataset +using FreqTables +using LinearAlgebra +using MixedModels +using MixedModelsMakie +using NLopt +using PooledArrays +using StatsAPI +``` + +and define some constants + +```{julia} +#| code-fold: true +#| output: false +#| label: constantsA03 +@isdefined(contrasts) || const contrasts = Dict{Symbol,Any}() +@isdefined(progress) || const progress = false +``` + +## Generalized linear models for binary data {#sec-BernoulliGLM} + +To introduce some terms and workflows we first consider the generalized linear model (GLM) for the Bernoulli distribution and the logit link. The linear predictor for a GLM - a model without random effects - is simply +$$ +{\bbeta}= {\bbX}{\bbbeta} , +$$ +and the mean response vector, ${\bbmu}=\bbg^{-1}(\bbeta)$, is obtained by component-wise application of the scalar logistic function (@eq-scalarlogistic). + +The probability mass function for the Bernoulli distribution is +$$ +f_{\mcY}(y|\mu) = \mu^y\,(1-\mu)^{(1-y)}\quad\mathrm{for}\quad y\in\{0,1\} . +$$ + +Because the elements of ${\mcY}|{\bbmu}$ are assumed to be independent, the log-likelihood is simply the sum of contributions from each element, which, on the deviance scale, can be written in terms of the *unit deviances* +$$ +\begin{aligned} +-2\,\ell({\bbmu}|{\mathbf{y}})&= -2\,\log(L({\bbmu}|{\mathbf{y}}))\\ +&=-2\,\sum_{i=1}^n y_i\log(\mu_i)+(1-y_i)\log(1-\mu_i) . +\end{aligned} +$$ {#eq-Bernoulliloglik} + +As described above, it is customary when working with GLMs to convert the log-likelihood to a [deviance](https://en.wikipedia.org/wiki/Deviance_(statistics)), which, for the Bernoulli distribution, is negative twice the log-likelihood. (For other distributions, the deviance may incorporate an additional term that depends only on ${\mathbf{y}}$.) + +One reason for preferring the deviance scale is that the change in deviance for nested models has approximately a $\chi^2$ distribution with degrees of freedom determined by the number of independent constraints on the parameters in the simpler model. +Especially for GLMs, the deviance plays a role similar to the sum of squared residuals in linear models. + +For greater numerical precision we avoid calculating $1-\mu$ directly when evaluating expressions like @eq-Bernoulliloglik and instead use +$$ +1 - \mu = 1 - \frac{1}{1+e^{-\eta}}=\frac{e^{-\eta}}{1+e^{-\eta}} . +$$ +Evaluation of the last expression provides greater precision for large negative values of $\eta$ (corresponding to small values of $\mu$) than does first evaluating $\mu$ followed by $1 - \mu$. + +After some algebra, we write the *unit deviance*, $d(y_i,\eta_i)$, which is the contribution to the deviance from the $i$th observation, as +$$ +\begin{aligned} +d(y_i, \eta_i)&=-2\left[y_i\log(\mu_i)+(1-y_i)\log(1-\mu_i)\right]\\ +&=2\left[(1-y_i)\eta_i-\log(1+e^{-\eta_i})\right] +\end{aligned} +\quad i=1,\dots,n +$$ + +A Julia function to evaluate both the mean and the unit deviance can be written as + +```{julia} +#| output: false +function meanunitdev(y::T, η::T) where {T<:AbstractFloat} + expmη = exp(-η) + return (; μ=inv(1 + expmη), dev=2 * ((1 - y) * η + log1p(expmη))) +end +``` + +::: {.callout-note collapse="true"} + +### log1p + +Mathematically `log1p`, read *log of 1 plus*, is defined as $\mathrm{log1p}(x)=\log(1+x)$ but it is implemented in such a way as to provide greater accuracy when $x$ is small. For example, + +```{julia} +let small = eps() / 10 + @show small + @show 1 + small + @show log(1 + small) + @show log1p(small) +end; +``` + +`1 + small` evaluates to `1.0` in floating point arithmetic because of round-off, producing 0 for the expression `log(1 + small)`, whereas `log1p(small) ≈ small`, as it should be. +::: + +This function returns a `NamedTuple` of values from scalar arguments. +For example, + +```{julia} +meanunitdev(0.0, 0.21) +``` + +A `Vector` of such `NamedTuple`s is a *row-table* (@sec-Tablesjl), which can be updated in place by [dot-vectorization](https://docs.julialang.org/en/v1/manual/functions/#man-vectorized) of the scalar `meanunitdev` function, as shown below. + +### An example: fixed-effects only from com05 + +We illustrate some of these computations using only the fixed-effects specification for `com05`, a GLMM fit to the `contra` data set in @sec-glmmbinomial. Because we will use the full GLMM later we reproduce `com05` by loading the data, creating the binary `ch` variable indicating children/no-children, defining the contrasts and formula to be used, and fitting the model as in @sec-glmmbinomial. + +```{julia} +#| code-fold: show +#| output: false +#| label: com05 +contra = let tbl = dataset(:contra) + Table(tbl; ch=tbl.livch .≠ "0") +end +contrasts[:urban] = HelmertCoding() +contrasts[:ch] = HelmertCoding() +com05 = + let d = contra, + ds = Bernoulli(), + f = @formula( + use ~ 1 + urban + ch * age + age & age + (1 | dist & urban) + ) + + fit(MixedModel, f, d, ds; contrasts, nAGQ=9, progress) + end +``` + +Extract the fixed-effects model matrix, $\bbX$, and initialize the coefficient vector, $\bbbeta$, to a copy (in case we modify it) of the estimated fixed-effects. + +```{julia} +βm05 = copy(com05.β) +``` + +As stated above, the `meanunitdev` function can be applied to the vectors, ${\mathbf{y}}$ and ${\bbeta}$, via dot-vectorization to produce a `Vector{NamedTuple}`, which is the typical form of a row-table. + +```{julia} +rowtbl = meanunitdev.(com05.y, com05.X * βm05) +typeof(rowtbl) +``` + +For display we convert the row-table to a column-table and prepend another column-table consisting of $\bby$ and $\bbeta$. + +```{julia} +Table((; y=com05.y, η=com05.X * βm05), rowtbl) # display as a Table +``` + +The deviance for this value of ${\bbbeta}$ in this model is the sum of the unit deviances, which we write as `sum` applied to a [generator expression](https://docs.julialang.org/en/v1/manual/arrays/#Generator-Expressions). (In general we extract columns of a row-table with generator expressions that produce [iterators](https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration).) + +```{julia} +sum(r.dev for r in rowtbl) +``` + +### Encapsulating the model in a struct + +When minimizing the deviance it is convenient to have the different components of the model encapsulated in a user-created `struct` type so we can update the parameter values and evaluate the deviance without needing to keep track of all the pieces of the model. + +```{julia} +struct BernoulliGLM{T<:AbstractFloat} + X::Matrix{T} + β::Vector{T} + ytbl::NamedTuple{(:y, :η),NTuple{2,Vector{T}}} + rtbl::Vector{NamedTuple{(:μ, :dev),NTuple{2,T}}} +end +``` + +We also create an *external constructor*, which is a function defined outside the struct and of the same name as the struct, that constructs and returns an object of that type. +In this case the external constructor creates a `BernoulliGLM` from the model matrix and the response vector, after some consistency checks on the arguments passed to it. + +```{julia} +#| output: false +function BernoulliGLM( + X::Matrix{T}, + y::Vector{T}, +) where {T<:AbstractFloat} + + # check consistency of arguments + n = size(X, 1) # number of rows in X + if length(y) ≠ n || any(!in([0, 1]), y) + throw(ArgumentError("y is not an $n-vector of 0's and 1's")) + end + + # initial β from linear regression of y in {-1,1} coding + β = X \ replace(y, 0 => -1) + η = X * β + + return BernoulliGLM(X, β, (; y, η), meanunitdev.(y, η)) +end +``` + +To optimize the deviance we define an *extractor* method that returns the deviance + +```{julia} +StatsAPI.deviance(m::BernoulliGLM) = sum(r.dev for r in m.rtbl) +``` + +::: {.callout-note collapse="true"} + +### Why StatsAPI.deviance and not just deviance? + +This extractor is written as a method for the generic `deviance` function defined in the `StatsAPI` package. +Doing so allows us to use the `deviance` name for the extractor without interfering with `deviance` methods defined for other model types. +::: + +We also define a mutating function, `setβ!`, that installs a new value of `β` then updates `η` and `rtbl` in place. + +```{julia} +#| output: false +function setβ!(m::BernoulliGLM, newβ) + (; y, η) = m.ytbl # destructure ytbl + mul!(η, m.X, copyto!(m.β, newβ)) # η = X * newβ in place + m.rtbl .= meanunitdev.(y, η) # update rtbl in place + return m +end +``` + +Create such a struct from `X` and `y` for model `com05`. + +```{julia} +com05fe = BernoulliGLM(com05.X, com05.y) +β₀ = copy(com05fe.β) # keep a copy of the initial values +``` + +These initial values of $\bbbeta$ are from a least squares fit of $\bby$, converted from `{0,1}` coding to `{-1,1}` coding, on the model matrix, $\bbX$. + +As a simple test of the `setβ!` and `deviance` methods we can check that `com05fe` produces the same deviance value for `βm05` as was evaluated above. + +```{julia} +deviance(setβ!(com05fe, βm05)) +``` + +For fairness in later comparisons we restore the initial values `β₀` to the model. +These are rough starting estimates with a deviance that is considerably greater than that at `βm05`. + +```{julia} +deviance(setβ!(com05fe, β₀)) +``` + +### Fit the GLM using a general optimizer + +We can use a general optimizer like those available in [NLopt.jl](https://github.com/JuliaOpt/NLopt.jl) to minimize the deviance. +Following the instructions given at that package's repository, we create an `Opt` object specifying the algorithm to be used, BOBYQA (@powell2009bobyqa), and the dimension of the problem, then define and assign the objective function in the required form, and call `optimize` + +```{julia} +function StatsAPI.fit!(m::BernoulliGLM{T}) where {T} + opt = Opt(:LN_BOBYQA, length(m.β)) + function objective(x::Vector{T}, g::Vector{T}) where {T} + isempty(g) || throw( + ArgumentError("Gradient not available, g must be empty"), + ) + return deviance(setβ!(m, x)) + end + opt.min_objective = objective + minf, minx, ret = optimize(opt, copy(m.β)) + @info (; code=ret, nevals=opt.numevals, minf) + return m +end +``` + +```{julia} +fit!(com05fe); +``` + +The optimizer has determined a coefficient vector that reduces the deviance to 2409.38, at which point convergence was declared because changes in the objective are limited by round-off. +This required about 500 evaluations of the deviance at candidate values of $\bbbeta$. + +Each evaluation of the deviance is fast, requiring only a fraction of a millisecond on a laptop computer, + +```{julia} +βopt = copy(com05fe.β) +@benchmark deviance(setβ!(m, β)) seconds = 1 setup = + (m = com05fe; β = βopt) +``` + +but the already large number of evaluations for these six coefficients would not scale well as this dimension increases. + +Fortunately there is an algorithm, called *iteratively reweighted least squares* (IRLS), that uses the special structure of the GLM to provide fast and stable convergence to estimates of the coefficients, even for models with a large number of coefficients. +This will be important to us in fitting GLMMs where we must optimize with respect to the random effects, whose dimension can be large. + +## The IRLS algorithm {#sec-IRLS} + +As we have seen, in a GLM we are modeling the responses and the predicted values on two scales --- the *linear predictor scale*, for $\bbeta$, and the *response scale*, for $\bby$ and $\bbmu$. +The scalar link function, $\eta=g(\mu)$, and the inverse link, $\mu=g^{-1}(\eta)$, map vectors component-wise between these two scales. + +For operations like determining a new candidate value of $\bbbeta$, the linear predictor scale is preferred, because, on that scale, $\bbeta=\bbX\bbbeta$ is a linear function of $\bbbeta$. +Thus it would be convenient if we could transform the response, ${\mathbf{y}}$, to the linear predictor scale where we could define a residual and use some form of minimizing a sum of squared residuals to evaluate a new coefficient vector (or, alternatively, evaluate an increment that will be added to the current coefficient vector). +Unfortunately, a naive approach of transforming $\bby$ to the linear predictor scale won't work because the elements of ${\mathbf{y}}$ are all $0$ or $1$ and the logit link function maps these values to $-\infty$ and $\infty$, respectively. + +For an iterative algorithm, however, we can use a local linear approximation to the link function to define a *working residual*, from which to evaluate an increment to the coefficient vector, or a *working response*, from which we evaluate the new coefficient vector directly. +Because the link and inverse link functions are defined component-wise we will define the approximation for scalars $y_i$, $\mu_i$, and $\eta_i$ and for the scalar link function, $g$, with the understanding that these definitions apply component-wise to the vectors. + +The *working residual* is evaluated by mapping the residual on the response scale, $y_i-\mu_i$, through the linear approximation to the link, $g(\mu)$, at $\mu_i$. +That is, +$$ +\tilde{r_i}=(y_i-\mu_i)g'(\mu_i)\quad i=1,\dots,n . +$$ +Because the derivative, $g'(\mu_i)$, for the logit link function is $1/[\mu_i(1-\mu_i)]$, these working residuals are +$$ +\tilde{r}_i = (y_i-\mu_i)g'(\mu_i) = \frac{y_i - \mu_i}{\mu_i(1-\mu_i)}\quad i=1,\dots,n . +$$ +Similarly, the *working response* on the linear predictor scale, is defined by adding the working residual to the current linear predictor value, +$$ +\tilde{y_i}=\eta_i + \tilde{r_i}=\eta_i +(y_i-\mu_i)g'(\mu_i)= +\eta_i + \frac{y_i - \mu_i}{\mu_i(1-\mu_i)}\quad i=1,\dots,n . +$$ + +On the linear predictor scale we can fit a linear model to the working response to obtain a new parameter vector, but we must take into account that the variances of the *noise terms* in this linear model, which are the working residuals, are not constant. +We use *weighted least squares* where the weights are inversely proportional to the variance of the working residual. +The variance of the random variable $\mcY_i$ is $\mu_i(1-\mu_i)$, hence the variance of the working residual is +$$ +\mathrm{Var}(\tilde{r_i})=g'(\mu_i)^2 \mathrm{Var}(\mcY_i)=\frac{\mu_i(1-\mu_i)}{\left[\mu_i(1-\mu_i)\right]^2}=\frac{1}{\mu_i(1-\mu_i)} +\quad i=1,\dots,n . +$$ + +Thus the working weights are +$$ +\begin{aligned} +w_i&=\mu_i(1-\mu_i)\\ +&=\frac{1}{1+e^{-\eta_i}}\frac{e^{-\eta_i}}{1+e^{-\eta_i}} +\end{aligned} +,\quad i=1,\dots,n. +$$ + +In practice we will use the square roots of the working weights, evaluated as +$$ +\sqrt{w_i}=\frac{\sqrt{e^{-\eta_i}}}{1+e^{-\eta_i}}=\frac{e^{-\eta_i/2}}{1+e^{-\eta_i}}\quad i=1,\dots,n . +$$ + +Note that $\mathrm{Var}(\mcY_i)$ happens to be the inverse of $g'(\mu_i)$ for a Bernoulli response and the logit link function. +This will always be true for distributions in the [exponential family](https://en.wikipedia.org/wiki/Exponential_family) and their canonial links. + +At the $k$th iteration the IRLS algorithm updates the coefficient vector to $\bbbeta^{(k)}$, which is a weighted least squares solution that could be written as +$$ +\bbbeta^{(k)}= \left(\bbX'\bbW\bbX\right)^{-1}\left(\bbX'\bbW\tilde{\bby}\right) , +$$ +where $\bbW$ is an $n\times n$ diagonal matrix of the working weights and $\tilde{\bby}$ is the working response, both evaluated at $\bbbeta^{(k-1)}$, the coefficient vector from the previous iteration. + +In practice we use the square roots of the working weights, which we write as a diagonal matrix, $\bbW^{1/2}$, and a QR decomposition (@sec-matrixdecomp) of a weighted model matrix, $\bbW^{1/2}\bbX$, to solve for the updated coefficient vector from the weighted working response, $\bbW^{1/2}\tilde{\bby}$, with elements +$$ +\begin{aligned} +\sqrt{w_i}(\eta_i+\tilde{r}_i)&=\sqrt{\mu_i(1-\mu_i)}(\eta_i+\tilde{r}_i)\\ +&=\sqrt{w_i}\eta_i +\frac{(y_i-\mu_i)\sqrt{\mu_i(1-\mu_i)}}{\mu_i(1-\mu_i)}\\ +&=\sqrt{w_i}\eta_i +\frac{y_i-\mu_i}{\sqrt{w_i}} +\end{aligned},\quad i=1,\dots,n +$$ + +It is possible to write the IRLS algorithm using a weighted least squares fit of the working residuals on the model matrix to determine a parameter increment. +However, in the PIRLS algorithm it is necessary to use the working response, not the working residual, so we define the IRLS algorithm in those terms too. + +Furthermore, in the PIRLS algorithm we will need to allow for an *offset* when calculating the working response. +In the presence of an offset, $\bbo$, a constant vector of length $n$, the linear predictor is defined as +$$ +\bbeta = \bbo + \bbX\bbbeta . +$$ +The mean, $\bbmu$, the working weights and the working residuals are defined as before but the working response becomes +$$ +\tilde{\bby}=\tilde{\bbr} + \bbeta - \bbo . +$$ + +For a linear model there is rarely a reason for using an offset. +Instead we can simply subtract the constant vector, $\bbo$, from the response, $\bby$, because the response and the linear predictor are on the same scale. +However, this is not the case for a GLM where we must deal with the effects of the constant offset on the linear predictor scale, not on the response scale. + +### Implementation of IRLS for Bernoulli-Logit + +We define a `BernoulliIRLS` struct with three additional elements in the rowtable: the square roots of the working weights, `rtwwt`, the weighted working residuals, `wwres`, and the weighted working response, `wwresp`. +In the discussion above, `rtwwt` is the diagonal of $\bbW^{1/2}$, `wwres` is $\bbW^{1/2}\tilde{\bbr}$ and `wwresp` is $\bbW^{1/2}\tilde{\bby}$. + +We also add fields `Xqr`, in which the weighted model matrix, $\bbW^{1/2}\bbX$, is formed followed by its QR decomposition, and `βcp`, which holds a copy of the previous coefficient vector. + +```{julia} +#| output: false +struct BernoulliIRLS{T<:AbstractFloat} + X::Matrix{T} + Xqr::Matrix{T} # copy of X used in the QR decomp + β::Vector{T} + βcp::Vector{T} # copy of previous β + Whalf::Diagonal{T,Vector{T}} # rtwwt as a Diagonal matrix + ytbl::NamedTuple{(:y, :η),NTuple{2,Vector{T}}} + rtbl::Vector{ + NamedTuple{(:μ, :dev, :rtwwt, :wwres, :wwresp),NTuple{5,T}}, + } +end +``` + +with constructor + +```{julia} +#| output: false +function BernoulliIRLS( + X::Matrix{T}, + y::Vector{T}, +) where {T<:AbstractFloat} + n = size(X, 1) # number of rows of X + if length(y) ≠ n || !all(v -> (iszero(v) || isone(v)), y) + throw(ArgumentError("y is not an $n-vector of 0's and 1's")) + end + # initial β from linear least squares fit of y in {-1,1} coding + Xqr = copy(X) + β = qr!(Xqr) \ replace(y, 0 => -1) + βcp = copy(β) + η = X * β + rtbl = tblrow.(y, η) + Whalf = Diagonal([r.rtwwt for r in rtbl]) + return BernoulliIRLS(X, Xqr, β, βcp, Whalf, (; y, η), rtbl) +end +``` + +The `tblrow` function evaluates the mean, unit deviance, square root of the weight, and the weighted, working residual and weighted, working response for scalar $y$ and $\eta$. +The `offset` argument, which defaults to zero, is not used in calls for `BernoulliIRLS` models, but will be used in @sec-PIRLS when we discuss the PIRLS algorithm. + +```{julia} +#| output: false +function tblrow( + y::T, + η::T, + offset::T=zero(T), +) where {T<:AbstractFloat} + rtexpmη = exp(-η / 2) # square root of exp(-η) + expmη = abs2(rtexpmη) # exp(-η) + denom = 1 + expmη + μ = inv(denom) + dev = 2 * ((1 - y) * η + log1p(expmη)) + rtwwt = rtexpmη / denom # sqrt of working wt + wwres = (y - μ) / rtwwt # weighted working resid + wwresp = wwres + rtwwt * (η - offset) + return (; μ, dev, rtwwt, wwres, wwresp) +end +``` + +```{julia} +#| output: false +StatsAPI.deviance(m::BernoulliIRLS) = sum(r.dev for r in m.rtbl) +``` + +Next we define a mutating function, `updateβ!`, that evaluates $\bbbeta^{(k)}$, the updated coefficient vector at iteration $k$, in place by weighted least squares then updates the response table. + +```{julia} +#| output: false +function updateβ!(m::BernoulliIRLS) + (; X, Xqr, β, βcp, Whalf, ytbl, rtbl) = m # destructure m & ytbl + (; y, η) = ytbl + copyto!(βcp, β) # keep a copy of β + copyto!(Whalf.diag, r.rtwwt for r in rtbl) # rtwwt -> Whalf + mul!(Xqr, Whalf, X) # weighted model matrix + copyto!(η, r.wwresp for r in rtbl) # use η as temp storage + ldiv!(β, qr!(Xqr), η) # weighted least squares + rtbl .= tblrow.(y, mul!(η, X, β)) # update η and rtbl + return m +end +``` + +For our example, we start at the same coefficient vector as we did with the general optimizer. + +```{julia} +com05fe = BernoulliIRLS(com05.X, com05.y) +deviance(com05fe) +``` + +The first IRLS iteration + +```{julia} +deviance(updateβ!(com05fe)) +``` + +reduces the deviance substantially. + +We create a `fit!` method to iterate to convergence. + +```{julia} +#| output: false +function StatsAPI.fit!(m::BernoulliIRLS, β₀=m.β; verbose::Bool=true) + (; X, β, βcp, ytbl, rtbl) = m + (; y, η) = ytbl + rtbl .= tblrow.(y, mul!(η, X, copyto!(β, β₀))) + olddev = deviance(m) + verbose && @info 0, olddev # record the deviance at initial β + for i in 1:100 # perform at most 100 iterations + newdev = deviance(updateβ!(m)) + verbose && @info i, newdev # iteration number and deviance + if newdev > olddev + @warn "failure to decrease deviance" + copyto!(β, βcp) # roll back changes to β, η, and rtbl + rtbl = tblrow.(y, mul!(η, X, β)) + break + elseif (olddev - newdev) < (1.0e-10 * olddev) + break # exit loop if deviance is stable + else + olddev = newdev + end + end + return m +end +``` + +```{julia} +fit!(com05fe, β₀); +``` + +The IRLS algorithm has converged in 4 iterations to essentially the same deviance as the general optimizer achieved after around 500 function evaluations. +Each iteration of the IRLS algorithm takes more time than a deviance evaluation, but still only a fraction of a millisecond on a laptop computer. + +```{julia} +@benchmark deviance(updateβ!(m)) seconds = 1 setup = (m = com05fe) +``` + +:::{.callout-note collapse="true"} + +### Alternative version of the IRLS algorithm + +The preceding text presented a fixed-point version of the IRLS algorithm. +There is another version of the IRLS algorithm which expresses the next iteration step for $\beta$ as a Newton-Raphson update with the following update equation: +$$ + \bbbeta^{(k)}\ =\ \bbbeta^{(k-1)} + \alpha \times \left(\bbX'\bbW\bbX\right)^{-1} \bbX'\bbW\tilde{\bbr} , +$$ +where $\alpha$ is a step size parameter. + +For $\alpha = 1$, it is easy to see that the Newton-Raphson step is equivalent to the fixed-point formulation +$$ + \bbbeta^{(k)} = \left(\bbX'\bbW\bbX\right)^{-1} \bbX'\bbW\tilde{\bby} +$$ +by using the identity $\bbbeta^{(k-1)} = \left(\bbX'\bbW\bbX\right)^{-1} \left(\bbX'\bbW\bbX\right) \bbbeta$ and combing the two terms on the right hand side. +For more details see [this RPubs tutorial](https://rpubs.com/enwuliu/1011024) by Enwu Liu. + +The Newton-Raphson formulation is used by [GLM.jl](https://juliastats.org/GLM.jl/stable/), but is less suitable for penalized IRLS (PIRLS), which we use below to extend this approach to generalized linear mixed models. + +::: + +## GLMMs and the PIRLS algorithm {#sec-PIRLS} + +In @sec-lmmtheory we showed that, given a value of $\bbtheta$, which determines the relative covariance factor, $\bbLambda_{\bbtheta}$, of the random effects, $\mcB$, the *conditional mode*, $\tilde{\bbb}$, of the random effects can be evaluated as the solution to a *penalized least squares* (PLS) problem. +It is convenient to write the PLS problem in terms of the *spherical random effects*, $\mcU\sim\mcN(\bbzero,\sigma^2\bbI)$, with the defining relationship $\mcB=\bbLambda_{\bbtheta}\mcU$, as in @eq-penalized-rss +$$ +\tilde{\bbu}=\arg\min_{\bbu}\left( +\left\|\bby-\bbX\bbbeta-\bbZ\bbLambda_{\bbtheta}\bbu\right\|^2 + +\left\|\bbu\right\|^2 +\right) . +$$ + +We wrote @eq-penalized-rss for the LMM case as minimizing the penalized sum of squared residuals with respect to both $\bbbeta$ and $\bbu$. +Here, and in @eq-condmodeu below, we minimize with respect to $\bbu$ only while holding $\bbbeta$ fixed. + +The solution of this PLS problem, $\tilde\bbu$, is the *conditional mode* of $\mcU$, in that it maximizes the density of the conditional distribution, $(\mcU|\mcY=\bby)$, at the observed $\bby$. +(In the case of a LMM, where the conditional distributions, $(\mcB|\mcY=\bby)$ and $(\mcU|\mcY=\bby)$, are multivariate Gaussian, the solution of the PLS problem is also the *mean* of the conditional distribution, but this property doesn't carry over to GLMMs.) + +In a Bernoulli generalized linear mixed model (GLMM) the mode of the conditional distribution, $(\mcU|\mcY=\bby)$, minimizes the *penalized GLM deviance*, +$$ +\tilde{\bbu}=\arg\min_{\bbu}\left( +\left\|\bbu\right\|^2+\sum_{i-1}^n d(y_i,\eta_i(\bbu)) +\right) , +$$ {#eq-condmodeu} +where $d(y_i,\eta_i),\,i=1,\dots,n$ are the unit deviances defined in @sec-BernoulliGLM. +We modify the IRLS algorithm as *penalized iteratively re-weighted least squares* (PIRLS) to determine these values. + +As with IRLS, each iteration of the PIRLS algorithm involves using the current linear predictor, $\bbeta(\bbu)=\bbX\bbbeta+\bbZ\bbLambda_{\bbtheta}\bbu$, ($\bbbeta$ and $\bbtheta$ are assumed known and fixed, and $\bbX\bbbeta$ is an offset) to evaluate the mean, $\bbmu=\bbg^{-1}(\bbeta)$, of the conditional distribution, $(\mcY|\mcU=\bbu)$, as well as the unit deviances, $d(y_i,\eta_i)$, the square roots of the working weights, which are on the diagonal of $\bbW^{1/2}$, and the weighted, working response, $\bbW^{1/2}\tilde{\bby}$. +The updated spherical random effects vector, $\bbu$, is the solution to +$$ +(\bbLambda'\bbZ'\bbW\bbZ\bbLambda+\bbI)\bbu=\bbLambda'\bbZ'\bbW\tilde{\bby} +$$ +and is evaluated using the Cholesky factor, $\bbL$, of $\bbLambda'\bbZ'\bbW\bbZ\bbLambda+\bbI$. + +As in the solution of the PLS problem in @sec-lmmtheory, the fact that $\bbZ$ is sparse and that the sparsity is also present in $\bbL$, makes it feasible to solve for $\bbu$ even when its dimension is large. + +### PIRLS for com05 + +To illustrate the calculations we again use the `com05` model, which has a single, scalar random-effects term, `(1 | dist & urban)`, in its formula. +The matrix $\bbZ$ is displayed as + +```{julia} +com05re = only(com05.reterms) +Int.(collect(com05re)) # Int values for compact printing +``` + +but internally it is stored much more compactly because it is an +*indicator matrix* (also called *one-hot* encoding), which means that all $Z_{i,j}\in\{0,1\}$ and in each row there is exactly one value that is one (and all the others are zero). +The column in which the non-zero element of each row occurs is given as an integer vector in the `refs` property of `com05re`. + +```{julia} +com05re.refs' # transpose for compact printing +``` + +We define a struct + +```{julia} +#| output: false +struct BernoulliPIRLS{T<:AbstractFloat,S<:Integer} + X::Matrix{T} + θβ::Vector{T} + ytbl::NamedTuple{ # column-table + (:refs, :y, :η, :offset), + Tuple{Vector{S},Vector{T},Vector{T},Vector{T}}, + } + utbl::NamedTuple{ # column-table + (:u, :u0, :Ldiag, :pdev, :pdev0, :aGHQ), + NTuple{6,Vector{T}}, + } + rtbl::Vector{ # row-table + NamedTuple{(:μ, :dev, :rtwwt, :wwres, :wwresp),NTuple{5,T}}, + } +end +``` + +with an external constructor + +```{julia} +#| output: false +function BernoulliPIRLS( + X::Matrix{T}, + y::Vector{T}, + refs::Vector{S}, +) where {T<:AbstractFloat,S<:Integer} + # use IRLS to check X and y, obtain initial β, and establish rtbl + irls = fit!(BernoulliIRLS(X, y); verbose=false) + β = irls.β + θβ = append!(ones(T, 1), β) # initial θ = 1 + η = X * β + + # refs should contain all values from 1 to maximum(refs) + refvals = sort!(unique(refs)) + q = length(refvals) + if refvals ≠ 1:q + throw(ArgumentError("sort!(unique(refs)) must be 1:$q")) + end + length(refs) == length(y) || + throw(ArgumentError("lengths of y and refs aren't equal")) + + ytbl = (; refs, y, η, offset=copy(η)) + + utbl = NamedTuple( + nm => zeros(T, q) for + nm in (:u, :u0, :Ldiag, :pdev, :pdev0, :aGHQ) + ) + return updatetbl!(BernoulliPIRLS(X, θβ, ytbl, utbl, irls.rtbl)) +end +``` + +::: {.callout-note collapse="true"} + +### Why are θ and β stored in a single vector? + +The reason for storing both $\bbtheta$ and $\bbbeta$ in a single vector is to provide for their simultaneous optimization with an optimizer such as those in [NLopt.jl](https://github.com/JuliaOpt/NLopt.jl). +::: + +The `utbl` field in a `BernoulliPIRLS` struct contains vectors named `u0`, `pdev`, `pdev0`, and `aGHQ`, in addition to `u` and `Ldiag`. +These are not used in the PIRLS algorithm (other than for keeping a copy of the previous $\bbu$) or for optimizing Laplace's approximation to the objective. +However, they will be used in adaptive Gauss-Hermite quadrature evaluation of the objective (@sec-aGHQ), so we keep them in the struct throughout. + +The `updatetbl!` method for this type first evaluates $\bbeta$ via a "virtual" multiplication that forms $\bbZ\bbLambda_{\bbtheta}\bbu$ plus the stored `offset`, which is $\bbX\bbbeta$, then updates the rowtable from $\bby$, $\bbeta$, and the offset. +For this model $\bbtheta$ is one-dimensional and $\bbLambda_{\bbtheta}$ is a scalar multiple of $\bbI_q$, the identity matrix of size $q$, and thus the matrix multiplication by $\bbLambda_{\bbtheta}$ can be expressed as scalar products. + +```{julia} +#| output: false +function updatetbl!(m::BernoulliPIRLS) + (; refs, y, η, offset) = m.ytbl + u = m.utbl.u + θ = first(m.θβ) + # evaluate η = offset + ZΛu where Λ is θ * I and Z is one-hot + fill!(η, 0) + @inbounds for i in eachindex(η, refs, offset) + η[i] += offset[i] + u[refs[i]] * θ + end + m.rtbl .= tblrow.(y, η, offset) + return m +end +``` + +The `pdeviance` method returns the deviance for the GLM model plus the penalty on the squared length of `u`. + +```{julia} +#| output: false +function pdeviance(m::BernoulliPIRLS) + return sum(r.dev for r in m.rtbl) + sum(abs2, m.utbl.u) +end +``` + +The `updateu!` method is similar to `updateβ!` for the `BernoulliIRLS` type except that it is based on the diagonal matrix $\bbLambda'\bbZ'\bbW\bbZ\bbLambda + \bbI$. +Only the diagonal elements of this matrix are constructed and used to solve for the updated $\bbu$ vector. +At convergence of the PIRLS algorithm the elements of `Ldiag` are replaced by their square roots. + +```{julia} +#| output: false +function updateu!(m::BernoulliPIRLS) + (; u, u0, Ldiag) = m.utbl + copyto!(u0, u) # keep a copy of u + θ = first(m.θβ) # extract the scalar θ + fill!(u, 0) + if iszero(θ) # skip the update if θ == 0 + fill!(Ldiag, 1) # L is the identity if θ == 0 + return updatetbl!(m) + end + fill!(Ldiag, 0) + @inbounds for (ri, ti) in zip(m.ytbl.refs, m.rtbl) + rtWΛ = θ * ti.rtwwt # non-zero in i'th row of √WZΛ + Ldiag[ri] += abs2(rtWΛ) # accumulate Λ'Z'WZΛ + u[ri] += rtWΛ * ti.wwresp # accumulate Λ'Z'Wỹ + end + Ldiag .+= 1 # form diagonal of Λ'Z'WZΛ + I = LL' + u ./= Ldiag # solve for u with diagonal LL' + return updatetbl!(m) # and update η and rtbl +end +``` + +Create a `BernoulliPIRLS` struct for the `com05` model and check the penalized deviance at the initial values + +```{julia} +m = BernoulliPIRLS(com05.X, com05.y, only(com05.reterms).refs) +pdeviance(m) +``` + +As with IRLS, the first iteration of PIRLS reduces the objective, which is the penalized deviance in this case, substantially. + +```{julia} +pdeviance(updateu!(m)) +``` + +Create a `pirls!` method for this struct. + +```{julia} +#| output: false +function pirls!(m::BernoulliPIRLS; verbose::Bool=false) + (; u, u0, Ldiag) = m.utbl + fill!(u, 0) # start from u == 0 + copyto!(u0, u) # keep a copy of u + oldpdev = pdeviance(updatetbl!(m)) + verbose && @info 0, oldpdev + for i in 1:10 # maximum of 10 PIRLS iterations + newpdev = pdeviance(updateu!(m)) + verbose && @info i, newpdev + if newpdev > oldpdev # PIRLS iteration failed + @warn "PIRLS iteration did not reduce penalized deviance" + copyto!(u, u0) # restore previous u + updatetbl!(m) # restore η and rtbl + break + elseif (oldpdev - newpdev) < (1.0e-8 * oldpdev) + copyto!(u0, u) # keep a copy of u + break + else + copyto!(u0, u) # keep a copy of u + oldpdev = newpdev + end + end + map!(sqrt, Ldiag, Ldiag) # replace diag(LL') by diag(L) + return m +end +``` + +The PIRLS iterations always start from $\bbu=\mathbf{0}$ so that the converged value of the penalized deviance is reproducible for given values of $\theta$ and $\bbbeta$. +If we allowed the algorithm to start at whatever values are currently stored in $\bbu$ then there could be slight differences in the value of the penalized deviance at convergence of PIRLS, which can cause problems when trying to optimize with respect to $\theta$ and $\bbbeta$. + +```{julia} +pirls!(m; verbose=true); +``` + +As with IRLS, PIRLS is a fast and stable algorithm for determining the mode of the conditional distribution $(\mcU|\mcY=\bby)$ with $\bbtheta$ and $\bbbeta$ held fixed. + +```{julia} +@benchmark pirls!(mm) seconds = 1 setup = (mm = m) +``` + +The time taken for the four iterations to determine the conditional mode of $\bbu$ is comparable to the time taken for a single call to `updateβ!`. +Most of the time in `updateβ!` is spent in the QR factorization to solve the weighted least squares problem, whereas in `updateu!`and thus in `pirls!`, we take advantage of the fact that the solution of the penalized, weighted least squares problem is based on a diagonal matrix. + +## Laplace's approximation to the log-likelihood {#sec-GLMMLaplace} + +The PIRLS algorithm determines the value of $\bbu$ that minimizes the penalized deviance +$$ +\tilde{\bbu}=\arg\min_{\bbu}\left(\left\|\bbu\right\|^2+\sum_{i=1}^n d(y_i,\eta_i)\right) , +$$ +where $\eta_i, i=1,\dots,n$ is the $i$th component of $\bbeta=\bbX\bbbeta+\bbZ\bbLambda\bbu$. +A quadratic approximation to the penalized deviance at $\tilde{\bbu}$ is +$$ +\begin{aligned} +\tilde{d}(\bby,\bbu)&=\|\bbu\|^2+\sum_{i=1}^n d(y_i,\eta_i)\\ +&\approx\|\tilde{\bbu}\|^2+\sum_{i=1}^n d(y_i,\tilde{\eta}_i)+ +(\bbu-\tilde{\bbu})'(\bbLambda'\bbZ'\bbW\bbZ\bbLambda+\bbI)(\bbu-\tilde{\bbu})\\ +&=\|\tilde{\bbu}\|^2+\sum_{i=1}^n d(y_i,\tilde{\eta}_i)+ +(\bbu-\tilde{\bbu})'\bbL\bbL'(\bbu-\tilde{\bbu})\\ +&=\tilde{d}(\bby,\tilde{\bbu})+ +(\bbu-\tilde{\bbu})'\bbL\bbL'(\bbu-\tilde{\bbu}) +\end{aligned} +$$ {#eq-pdevquad} +where $\bbL$ is the lower Cholesky factor of $\bbLambda'\bbZ'\bbW\bbZ\bbLambda+\bbI$. +(In @eq-pdevquad the linear term in $(\bbu-\tilde{\bbu})$ that would normally occur in such an expression is omitted because the gradient of $\tilde{d}(\bby,\bbu)$ is zero at $\tilde{\bbu}$.) + +[Laplace's approximation](https://en.wikipedia.org/wiki/Laplace%27s_approximation) to the log-likelihood uses this quadratic approximation to the penalized deviance, which is negative one-half the logarithm of the integrand, to approximate the value of the integral. + +On the deviance scale, which is negative twice the log-likelihood, the approximation is +$$ +\begin{aligned} +-2\,\ell(\bbu|\bby,\bbtheta,\bbbeta)&=-2\,\log\left(L(\bbu|\bby,\bbtheta,\bbbeta)\right)\\ +&=-2\,\log\left(\int_{\bbu}\frac{1}{\sqrt{2\pi}^q}\exp\left(\frac{\left\|\bbu\right\|^2+\sum_{i=1}^n d(y_i,\mu_i)}{-2}\right)\,d\bbu\right)\\ +&\approx\tilde{d}(\bby,\tilde{\bbu})-2\,\log\left( +\int_\bbu\frac{1}{\sqrt{2\pi}^q}\exp\left(\frac{[\bbu-\tilde{\bbu}]'\bbL\bbL'[\bbu-\tilde{\bbu}]}{-2}\right)\,d\bbu +\right)\\ +&=\tilde{d}(\bby,\tilde{\bbu})-2\,\log\left( +\int_\bbu\frac{1}{\sqrt{2\pi}^q}\exp\left(\frac{\left\|\bbL'[\bbu-\tilde{\bbu}\right\|^2}{-2}\right)\,d\bbu +\right)\\ +&=\tilde{d}(\bby,\tilde{\bbu})-2\,\log\left(|\bbL|^{-1}\right)\\ +&=\tilde{d}(\bby,\tilde{\bbu})+\log\left(|\bbL|^2\right) +\end{aligned} +$$ + +```{julia} +#| output: false +function laplaceapprox(m::BernoulliPIRLS) + return pdeviance(m) + 2 * sum(log, m.utbl.Ldiag) +end +``` + +```{julia} +laplaceapprox(pirls!(m)) +``` + +The remaining step is to optimize Laplace's approximation to the GLMM deviance with respect to $\theta$ and $\bbbeta$, which we do using the BOBYQA optimizer from [NLopt.jl](https://github.com/JuliaOpt/NLopt.jl) + +```{julia} +#| output: false +function StatsAPI.fit!(m::BernoulliPIRLS) + θβ = m.θβ + pp1 = length(θβ) # length(β) = p and length(θ) = 1 + opt = Opt(:LN_BOBYQA, pp1) + mβ = view(θβ, 2:pp1) + function obj(x, g) + if !isempty(g) + throw(ArgumentError("gradient not provided, g must be empty")) + end + copyto!(θβ, x) + mul!(m.ytbl.offset, m.X, mβ) + return laplaceapprox(pirls!(m)) + end + opt.min_objective = obj + lb = fill!(similar(θβ), -Inf) # vector of lower bounds + lb[1] = 0 # scalar θ must be non-negative + NLopt.lower_bounds!(opt, lb) + minf, minx, ret = optimize(opt, copy(θβ)) + @info (; ret, fevals=opt.numevals, minf) + return m +end +``` + +```{julia} +fit!(m); +``` + +```{julia} +#| code-fold: true +print( + "Converged to θ = ", + first(m.θβ), + " and β =", + view(m.θβ, 2:lastindex(m.θβ)), +) +``` + +These estimates differ somewhat from those for model `com05`. + +```{julia} +#| code-fold: true +print( + "Estimates for com05: θ = ", + only(com05.θ), + ", fmin = ", + deviance(com05), + ", and β =", + com05.β, +) +``` + +The discrepancy in the results is because the `com05` results are based on a more accurate approximation to the integral called *adaptive Gauss-Hermite Quadrature*, which is discussed in @sec-aGHQ. + +### Generalizations to more complex structure + +There is an implicit assumption in the `BernoulliPIRLS` structure that random effects in the model are simple, scalar random effects associated with a single grouping factor, which is represented by `m.ytbl.refs`. +For such models the random effects model matrix, $\bbZ$, is an $n\times q$ indicator matrix, the covariance parameter, $\bbtheta$, is one-dimensional and the covariance factor, $\bbLambda_{\bbtheta}=\theta\,\bbI_q$ is a scalar multiple of the $q\times q$ identity matrix, $\bbI_q$. +Furthermore, $\bbLambda_{\bbtheta}'\bbZ'\bbW\bbZ\bbLambda_{\bbtheta}+\bbI_q$ is also diagonal, as is its Cholesky factor, $\bbL$. + +We have taken advantage of the special structure of these matrices both in representations --- storing $\bbL$ by storing only the diagonal values in the vector `m.utbl.Ldiag` --- and in some algorithms for the PIRLS iterative step. + +The PIRLS algorithm to determine the conditional mode, $\tilde{\bbu}$, of the random effects, $\mcU$, and Laplace's approximation to the log-likelihood for GLMMs can be generalized to models with vector-valued random effects, or with random effects associated with more than one grouping factor, or with both. +The more general representation of $\bbZ$ and $\bbL$ used with linear mixed models can be adapted for GLMMs as well. + +We chose to specialize the representation of GLMMs in this appendix to this specific type of random effects to be able to demonstrate adaptive Gauss-Hermite quadrature in @sec-aGHQ, which, at present, is restricted to models with a single, simple, scalar, random effects term. + +## Adaptive Gauss-Hermite quadrature {#sec-aGHQ} + +Recall from @eq-pdevquad that Laplace's approximation to the likelihood is based on a quadratic approximation to the penalized (GLM) deviance, $\tilde{d}(\bby,\bbu)$, at the conditional mode $\tilde{\bbu}$. +In the case of a model with a single, scalar, random effects term, like the model `com05`, each linear predictor value, $\eta_i,\,i=1,\dots,n$ depends on only one element of $\bbu$. +Writing the set of indices $i$ for which `refs[i] == j` as $\mcI(j)$, we can express the penalized deviance, and its quadratic approximation, as sums of scalar contributions, +$$ +\begin{aligned} +\tilde{d}(\bby,\bbu)&=\|\bbu\|^2+\sum_{i=1}^n d(y_i,\mu_i)\\ +&=\sum_{j=1}^q\left(u_j^2+\sum_{i\in\mcI(j)}d(y_i,\mu_i)\right)\\ +&\approx\sum_{j=1}^q \left(\tilde{u}_j^2+\sum_{i\in\mcI(j)}\left(d(y_i,\tilde{\mu}_i)+\ell_j^2(u_j-\tilde{u}_j)^2\right)\right) +\end{aligned} +$$ +where $\ell_j$ is the $j$th diagonal element of $\bbL$ and $\tilde{\mu}_i$ is the value of $\mu_i$ when $u_j=\tilde{u}_j$. + +Extending the notation of @eq-pdevquad we write the contribution from $u_j$ to the penalized (GLM) deviance, and to its quadratic approximation, as +$$ +\begin{aligned} +\tilde{d}_j(u_j)&= u_j+\sum_{i\in\mcI(j)}d(y_i,\mu_i)\\ +&\approx \tilde{u_j} + \sum_{i\in\mcI(j)}\left(d(y_i,\tilde{\mu}_i)+\ell_j^2(u_j-\tilde{u}_j)\right)\\ +&=\tilde{d}_j(\tilde{u}_j)+\ell_j^2(u_j-\tilde{u}_j)\quad j=1,\dots,q , +\end{aligned} +$$ +giving Laplace's approximation to the scalar integral defining the contribution of $u_j$ to negative twice the log-likelihood as +$$ +\begin{aligned} +-2\log\int_{u_j}\frac{e^{-\tilde{d}_j(u_j)/2}}{\sqrt{2\pi}}\,du_j&\approx +-2\log\int_{u_j}\frac{e^{\left((-\tilde{d}_j(\tilde{u_j})-\ell_j^2(u_j-\tilde{u}_j)^2)/2\right)}}{\sqrt{2\pi}}\,du_j\\ +&=\tilde{d}_j(\tilde{u}_j)-2\log\int_{u_j}\frac{e^{-\ell_j^2(u_j-\tilde{u}_j)^2/2}}{\sqrt{2\pi}}\,du_j\\ +&=\tilde{d}_j(\tilde{u}_j)-2\log\int_{z_j}\frac{e^{-z_j^2/2}}{\sqrt{2\pi}}\,\frac{dz_j}{\ell_j}\\ +&=\tilde{d}_j(\tilde{u}_j)+2\log(\ell_j)-2\log\int_{z_j}\frac{e^{-z_j^2/2}}{\sqrt{2\pi}}\,dz_j\\ +&=\tilde{d}_j(\tilde{u}_j)+2\log(\ell_j)-2\log(1)\\ +&=\tilde{d}_j(\tilde{u}_j)+2\log(\ell_j) +\end{aligned} +$$ {#eq-scalarlaplace} +using the change of variable +$$ +z_j=\ell_j(u_j-\tilde{u}_j)\quad j=1,\dots,q +$$ {#eq-ujtozj} +with inverse +$$ +u_j=\frac{z_j}{\ell_j}+\tilde{u}_j\quad j=1,\dots,q +$$ {#eq-zjtouj} +and derivative +$$ +\frac{du_j}{dz_j}=\frac{1}{\ell_j} . +$$ + +The change of variable @eq-ujtozj allows us to express the contribution from $u_j$ to Laplace's approximation as a constant, $\tilde{d}_j(\tilde{u}_j)$, plus the integral of a multiple, $1/\ell_j$, of the density of a standard normal distribution +$$ +\phi(z)=\frac{e^{-z^2/2}}{\sqrt{2\pi}} . +$$ + +The $K$th-order normalized Gauss-Hermite quadrature rule allows us to extend this approach to evaluate integrals of the form +$$ +\int_z f(z)\frac{e^{-z^2/2}}{\sqrt{2\pi}}\, dz \approx \sum_{k=1}^K w_k f(z_k) +$$ {#eq-normalizedGaussHermite} +where the weights, $w_k,\,k=1,\dots,K$, and the absiccae, $z_k,\,k=1,\dots,K$ are evaluated as described in @sec-NGHQ. +The approximation @eq-normalizedGaussHermite is exact when $f(z)$ is a polynomial of order $2K-1$ or less. + +We will apply a rule like @eq-normalizedGaussHermite where $f$ is the exponential of negative half the difference between the penalized deviance, $\tilde{d}_j(z_j/\ell_j+\tilde{u}_j)$, and its quadratic approximation at the conditional mode, $\tilde{u}_j$. +That is, we will center the standard normal density at the conditional mode, $\tilde{u}_j,\,j=1,\dots,q$, and scale it by the inverse of the quadratic term, $\ell_j,\,j=1,\dots,q$, in the quadratic approximation at that value of $u$. +This is said to be an *adaptive* quadrature rule because we are shifting and scaling the evaluation points according to the current conditions in the iterative algorithm. + +In other words we will first apply PIRLS to determine the conditional modes and the quadratic terms, then use a normalized Gauss-Hermite quadrature rule. + +### Normalized Gauss-Hermite quadrature rules {#sec-NGHQ} + +[*Gaussian Quadrature rules*](https://en.wikipedia.org/wiki/Gaussian_quadrature) provide sets of `x` values, called *abscissae*, and corresponding weights, `w`, to approximate an integral with respect to a *weight function*, $g(x)$. +For a $K$th order rule the approximation is +$$ +\int f(x)g(x)\,dx \approx \sum_{k=1}^K w_k f(x_k) +$$ + +For the [Gauss-Hermite](https://en.wikipedia.org/wiki/Gauss%E2%80%93Hermite_quadrature) rule the weight function is +$$ +g(x) = e^{-x^2} +$$ +and the domain of integration is $(-\infty, \infty)$. A slight variation of this is the *normalized Gauss-Hermite* rule for which the weight function is the standard normal density +$$ +g(z) = \phi(z) = \frac{e^{-z^2/2}}{\sqrt{2\pi}} . +$$ + +Thus, the expected value of $f(z)$, where $\mathcal{Z}\sim\mathscr{N}(0,1)$, is approximated as +$$ +\mathbb{E}[f]=\int_{-\infty}^{\infty} f(z) \phi(z)\,dz\approx\sum_{k=1}^K w_k\,f(z_k) . +$$ + +Naturally, there is a caveat. +For the approximation to be accurate the function $f(z)$ must behave like a low-order polynomial over the range of interest. +More formally, a $K$th order rule is exact when $f$ is a polynomial of order $2K-1$ or less. + +#### Evaluating the weights and abscissae + +In the [*Golub-Welsch algorithm*](https://en.wikipedia.org/wiki/Gaussian_quadrature#The_Golub-Welsch_algorithm) the abscissae for a particular Gaussian quadrature rule are determined as the eigenvalues of a symmetric tri-diagonal matrix and the weights are derived from the squares of the first row of the matrix of eigenvectors. +For a $K$th order normalized Gauss-Hermite rule the tridiagonal matrix has zeros on the diagonal and the square roots of `1:k-1` on the super- and sub-diagonal, e.g. + +```{julia} +sym5 = SymTridiagonal(zeros(5), sqrt.(1:4)) +``` + +```{julia} +ev = eigen(sym5); +ev.values +``` + +```{julia} +abs2.(ev.vectors[1, :]) +``` + +A function of `k` to evaluate the abscissae and weights is + +```{julia} +#| output: false +function gausshermitenorm(k) + ev = eigen(SymTridiagonal(zeros(k), sqrt.(1:(k - 1)))) + return Table((; + abscissae=ev.values, + weights=abs2.(ev.vectors[1, :]), + )) +end +``` + +providing + +```{julia} +gausshermitenorm(5) +``` + +The weights and positions for the 9th order rule are shown in @fig-ghnine. + +```{julia} +#| code-fold: true +#| fig-cap: Weights and positions for the 9th order normalized Gauss-Hermite quadrature rule +#| label: fig-ghnine +#| warning: false +draw( + data(gausshermitenorm(9)) * + mapping(:abscissae => "Positions", :weights); + figure=(; size=(600, 450)), +) +``` + +Notice that the magnitudes of the weights drop quite dramatically away from zero, even on a logarithmic scale (@fig-ghninelog) + +```{julia} +#| code-fold: true +#| fig-cap: Weights (logarithm base 2) and positions for the 9th order normalized Gauss-Hermite quadrature rule +#| label: fig-ghninelog +#| warning: false +draw( + data(gausshermitenorm(9)) * mapping( + :abscissae => "Positions", + :weights => log2 => "log₂(weight)", + ); + figure=(; size=(600, 450)), +) +``` + +The definition of `MixedModels.GHnorm` is similar to the `gausshermitenorm` function with some extra provisions for ensuring symmetry of the abscissae and of the weights and for caching values once they have been calculated. + +```{julia} +let tbl = GHnorm(9) + Table(abscissae=tbl.z, weights=tbl.w) +end +``` + +In particular, when $K$ is odd the middle abscissa, at index $(K+1)/2$, is exactly zero. + +As an example of evaluation using these weights and abscissae, we consider +$$ +\mathbb{E}[g(x)] \approx \sum_{i=1}^k g(\mu + \sigma z_i)\,w_i +$$ +where $\mathcal{X}\sim\mathscr{N}(\mu, \sigma^2)$. + +For example, $\mathbb{E}[\mathcal{X}^2]$ where $\mathcal{X}\sim\mathcal{N}(2, 3^2)$ is + +```{julia} +let μ = 2, σ = 3, ghn3 = GHnorm(3) + sum(@. ghn3.w * abs2(μ + σ * ghn3.z)) # should be μ² + σ² = 13 +end +``` + +(In general a dot, '`.`', after the function name in a function call, as in `abs2.(...)`, or before an operator creates a [*fused vectorized*](https://docs.julialang.org/en/v1/manual/performance-tips/#More-dots:-Fuse-vectorized-operations) +evaluation in Julia. The macro `@.` has the effect of vectorizing all operations in the subsequent expression.) + +### Illustration of contributions to the objective + +We have provided a `pdev` vector in the `utbl` field of a `BernoulliPIRLS` object to allow for accumulation of the penalized deviance contributions for each component of $\bbu$ in the model. + +```{julia} +#| output: false +function pdevcomps!(m::BernoulliPIRLS) + (; u, pdev) = m.utbl + pdev .= abs2.(u) # initialize pdevj to square of uj + @inbounds for (ri, ti) in zip(m.ytbl.refs, m.rtbl) + pdev[ri] += ti.dev + end + return m +end +``` + +After PIRLS has converged, we evaluate `pdevcomps!` and copy the `pdev` column of the `utbl` field to its `pdev0` column, which will be the baseline evaluation of the penalized deviance at the conditional modes. +Other evaluations of the penalized deviance components are plotted as differences from `pdev0`. + +```{julia} +pdevcomps!(pirls!(m)) +copyto!(m.utbl.pdev0, m.utbl.pdev) +Table(m.utbl) +``` + +Consider the change in the penalized deviance from that at the conditional mode for a selection of groups, which, by default, we choose to be the first 5 groups. + +```{julia} +#| output: false +#| code-fold: show +function pdevdiff( + m::BernoulliPIRLS{T}; + zvals=collect(-3.5:inv(32):3.5), + inds=1:5, +) where {T} + (; u, u0, Ldiag, pdev, pdev0) = m.utbl + pdevcomps!(pirls!(m)) # assign u0 + copyto!(pdev0, pdev) # and pdev0 + ni = length(inds) + nz = length(zvals) + uvals = Array{T}(undef, ni, nz) + exact = Array{T}(undef, ni, nz) + for (j, z) in enumerate(zvals) + u .= u0 .+ z ./ Ldiag # evaluate u from z + pdevcomps!(updatetbl!(m)) # evaluate pdev + for (i, ind) in enumerate(inds) # store selected u and pdev + uvals[i, j] = u[ind] + exact[i, j] = pdev[ind] - pdev0[ind] + end + end + uvals = collect(uvals') # transpose uvals + exact = collect(exact') # and exact + return (; zvals, inds, uvals, exact) +end +m05pdevdiff = pdevdiff(m); +``` + +We begin with plots of the difference in the penalized deviance from its value at the conditional mode, $\tilde{d}_j(u_j)-\tilde{d_j}(\tilde{u}_j)$, for $j=1,\dots,5$ in @fig-uscalepdev + +```{julia} +#| code-fold: true +#| fig-cap: Change in the penalized deviance contribution from that at the conditional mode, for each of the first 5 groups, in model com05, as a function of u. +#| label: fig-uscalepdev +#| warning: false +let (; zvals, inds, uvals, exact) = m05pdevdiff, + fig = Figure(; size=(600, 375)), + ax = Axis( + fig[1, 1]; + xlabel="u", + ylabel="Change in penalized deviance", + ) + + lins = [ + lines!(ax, view(uvals, :, j), view(exact, :, j)) for + j in axes(uvals, 2) + ] + Legend(fig[1, 2], lins, string.(inds)) + fig +end +``` + +then shift and scale the horizontal axis to the $z$ scale for this difference in the penalized deviance (from that at the conditional mode) in @fig-zscalepdev. + +```{julia} +#| code-fold: true +#| fig-cap: Change in the penalized deviance contribution from that at the conditional mode, for each of the first 5 groups, in model com05, as a function of z. +#| label: fig-zscalepdev +#| warning: false +let (; zvals, inds, uvals, exact) = m05pdevdiff, + fig = Figure(; size=(600, 375)), + ax = Axis( + fig[1, 1]; + xlabel="z", + ylabel="Change in penalized deviance", + ) + + lins = + [lines!(ax, zvals, view(exact, :, j)) for j in axes(uvals, 2)] + Legend(fig[1, 2], lins, string.(inds)) + fig +end +``` + +The next stage is to plot, on the $z$ scale, the difference between the penalized deviance and its quadratic approximation at $z=0$ in @fig-zpdevdiff + +```{julia} +#| code-fold: true +#| fig-cap: The difference between the contribution to the penalized deviance and its quadratic approximation for each of first 5 groups in model com05 as a function of z. +#| label: fig-zpdevdiff +#| warning: false +let (; zvals, inds, uvals, exact) = m05pdevdiff, + fig = Figure(; size=(600, 375)), + ax = Axis( + fig[1, 1]; + xlabel="z", + ylabel="Penalized deviance minus quadratic approx", + ) + + lins = [ + lines!(ax, zvals, view(exact, :, j) .- abs2.(zvals)) for + j in axes(uvals, 2) + ] + Legend(fig[1, 2], lins, string.(inds)) + fig +end +``` + +and, finally, the exponential of negative half of this difference in @fig-zexpneghalfdiff + +```{julia} +#| code-fold: true +#| fig-cap: Exponential of half the difference between the quadratic approximation and the contribution to the penalized deviance, for each of first 5 groups in model com05 as a function of z. +#| label: fig-zexpneghalfdiff +#| warning: false +let (; zvals, inds, uvals, exact) = m05pdevdiff, + fig = Figure(; size=(600, 375)), + ax = Axis( + fig[1, 1]; + xlabel="z", + ylabel="Exp of half the quadratic minus penalized deviance", + ) + + lins = [ + lines!( + ax, + zvals, + exp.(0.5 .* (abs2.(zvals) .- view(exact, :, j))), + ) for j in axes(uvals, 2) + ] + Legend(fig[1, 2], lins, string.(inds)) + fig +end +``` + +Writing the function shown in @fig-zexpneghalfdiff --- the exponential of negative half the difference between the penalized deviance and its quadratic approximation --- as +$$ +f_j(z_j)=\exp{\left(\frac{\tilde{d}_j(z_j/\ell_j+\tilde{u}_j)-\tilde{d}_j(\tilde{u}_j)-z_j^2}{-2}\right)} +\quad j=1,\dots,q +$$ +we can modify the scalar version of Laplace's approximation, @eq-scalarlaplace, as +$$ +\begin{multline*} +-2\log\int_{u_j}\frac{e^{-\tilde{d}_j(u_j)/2}}{\sqrt{2\pi}}\,du_j\\ +=-2\log\int_{z_j}\frac{f_j(z_j)\,e^{-(\tilde{d}_j(\tilde{u}_j)+z_j^2)/2}}{\sqrt{2\pi}}\,\frac{dz_j}{\ell_j}\\ +=\tilde{d}_j(\tilde{u}_j)+2\log(\ell_j)-2\log\int_{z_j}f_j(z_j)\frac{e^{-z_j^2/2}}{\sqrt{2\pi}}\,dz_j +\end{multline*} +$$ {#eq-scalaraGHQ} + +A $K$th-order adaptive Gauss-Hermite quadrature approximation to the objective, negative twice the log-likelihood, for the GLMM model is Laplace's approximation minus twice the logarithm of the $K$th order normalized Gauss-Hermite quadrature rule applied to $f_j(z_j)$. +We use the `aGHQ` column of `m.utbl` to accumulate these contributions and to take the logarithm then multiply the result by -2. + +```{julia} +#| output: false +#| code-fold: show +function evalGHQ!(m::BernoulliPIRLS; nGHQ::Integer=9) + (; ytbl, utbl, rtbl) = m + (; u, u0, Ldiag, pdev, pdev0, aGHQ) = utbl + ghqtbl = GHnorm(nGHQ) + pdevcomps!(pirls!(m)) # ensure that u0 and pdev0 are current + copyto!(pdev0, pdev) + fill!(aGHQ, 0) + for (z, w) in zip(ghqtbl.z, ghqtbl.w) + if iszero(z) # exp term is one when z == 0 + aGHQ .+= w + else + u .= u0 .+ z ./ Ldiag + pdevcomps!(updatetbl!(m)) + aGHQ .+= w .* exp.((abs2(z) .+ pdev0 .- pdev) ./ 2) + end + end + map!(log, aGHQ, aGHQ) # log.(aGHQ) in place + aGHQ .*= -2 + return m +end +``` + +```{julia} +evalGHQ!(m) +Table(m.utbl) +``` + +```{julia} +extrema(m.utbl.aGHQ) +``` + +As we see, these "correction terms" relative to Laplace's approximation are relatively small, compared to the contributions to the objective from each component of $\bbu$. +Also, the corrections are all negative, in this case. +Close examination of the individual curves in @fig-zpdevdiff shows that these curves, which are $-2\log(f_j(z))$, are more-or-less [odd functions](https://en.wikipedia.org/wiki/Even_and_odd_functions), in the sense that the value at $-z$ is approximately the negative of the value at $z$. +If we were integrating $\log(f_j(z_j))\phi(z_j)$ with a normalized Gauss-Hermite rule the negative and positive values would cancel out, for the most part, and some of the integrals would be positive while others would be negative. + +When we consider $f_j(z_j)$, shown in @fig-zexpneghalfdiff, the exponential function converts from differences to ratios and stretches positive differences more than negative differences, resulting in values slightly greater than 1 for $\int_z f_j(z)\phi(z) dz$ and, after taking negative twice the logarithm, correction terms that are slightly less than zero. + +## Optimization of the aGHQ objective + +```{julia} +#| output: false +function fitGHQ!(m::BernoulliPIRLS; nGHQ::Integer=9) + (; Ldiag, pdev0, aGHQ) = m.utbl + θβ = m.θβ + pp1 = length(θβ) # length(β) = p and length(θ) = 1 + opt = Opt(:LN_BOBYQA, pp1) + mβ = view(θβ, 2:pp1) + function obj(x, g) + if !isempty(g) + throw(ArgumentError("gradient not provided, g must be empty")) + end + copyto!(θβ, x) + mul!(m.ytbl.offset, m.X, mβ) + evalGHQ!(m; nGHQ) + return sum(pdev0) + sum(aGHQ) + 2 * sum(log, Ldiag) + end + opt.min_objective = obj + lb = fill!(similar(θβ), -Inf) # vector of lower bounds + lb[1] = 0 # scalar θ must be non-negative + NLopt.lower_bounds!(opt, lb) + minf, minx, ret = optimize(opt, copy(θβ)) + @info (; ret, fevals=opt.numevals, minf) + return m +end +``` + +```{julia} +#| warning: false +fitGHQ!(m) +m.θβ +``` + +*This page was rendered from git revision {{< git-rev short=true >}} using Quarto {{< version >}}.* diff --git a/markup/math/bareboat_math_17fcb0.adoc b/markup/math/bareboat_math_17fcb0.adoc new file mode 100644 index 0000000..fcee44a --- /dev/null +++ b/markup/math/bareboat_math_17fcb0.adoc @@ -0,0 +1,733 @@ += Marine IMU Wave-State Estimation with OU-Driven Quaternion MEKF +mgrouch +{docdate}, Marine IMU Wave-State Estimation +:imagesdir: images +:doctype: book +:organization: Bareboat Necessities +:description: Bareboat Necessities, Marine IMU wave-state estimation from low-cost IMU data +:title-logo-image: image:bareboat-necessities-logo.svg[Bareboat Necessities Logo] +ifdef::backend-pdf[] +:source-highlighter: rouge +:toc-placement!: manual +:pdf-page-size: Letter +:plantumlconfig: plantuml.cfg +endif::[] +ifndef::backend-pdf[] +:toc-placement: manual +endif::[] +:stem: +:experimental: +:reproducible: +:toclevels: 4 +:sectnums: +:sectnumlevels: 3 +:encoding: utf-8 +:lang: en +:icons: font +ifdef::env-github[] +:tip-caption: :bulb: +:note-caption: :information_source: +:important-caption: :heavy_exclamation_mark: +:caution-caption: :fire: +:warning-caption: :warning: +endif::[] +:env-github: + +{zwsp} + + +ifndef::backend-pdf[] +image::bareboat-necessities-logo.svg[Bareboat Necessities Logo] +endif::[] + +{zwsp} + + +toc::[] + +== Abstract + +This document replaces the earlier trochoidal-wave and raw double-integration draft with the more mature estimator now developed in the Ocean IMU project. +The current method is an OU-driven quaternion multiplicative extended Kalman filter, or Q-MEKF, for marine inertial sensing and wave-state estimation. +It estimates attitude, heave, 3D displacement, dominant wave frequency, and horizontal wave direction from a calibrated IMU, with optional magnetometer yaw correction and vessel-specific corrections such as IMU lever arm and steady wind heel. + +The central change is conceptual. +The old draft tried to infer wave height from simplified trochoidal formulas and then use those formulas to help a vertical Kalman integration scheme. +The current method instead models the unknown world-frame wave acceleration as a stationary Ornstein-Uhlenbeck, or OU, process and lets the Kalman filter jointly estimate attitude and wave kinematics. +Drift is controlled by a soft pseudo-measurement on the integral of displacement, with an adaptive covariance that scales with the sea state. + +This formulation is intended for embedded, low-cost marine IMU deployments. +It avoids reliance on barometric pressure for wave elevation, avoids uncontrolled double integration of acceleration, and uses a real-time adaptation loop so that the same filter can remain stable across calm chop, long swell, and larger sea states. + +== Source and Status + +This document is a practical AsciiDoc distillation of the more detailed Ocean IMU mathematical draft: + +* https://github.com/bareboat-necessities/ocean-imu[`bareboat-necessities/ocean-imu`] +* `doc/kalman_ou_iii/kalman_ou-w3d.tex` +* `doc/kalman_ou_iii/w3d-*.tex-part` + +It is not meant to duplicate every proof, coefficient table, or plotting fixture from Ocean IMU. +Instead, it records the model, state layout, update equations, tuning law, and validation results at a level appropriate for the Bareboat Necessities documentation. + +== Motivation + +A boat, buoy, or floating sensor experiences wave-induced translational motion, vessel attitude motion, sensor bias, vibration, magnetic disturbance, and measurement noise at the same time. +Estimating wave height by simply rotating the accelerometer into a vertical axis and double-integrating it is not stable in practice: + +* accelerometer bias integrates into velocity drift and then displacement drift; +* attitude error leaks gravity into the estimated acceleration; +* the initial vertical velocity and displacement are generally unknown; +* low-frequency drift is easily mistaken for long-period swell; +* a barometer does not directly solve the problem on a moving wave surface. + +The mature estimator treats the problem as a coupled inertial-navigation and stochastic wave-kinematics problem. +The wave acceleration is not assumed to be a perfect sinusoid or trochoid. +Instead, it is treated as colored, finite-variance excitation with a correlation time tied to the dominant wave period. + +== Estimator Overview + +The estimator combines four pieces: + +. a quaternion left-multiplicative EKF for attitude and gyro bias; +. a 3D linear kinematic chain for acceleration, velocity, displacement, and the integral of displacement; +. an OU process prior for latent world-frame acceleration; +. an online sea-state tuner that adapts the OU time constant, acceleration variance, and drift-control pseudo-measurement. + +At each IMU step: + +* the gyroscope propagates the nominal quaternion; +* the accelerometer contributes a rank-3 EKF measurement of body-frame specific force; +* the magnetometer, when enabled and stable, contributes a rank-3 yaw/field update; +* the pseudo-measurement `S = 0` softly constrains long-term displacement drift; +* the frequency tracker and tuner update the sea-state parameters. + +== Frames and Signals + +The working world frame is NED: north, east, down. +The body frame is the calibrated IMU or vessel body frame used by the implementation. + +The estimator assumes calibrated triads: + +* gyroscope body rate stem:[omega_m]; +* accelerometer specific force stem:[f_b]; +* magnetometer field stem:[m_b], when available. + +The gravity vector in NED is + +[stem] +++++ +g_w = [0, 0, g]^T, g = 9.80665 m/s^2. +++++ + +The rotation stem:[R_wb] maps world-frame vectors into the body frame. +The nominal attitude is stored as a unit quaternion representing world-to-body orientation. + +== State Vector + +The extended error-state vector is + +[stem] +++++ +x = [delta theta, b_g, v, p, S, a_w, b_a]^T. +++++ + +The state components are: + +[cols="1,4", options="header"] +|=== +| Symbol | Meaning + +| stem:[delta theta] +| Small attitude-error vector used by the left-multiplicative EKF correction. + +| stem:[b_g] +| Gyroscope bias, modeled as a random walk. + +| stem:[v] +| World-frame velocity. + +| stem:[p] +| World-frame displacement or position relative to the local wave-tracking origin. + +| stem:[S] +| Integral of displacement, stem:[S(t) = int_0^t p(lambda) d lambda]. This auxiliary state is used for drift suppression. + +| stem:[a_w] +| Latent world-frame wave acceleration, modeled as an OU process. + +| stem:[b_a] +| Accelerometer bias, modeled as a random walk with optional temperature-dependent drift in the measurement model. +|=== + +With all components enabled, the filter has + +[stem] +++++ +N_X = 3 + 3 + 3 + 3 + 3 + 3 + 3 = 21 +++++ + +states. + +== Measurement Model + +=== Accelerometer + +The accelerometer measures body-frame specific force: + +[stem] +++++ +f_b = R_wb (a_w - g_w) + b_a(T) + n_a. +++++ + +Here + +[stem] +++++ +b_a(T) = b_a0 + k_a (T - T_ref) +++++ + +allows a temperature-dependent accelerometer bias correction, and stem:[n_a] is accelerometer measurement noise. + +For the left-multiplicative convention, the linearized accelerometer Jacobians are + +[stem] +++++ +d f_b / d theta = -skew(f_cog,b), + +d f_b / d a_w = R_wb, + +d f_b / d b_a = I_3. +++++ + +The important point is that the accelerometer update does not merely tilt-correct the attitude. +Because stem:[d f_b / d a_w = R_wb], it also corrects the latent world-frame acceleration state. +That is what ties attitude, gravity alignment, and wave acceleration into one estimator. + +=== Magnetometer + +When magnetometer updates are enabled, the predicted magnetic field is + +[stem] +++++ +m_b = R_wb B_w + n_m. +++++ + +The world magnetic reference stem:[B_w] is obtained from calibration and local magnetic inclination/declination. +The attitude Jacobian is + +[stem] +++++ +d m_b / d theta = -skew(m_b). +++++ + +In practice, magnetometer yaw correction should be delayed until the tilt estimate is stable and a reliable local magnetic reference has been accumulated. + +=== Integral Pseudo-Measurement + +To suppress long-term double-integration drift, the filter applies a zero-valued pseudo-measurement to the integral state: + +[stem] +++++ +z_S = 0 = S + n_S, + +R_S = diag(sigma_Sx^2, sigma_Sy^2, sigma_Sz^2), + +d z_S / d S = I_3. +++++ + +This is not a physical sensor. +It is a soft regularizer. +Repeated application makes the triple integral behave like a leaky integral: low-frequency drift is attenuated while wave-band motion is still allowed. + +The choice of stem:[R_S] is critical: + +* small stem:[R_S] means strong drift control but risks over-regularizing long swell; +* large stem:[R_S] means weak drift control and more low-frequency wandering; +* adaptive stem:[R_S] lets the filter scale this tradeoff with the sea state. + +=== IMU Lever Arm + +If the IMU is not mounted at the vessel center of gravity, angular motion adds apparent acceleration. +For a body-frame lever arm stem:[r_b], body angular velocity stem:[omega_b], and angular acceleration stem:[alpha_b], the accelerometer model becomes + +[stem] +++++ +f_b = f_cog,b + alpha_b xx r_b + omega_b xx (omega_b xx r_b) + b_a(T) + n_a. +++++ + +The lever-arm term is treated as a known kinematic correction. +Setting stem:[r_b = 0] recovers the center-of-gravity model. + +== Continuous-Time Process Model + +=== Quaternion Propagation + +The nominal quaternion is propagated from the bias-corrected gyroscope: + +[stem] +++++ +d q / d t = -1/2 Omega(omega_m - b_g) q. +++++ + +Unit norm is enforced in implementation. +The gyro bias follows a random walk: + +[stem] +++++ +d b_g / d t = w_bg. +++++ + +The small left-multiplicative attitude error evolves approximately as + +[stem] +++++ +d(delta theta)/dt = -skew(omega_m - b_g) delta theta + delta b_g - n_g. +++++ + +=== OU-Driven Kinematic Chain + +For each world axis, the linear chain is + +[stem] +++++ +d v / d t = a_w, + +d p / d t = v, + +d S / d t = p. +++++ + +The latent acceleration is modeled by an OU process: + +[stem] +++++ +d a_w / d t = -(1/tau) a_w + sqrt(2/tau) L_a w_a, + +L_a L_a^T = Sigma_aw. +++++ + +Here stem:[tau] is the acceleration correlation time and stem:[Sigma_aw] is the stationary acceleration covariance. +The OU model is not claiming that the ocean surface is literally an OU process. +It is a compact Gauss-Markov prior for colored wave excitation with bounded variance and a finite correlation time. +That prior is useful because it is Markov, embedded-friendly, and admits analytic discretization. + +The accelerometer bias is modeled as + +[stem] +++++ +d b_a / d t = w_ba. +++++ + +Its temperature correction belongs in the measurement model, not in the process model. + +=== Unified Error-State Form + +The continuous-time linearized error dynamics can be written as + +[stem] +++++ +d x_err / d t = F x_err + L w, + +P_dot = F P + P F^T + Q_c. +++++ + +With measurements, the continuous Kalman-Bucy information term is + +[stem] +++++ +P_dot = F P + P F^T + Q_c - P H^T R^(-1) H P. +++++ + +The implementation uses the corresponding discrete prediction and Joseph-form correction. + +== Discrete-Time Prediction + +For sample interval stem:[h], a linear time-invariant SDE is discretized as + +[stem] +++++ +x_(k+1|k) = Phi(h) x_k, + +P_(k+1|k) = Phi(h) P_k Phi(h)^T + Q_d(h), + +Phi(h) = exp(F h), + +Q_d(h) = int_0^h exp(F t) L Q_c L^T exp(F^T t) d t. +++++ + +The Ocean IMU implementation computes the important OU-driven blocks analytically. +This avoids numerical instability and avoids repeatedly using a general-purpose matrix exponential on small embedded targets. + +=== OU Axis Transition + +For one axis with state stem:[[v, p, S, a]^T], define + +[stem] +++++ +x = h / tau, + +alpha = e^(-x). +++++ + +The per-axis transition has the form + +[stem] +++++ +Phi_axis = [ + 1, 0, 0, phi_va; + h, 1, 0, phi_pa; + 1/2 h^2, h, 1, phi_Sa; + 0, 0, 0, alpha +]. +++++ + +The coupling terms are + +[stem] +++++ +phi_va = tau (1 - alpha), + +phi_pa = tau^2 (x + alpha - 1), + +phi_Sa = tau^3 (1/2 x^2 - x - alpha + 1). +++++ + +The full 3D OU-chain transition is the block diagonal stacking of three such axis transitions. +The covariance stem:[Q_d] is computed from an exact coefficient matrix for normal stem:[x] and from a Maclaurin branch for small stem:[x], followed by symmetrization and positive-semidefinite cleanup. + +== Rank-3 Measurement Updates + +The accelerometer, magnetometer, and pseudo-measurement channels are all rank-3 updates. +For a measurement + +[stem] +++++ +z = h(x) + nu, +++++ + +the EKF update is + +[stem] +++++ +r = z - h(x^-), + +S_innov = H P^- H^T + R, + +K = P^- H^T S_innov^(-1), + +x^+ = x^- + K r. +++++ + +The covariance update should use the Joseph form: + +[stem] +++++ +P^+ = (I - K H) P^- (I - K H)^T + K R K^T. +++++ + +After each correction, the attitude-error subvector is injected back into the nominal quaternion: + +[stem] +++++ +q <- exp(1/2 delta theta) ox q, + +delta theta <- 0. +++++ + +The rank-3 structure is important for embedded use. +The expensive inversion is only a 3 by 3 solve for each triad update. + +== Initialization and Reference Alignment + +Startup should be staged. +The filter should not immediately trust yaw, acceleration bias, displacement, or drift-control states. + +A practical sequence is: + +. Estimate gravity direction from accelerometer data and initialize roll/pitch. +. Leave yaw arbitrary until a stable magnetic reference is available. +. Run an early attitude-only or reduced-state phase while the frequency tracker gathers statistics. +. Enable the full linear wave block after the tuner has usable estimates of frequency and acceleration variance. +. Delay magnetometer yaw correction until tilt is stable and magnetic samples have been accumulated in the tilt frame. +. Enter live operation with online adaptation enabled. + +This avoids seeding displacement, bias, and pseudo-measurement states with startup transients. + +== Frequency Tracking + +Adaptive tuning requires an online estimate of the dominant wave frequency. +The signal is derived from vertical inertial acceleration, typically as an up-positive scalar: + +[stem] +++++ +a_up = -a_z,inert. +++++ + +Three embedded-friendly trackers are supported in Ocean IMU: + +[cols="1,4", options="header"] +|=== +| Tracker | Role + +| KalmANF adaptive notch +| Models the signal with a second-order notch and updates the notch parameter with a scalar Kalman step. + +| Aranovskiy observer +| Uses a nonlinear sinusoidal frequency observer with a filtered input and adaptive auxiliary state. + +| PLL +| Uses a band-passed signal, I/Q demodulation, and a bounded PI phase-locked loop. +|=== + +The raw frequency is clamped and smoothed to produce stem:[f_tune], which drives the sea-state tuner and the horizontal wave-direction estimator. + +== Variance-Informed Online Adaptation + +The tuner adapts three quantities: + +* OU correlation time stem:[tau]; +* stationary acceleration scale stem:[sigma_a]; +* integral pseudo-measurement level stem:[R_S]. + +The variance estimate is tied to a fixed number of wave periods so that the adaptation horizon scales naturally between chop and swell: + +[stem] +++++ +T_eff = 1 / f_tune, + +tau_var = clip(K_periods T_eff, tau_var,min, tau_var,max), + +alpha_var = 1 - e^(-Delta t / tau_var). +++++ + +After subtracting a configured acceleration noise floor, + +[stem] +++++ +sigma_wave^2 = max(0, sigma_tot^2 - sigma_nf^2), +++++ + +the target parameters are + +[stem] +++++ +tau_star = c_tau / (2 f_tune), + +sigma_a,star = c_sigma sqrt(max(sigma_wave^2, epsilon)), + +R_S,star = c_R sigma_a,star tau_star^3. +++++ + +The applied values are exponentially smoothed. +stem:[tau] and stem:[sigma_a] use a fixed adaptation time constant. +stem:[R_S] is smoothed with a time constant proportional to the current wave time scale, so it responds faster in short-period seas and slower in long-period swell. + +=== Why stem:[R_S] Scales as stem:[sigma_a tau^3] + +The pseudo-measurement is not arbitrary. +The triple-integral state stem:[S] is the result of integrating acceleration three times: + +[stem] +++++ +d v / d t = a, + +d p / d t = v, + +d S / d t = p. +++++ + +In the frequency domain, the transfer from acceleration to stem:[S] has magnitude squared proportional to stem:[1 / omega^6]. +For a broad class of wave spectra, after separating spectrum scale from spectrum shape, the natural spread of stem:[S] follows + +[stem] +++++ +sigma_S ~= c_spec sigma_a tau^3. +++++ + +Therefore a practical sea-state-invariant pseudo-measurement law is + +[stem] +++++ +R_S = k_i sigma_a tau^3. +++++ + +This makes a calm sea and a steep sea produce comparable normalized pseudo-measurement innovations. +The filter does not become overly stiff in large waves or overly loose in calm conditions purely because the acceleration level changed. + +=== Anisotropy + +The implementation may use different horizontal and vertical settings: + +[stem] +++++ +Sigma_aw^(1/2) = diag(S_sigma sigma_a, S_sigma sigma_a, sigma_a), + +R_S = diag(rho_xy R_S, rho_xy R_S, R_S). +++++ + +This allows stronger or weaker horizontal regularization without changing the vertical heave behavior. + +== Horizontal Wave Direction + +The filter estimates a slowly varying horizontal acceleration amplitude vector stem:[A_k]. +Let + +[stem] +++++ +z_k = [a_x(k), a_y(k)]^T. +++++ + +For a dominant narrow-band wave with phase stem:[phi_k], the simplified observation model is + +[stem] +++++ +z_k ~= cos(phi_k) A_k + eta_k. +++++ + +This is the online Kalman-filter form of a cosine-projection least-squares fit: + +[stem] +++++ +A_LS = (sum_k cos(phi_k) z_k) / (sum_k cos(phi_k)^2). +++++ + +The 2D direction filter uses + +[stem] +++++ +A_(k+1) = A_k + w_k, + +H_k = cos(phi_k) I_2, + +z_k = H_k A_k + eta_k. +++++ + +When stem:[abs(cos(phi_k))] is too small, the update is skipped because the observation carries little information near horizontal zero crossings. + +The wave line angle is + +[stem] +++++ +d_hat = A_k / ||A_k||, + +theta = wrap_[0,180)(atan2(d_y, d_x) 180 / pi). +++++ + +This gives direction modulo stem:[180 deg]. +A separate vertical-horizontal phase discriminator can choose the travel sense along that line, producing a directed azimuth when the sign estimate is stable. + +== Validation Summary + +Ocean IMU validates the filter on synthetic directional sea states with controlled ground truth. +The simulations use 20 minute runs at 200 Hz, with IMU and magnetometer error models representative of low-cost MEMS hardware. + +=== Wave Scenarios + +[cols="1,2,1,1,2", options="header"] +|=== +| Scenario | Model | stem:[H_s] m | stem:[T_p] s | Directional spread + +| W1 | JONSWAP, PM-Stokes | 0.27 | 3.0 | +30 deg / cos-spread +| W2 | JONSWAP, PM-Stokes | 1.50 | 5.7 | -30 deg / cos-spread +| W3 | JONSWAP, PM-Stokes | 4.00 | 8.5 | +30 deg / cos-spread +| W4 | JONSWAP, PM-Stokes | 8.50 | 11.4 | -30 deg / cos-spread +|=== + +=== Simulation Results + +The table below summarizes the last 60 seconds RMS window from the Ocean IMU validation run. +`R/P/Y` are roll, pitch, and yaw RMS errors in degrees. +`T/A/U` means Toward, Away, and Uncertain percentage of samples for the sign discriminator. + +[cols="1,1,1,1,1,1,1,1,1", options="header"] +|=== +| Case | stem:[H_s] | Z RMS m | Z % stem:[H_s] | R deg | P deg | Y deg | mean theta deg | T/A/U % + +| JONSWAP | 0.27 | 0.026 | 9.7 | 0.42 | 0.30 | 1.11 | 29.2 | 99.5/0.0/0.5 +| JONSWAP | 1.50 | 0.085 | 5.7 | 0.45 | 0.65 | 0.34 | -32.7 | 100.0/0.0/0.1 +| JONSWAP | 4.00 | 0.297 | 7.4 | 0.60 | 1.36 | 1.59 | 31.5 | 99.3/0.7/0.0 +| JONSWAP | 8.50 | 0.453 | 5.3 | 1.37 | 0.54 | 1.06 | -30.8 | 99.0/0.6/0.4 +| PM+Stokes | 0.27 | 0.020 | 7.6 | 0.37 | 0.12 | 1.94 | 37.3 | 99.7/0.0/0.3 +| PM+Stokes | 1.50 | 0.063 | 4.2 | 0.18 | 0.17 | 2.10 | -34.5 | 99.7/0.0/0.3 +| PM+Stokes | 4.00 | 0.262 | 6.6 | 0.19 | 0.39 | 2.10 | 26.4 | 100.0/0.0/0.0 +| PM+Stokes | 8.50 | 0.537 | 6.3 | 1.00 | 0.56 | 2.21 | -19.1 | 99.8/0.0/0.2 +|=== + +The simulation results show drift-suppressed vertical displacement while retaining realistic wave-band motion. +The model also keeps roll, pitch, yaw, and wave-direction estimates bounded under sensor noise, residual bias, and multicomponent directional seas. + +== Embedded Hardware Platform + +The implementation has also been exercised on real embedded hardware using the M5Stack AtomS3R ESP32-S3 module. +The purpose of this validation is to confirm real-time behavior and implementation feasibility: + +* fixed-rate IMU sampling; +* bounded memory use; +* calibrated sensor triads; +* quaternion propagation from gyroscope data; +* rank-3 accelerometer updates at IMU rate; +* delayed magnetometer yaw correction when available; +* adaptive frequency and sea-state tuning from the vertical acceleration-like signal. + +Quantitative wave-kinematics accuracy is evaluated in simulation, where exact displacement, velocity, acceleration, and attitude ground truth are available. +Real hardware validates the embedded execution path and sensor-processing pipeline. + +== Practical Implementation Notes + +=== Prefer a Unified Filter Over a Pipeline + +The mature method does not first estimate attitude, then separately integrate acceleration, then separately estimate wave spectra. +It keeps attitude, acceleration, velocity, displacement, and drift control in one covariance model. +This is important because tilt error and acceleration error are coupled by gravity. + +=== Do Not Treat the Pseudo-Measurement as a Sensor + +The stem:[S = 0] pseudo-measurement is an artificial stabilizer. +Its covariance is a tuning parameter. +It should be adapted from frequency and acceleration variance, not chosen as a fixed physical sensor noise. + +=== Use Calibrated Axes + +All equations assume that accelerometer, gyro, and magnetometer readings have already been calibrated and mapped into the expected body-frame convention. +Hard-iron, soft-iron, scale, axis alignment, and gyro/accelerometer bias calibration should be handled before the estimator input stage. + +=== Correct Lever Arm When Needed + +An IMU mounted away from the vessel center of gravity will see angular-acceleration and centripetal terms. +For small boats and low-cost modules this can be a large source of error. +Use the lever-arm correction when the installation geometry is known. + +=== Delay Magnetometer Trust + +Magnetometer data are useful for yaw, but they are easily corrupted by local magnetic disturbances. +The estimator should initialize tilt first, accumulate a stable magnetic reference, and only then enable regular yaw updates. + +=== Barometer Is Not the Primary Wave Sensor + +A barometer can be useful for weather and slow altitude trends, but it should not be treated as a direct wave-elevation sensor on a floating platform. +The wave surface is not a static height field measured by air pressure in the way hiking or stair-climbing algorithms assume. + +== Relationship to the Old Draft + +The old document contained useful early notes about why double integration drifts and why pressure is not a reliable wave-height source on the wave surface. +Those points remain valid. +However, the trochoidal reconstruction and Doppler-based approach is no longer the preferred core algorithm. + +The current preferred algorithm is: + +. calibrated IMU and optional magnetometer input; +. quaternion MEKF for attitude and gyro bias; +. OU-driven 3D kinematic chain for wave acceleration, velocity, displacement, and integral displacement; +. adaptive pseudo-measurement drift control; +. online frequency tracking and wave-direction estimation; +. simulation validation against directional JONSWAP and PM-Stokes sea states; +. embedded execution on ESP32-S3-class hardware. + +== References + +* Bareboat Necessities Ocean IMU project: https://github.com/bareboat-necessities/ocean-imu +* M. S. Grushinskiy, _OU-Driven Quaternion MEKF for Marine INS and Wave-State Estimation_, draft in `ocean-imu/doc/kalman_ou_iii`. +* R. E. Kalman, _A New Approach to Linear Filtering and Prediction Problems_, 1960. +* G. E. Uhlenbeck and L. S. Ornstein, _On the Theory of the Brownian Motion_, 1930. +* F. L. Markley, _Attitude Error Representations for Kalman Filtering_, 2003. +* J. Sola, _Quaternion Kinematics for the Error-State Kalman Filter_, 2017. +* S. M. Sharkh et al., _A Novel Kalman Filter Based Technique for Calculating the Time History of Vertical Displacement of a Boat from Measured Acceleration_, 2014. diff --git a/markup/math/chapter_02_52ac82.rmd b/markup/math/chapter_02_52ac82.rmd new file mode 100644 index 0000000..f94c1b5 --- /dev/null +++ b/markup/math/chapter_02_52ac82.rmd @@ -0,0 +1,859 @@ +--- +title: "Overview of Supervised Learning" +output: + html_document: + toc: yes +--- + + + +--- + +## Note [p:12 para:2 eq:2.5] derivative-scalar-by-vector + +Item | Description +--- | --- +Authors | [PengjuYan](https://github.com/PengjuYan) +Date | 2015/8/18 +Reference | [Wikipedia: Matrix calculus][wikipedia-matrix-calculus] + +[wikipedia-matrix-calculus]: https://en.wikipedia.org/wiki/Matrix_calculus + +There are 2 _flavors_ of definition of **the derivative of a scalar by a vector** in terms of the form of the resultant vector: + +- Row vector: [Wikipedia: Matrix calculus][wikipedia-matrix-calculus], [tirgul3_derivatives.pdf: Derivatives with respect to vectors](http://www.cs.huji.ac.il/~csip/tirgul3_derivatives.pdf) +- Column vector: [IFEM.AppF.pdf: Matrix Calculus](http://www.colorado.edu/engineering/cas/courses.d/IFEM.d/IFEM.AppF.d/IFEM.AppF.pdf), [onlinelibrary: Differentiation with respect to a vector](http://onlinelibrary.wiley.com/doi/10.1002/0471705195.app3/pdf) + +This book follows the latter, i.e., the column vector form: + +$$ +\begin{equation} +\frac{\partial{y}}{\partial{\mathbf{x}}} = \begin{bmatrix} \frac{\partial y}{\partial x_1} \\ \frac{\partial y}{\partial x_2} \\ \vdots \\ \frac{\partial y}{\partial x_n} \end{bmatrix} +\end{equation} +$$ + +This can also be verified by equation (3.14) on page 45. + +--- + +## Note [p:15 para:-2] knn-degrees-of-freedom + +Item | Description +--- | --- +Authors | [PengjuYan](https://github.com/PengjuYan) +Date | 2015/8/20 +Reference | [Wikipedia: Degrees of freedom][wikipedia-degrees-of-freedom] + +[wikipedia-degrees-of-freedom]: https://en.wikipedia.org/wiki/Degrees_of_freedom_%28statistics%29 + +In the paragraph of interest, it is said that: + +> ... we will see that the _effective_ number of parameters of $k$-nearest neighbors is $N/k$ ... To get an idea of why, note that if the neighborhoods were nonoverlapping, there would be $N/k$ neighborhoods and we would fit one parameter (a mean) in each neighborhood. + +In order to understand this paragraph quantitatively, we may need to refer to [Wikipedia: Degrees of freedom][wikipedia-degrees-of-freedom] and equation (3.50) on page 68. In many regression tasks, including $k$-nearest-neighbors, the prediction on training data can be given by a linear combination of target values of the training samples: + +$$ +\begin{equation} +\hat{\mathbf{y}} = \mathbf{H}\mathbf{y} +\end{equation} +$$ + +A general definition of the **effective degrees of freedom** is given by the trace of the **hat** matrix $\mathbf{H}$: + +$$ +\begin{equation} +\mathrm{tr}\left(\mathbf{H}\right) = \sum_{i} h_{ii} +\end{equation} +$$ + +In a $k$-nearest-neighbor fit, each row of the hat matrix $\mathbf{H}$ contains exactly $k$ non-zero cells with the value of $1/k$, and the diagonal cell is always $1/k$ because the nearest neighbor of each data sample is of course itself. Therefore, the trace of the hat matrix is naturally $N/k$. + +--- + +## Note [p:16 para:-1] - [p:17 para:1] simulated-gaussian-mixture + +Item | Description +--- | --- +Authors | [PengjuYan](https://github.com/PengjuYan) +Date | 2015/9/1 +Reference | [Wikipedia: Mixture model][wikipedia-mixture-model] + +[wikipedia-mixture-model]: https://en.wikipedia.org/wiki/Mixture_model + +In section 2.3, the training data were _simulated from a model somewhere between the two, but closer to Scenario 2_. + +> **Scenario 1**: The training data in each class were generated from bivariate Gaussian distributions with uncorrelated components and different means. + +> **Scenario 2**: The training data in each class came from a mixture of 10 low-variance Gaussian distributions, with individual means themselves distributed as Gaussian. + +The sampling procedure described in the paragraph of interest **follows** the definition of Gaussian mixture models of no doubt. The difference between that procedure and Scenario 2 lies in the fact that the two means of the Gaussian distributions from which the individual means of the two classes were drawn **are different**, which are $\left(1, 0\right)^T$ and $\left(0, 1\right)^T$, respectively. In Scenario 2 however, the individual means follow the same Gaussian distribution. Therefore, the separability of the simulated data lies between Scenario 1 and Scenario 2. + +--- + +## Note [p:23 para:1] high-dimension-extrapolation + +Item | Description +--- | --- +Authors | [PengjuYan](https://github.com/PengjuYan) +Date | 2015/9/10 +Reference | [Wikipedia: Extrapolation][wikipedia-extrapolation] + +[wikipedia-extrapolation]: https://en.wikipedia.org/wiki/Extrapolation + +In the paragraph of interest, it is said that: + +> Hence most data points are closer to the boundary of the sample space than to any other data point. The reason that this presents a problem is that prediction is much more difficult near the edges of the training sample. One must extrapolate from neighboring sample points rather than interpolate between them. + +Interpolation and extrapolation correspond to predictions inside and at the boundary of the training region, respectively. + +Let's first illustrate the difference in the 1-dimensional space. When we need to predict the $y$ value given a test data point $x$ _inside_ the training region, then we can find approximately $k/2$ training data points at both left and right sides of $x$, then we can predict $y$ by _interpolating_ among the $k$ surrounding training data points. However, when $x$ is at the left _boundary_ of the training region, then we may find that only $k/10$ of the $k$-nearest neighbors are at the left side of $x$, and the rest $9k/10$ are at the right side. Or even more unfortunetaly, all the $k$-nearest neighbors could be at the right side of $x$. Therefore, we are actually _extrapolating_ from the neighbors in order to predict $y$, because $x$ is not well _embraced_ by the $k$-nearest neighbors. + +In high dimensional spaces, most points appear at the boundaries. For each $x$ we want to predict, it is extremely highly possible that $x$ lies at the boundary of the training region. Most of the $k$-nearest neighbors of $x$ are just at one side of $x$ hence are not embracing $x$ well. That comes the sentence **"One must extrapolate from neighboring sample points rather than interpolate between them"**. + +--- + +## Ex. 2.1 output-class-index + +Item | Description +--- | --- +Authors | [justdark](https://github.com/justdark) +Date | 2015/9/5 + +**Ex. 2.1** Suppose each of $K$-classes has an associated target $t_{k}$, which is a vector of all zeros, except a one in the $k$th position. Show that classifying to the largest element of $\hat{y}$ amounts to choosing the closest target, $\mathrm{min}_{k}\left\Vert t_{k} - \hat{y}\right\Vert$, if the elements of $\hat{y}$ sum to one. + +**Proof** + +According to the description, what we need to prove is: + +$$ +\begin{equation} +\mathop{\mathrm{argmax}}_{k}\left(\hat{y}_k\right)=\mathop{\mathrm{argmin}}_{k}\left(\left\Vert t_{k}-\hat{y}\right\Vert\right) +\end{equation} +$$ + +So we have: +$$ +\begin{align} +\mathop{\mathrm{argmin}}_{k}\left(\left\Vert t_{k}-\hat{y}\right\Vert\right) &= \mathop{\mathrm{argmin}}_{k}\left\Vert t_{k}-\hat{y}\right\Vert^2 \\ +&= \mathop{\mathrm{argmin}}_{k} \sum_{i=1}^K\left[\left(t_{k}\right)_{i}-\hat{y}_i\right]^2 \\ +&= \mathop{\mathrm{argmin}}_{k} \sum_{i=1}^K\left[\left(t_{k}\right)_{i}^2+\hat{y}_i^2-2\left(t_{k}\right)_{i}\hat{y}_i\right] \\ +&= \mathop{\mathrm{argmin}}_{k} \sum_{i=1}^K\left[\left(t_{k}\right)_{i}^2-2\left(t_{k}\right)_{i}\hat{y}_i\right] \\ +&= \mathop{\mathrm{argmin}}_{k} \left[\sum_{i=1}^K\left(t_{k}\right)_{i}^2-\sum_{i=1}^K2\left(t_{k}\right)_{i}\hat{y}_i\right] \\ +&= \mathop{\mathrm{argmin}}_{k} \left[1-\sum_{i=1}^K2\left(t_{k}\right)_{i}\hat{y}_i\right] \\ +&= \mathop{\mathrm{argmax}}_{k} \sum_{i=1}^K\left[\left(t_{k}\right)_{i}\hat{y}_i\right] \\ +&= \mathop{\mathrm{argmax}}_{k} \left(\hat{y}_k\right) +\end{align} +$$ + +As you can see, the last condition that the elements of $\hat{y}$ sum to one doesn't appear in our proof, because it's unnecessary for the conclusion. + +--- + +## Ex. 2.2 bayes-decision-boundary + +Item | Description +--- | --- +Authors | [justdark](https://github.com/justdark) +Date | 2015/9/8 + +**Ex. 2.2** Show how to compute the Bayes decision boundary for the simulation example in Figure 2.5. + +**Proof** + +From the description we can conclude that the boundary's property: +$$ +\begin{equation} +Pr\left(\mathcal{G}_{orange}\left|\right.X=x\right)=Pr\left(\mathcal{G}_{blue}\left|\right.X=x\right) +\end{equation} +$$ +where x is the point on the boundary. By the Bayes equation: +$$ +\begin{equation} +Pr\left(\mathcal{G}_{k}\left|\right.X = x\right) = \frac{Pr\left(X = x\left|\right.\mathcal{G}_{k}\right)Pr\left(\mathcal{G}_{k}\right)}{Pr\left(X=x\right)} +\end{equation} +$$ + +Because the $Count\left(orange\right)=Count\left(blue\right)$, so +$$ +\begin{equation} +Pr\left(\mathcal{G}_{orange}\right)=Pr\left(\mathcal{G}_{blue}\right) +\end{equation} +$$ + +We can simplify the boundary's property, it's also **the solution of this exercise**: +$$ +\begin{align} +Pr\left(X = x\left|\right.\mathcal{G}_{orange}\right)&=Pr\left(X = x\left|\right.\mathcal{G}_{blue}\right) +\end{align} +$$ + +How to calculate the $Pr\left(X = x\left|\right.\mathcal{G}_{k}\right)$ ? + +For the **Scenario 1**, if the $\mathcal{G}$ is simulated from two bivariate Guassian distribution, we can use the **probability density function (pdf)** of Guassian distribution: +$$ +\begin{align} +f\left(x\right)=\frac{1}{\sqrt{\left(2\pi\right)^{2}\left|\Sigma\right|}}\exp\left(-\frac{1}{2}\left({x}-{\mu}\right)^\mathrm{T}{\Sigma}^{-1}\left({x}-{\mu}\right)\right) +\end{align} +$$ +where $\left|\Sigma\right|$ is the determinant of $\Sigma$ +Because the $\sigma$ is same for all class, so the boundary is actually **midperpendicular** of line segment from $\mu_{orange}$ to $\mu_{blue}$. + +For a more complicated scenario which generate the data in Figure 2.5, each class, we first generate 5 points as the 5 new Guassian distributions' mean, then each distribution generates 20 points as the results, finally we got 100 points for the class. + +Use $\left(m_k\right)_t,t\le5$ as the results of the first step for class $k$. +The probability that a point is generate from a given mean $\left(m_k\right)_t$ is: +$$ +\begin{align} +f\left(x,\left(m_k\right)_t\right)=\frac{1}{\sqrt{\left(2\pi\right)^{2}\left|\Sigma^{'}\right|}}\exp\left(-\frac{1}{2}\left[{x}-{\left(m_k\right)_t}\right]^\mathrm{T}{\Sigma^{'}}^{-1}\left[{x}-{\left(m_k\right)_t}\right]\right) +\end{align} +$$ +(add apostrophe on the $\Sigma$ to distinguish it from basic one) + +So we can define the probability that the point is generate from the $k$th class as: +$$ +\begin{align} +Pr\left(X = x\left|\right.\mathcal{G}_{k}\right) = \frac{1}{5}\sum_{t=1}^{5}f\left(x,\left(m_k\right)_t\right) +\end{align} +$$ +This equation is more complicated than scenario 1, with the sum over $exp$ function, so the boundary is nonlinear as plot on Figure 2.5. +--- + +## Ex. 2.3 median-distance-of-sphere + +Item | Description +--- | --- +Authors | [maorenxin](https://github.com/maorenxin) +Date | 2015/9/8 +Reference | [Wikipedia: Volume of the n-sphere](https://en.wikipedia.org/wiki/Sphere) + + +**Ex. 2.3** Derive equation (2.24). +$$ +\begin{equation} +d\left(p, N\right) = \left(\ 1- \frac{1}{2}^{1/N} \right)^{1/p} +\end{equation} +$$ + +**Proof** + +First of all, let $r$ be the median distance from the origin to the closest data point. Then +$$ +\begin{equation} +P\left(\text{All } N \text{ points are further than r from the origin}\right) = \frac{1}{2} +\end{equation} +$$ + +Since points $x_i$ are independently distributed, which implies that +$$ +\begin{equation} +\frac{1}{2} = \prod_{i=1}^N P\left(\left\Vert x_i \right\Vert > r\right) +\end{equation} +$$ + +and as points $x_i$ are uniformly distributed in the unit ball, we have + +$$ +\begin{align} +P \left(\left\Vert x_i \right\Vert > r \right) &= 1- P\left(\left\Vert x_i \right\Vert \leq r \right) \\ +&= 1 - \frac{V_p\left(r\right)}{V_p\left(R\right)} \\ +&= 1- r^p +\end{align} +$$ +and $V$ represents Volume. + +Putting all together, we obtain that +$$ +\begin{equation} +\frac{1}{2}=\left(1-r^p \right)^N +\end{equation} +$$ + +and solving for $r$, we will have +$$ +\begin{equation} +d\left(p, N\right) = \left(\ 1- \frac{1}{2}^{1/N} \right)^{1/p} +\end{equation} +$$ + +For the sphere volume of $p$ dimension, we can refer to [Volume of the n-sphere](https://en.wikipedia.org/wiki/Sphere) for more detail. Here we demonstrate the formula: +$$ +\begin{align} +V_p\left({R}\right) = \frac{R^p}{n} \frac{2\pi^{p/2}}{\Gamma \left(n/2\right)} \\ +\Gamma\left(n/2\right) = \frac{\left(n-2\right)!!\sqrt{\pi}}{2^{\left(n-1\right)/2}} +\end{align} +$$ + +--- + +## Ex. 2.5 linear-model-bias-variance + +Item | Description +--- | --- +Authors | [squall1988](https://github.com/squall1988), [PengjuYan](https://github.com/PengjuYan) +Date | 2015/9/10 +Reference | [Wikipedia: Bias–variance tradeoff][wikipedia-bias-variance_tradeoff], [Wikipedia: Trace][wikipedia-trace], [Wikipedia: Quadratic form][wikipedia-quadratic-form] + +[wikipedia-bias-variance_tradeoff]: https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff +[wikipedia-trace]: https://en.wikipedia.org/wiki/Trace_%28linear_algebra%29 +[wikipedia-quadratic-form]: https://en.wikipedia.org/wiki/Quadratic_form_%28statistics%29 + +**Ex. 2.5** + +\(a) Derive equation (2.27). The last line makes use of (3.8) through a +conditioning argument. + +\(b) Derive equation (2.28), making use of the _cyclic_ property of the trace +operator $\left[\mathrm{trace}\left(AB\right) = \mathrm{trace}\left(AB\right)\right]$, and its linearity (which allows us +to interchange the order of trace and expectation). + +**Proof (a)** + +**Step a.1** Let's first prove equation (2.25) the bias-variance decomposition of mean squared error (MSE): + +$$ +\begin{align} +MSE\left(x_0\right) +&= E_{\mathcal{T}} \left[f\left(x_0\right) - \hat{y}_0\right]^2 \\ +&= E_{\mathcal{T}} \left[\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 + \left[E_{\mathcal{T}}\left(\hat{y}_0\right) - f\left(x_0\right)\right]^2 \\ +&= Var_{\mathcal{T}}\left(\hat{y}_0\right) + Bias^2\left(\hat{y}_0\right) +\end{align} +$$ + +It can be shown by the following derivations: + +$$ +\begin{align} +MSE\left(x_0\right) +&= E_{\mathcal{T}} \left[\hat{y}_0 - f\left(x_0\right)\right]^2 \\ +&= E_{\mathcal{T}} \left[\left(\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right) - \left(f\left(x_0\right)- E_{\mathcal{T}}\left(\hat{y}_0\right)\right)\right]^2 \\ +&= E_{\mathcal{T}} \left[\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 -2E_{\mathcal{T}} \left[\left(\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right) \left(f\left(x_0\right) - E_{\mathcal{T}}\left(\hat{y}_0\right)\right)\right] + E_{\mathcal{T}} \left[f\left(x_0\right) - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 \\ +&= E_{\mathcal{T}} \left[\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 -2 \left(f\left(x_0\right) - E_{\mathcal{T}}\left(\hat{y}_0\right)\right) E_{\mathcal{T}} \left(\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right) + \left[f\left(x_0\right) - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 \\ +&= E_{\mathcal{T}} \left[\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 -2 \left(f\left(x_0\right) - E_{\mathcal{T}}\left(\hat{y}_0\right)\right) \times 0 + \left[f\left(x_0\right) - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 \\ +&= E_{\mathcal{T}} \left[\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 + \left[f\left(x_0\right) - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 \\ +\label{eq:ex-2.5-mse} +&= Var_{\mathcal{T}}\left(\hat{y}_0\right) + Bias^2\left(\hat{y}_0\right) +\end{align} +$$ + +Note that the bias-variance decomposition of MSE does not depend on any specific assumptions such as linear models or independence. + +**Step a.2** Then we show that expected prediction error (EPE) can be decomposed to the irreducible squared error $\sigma^2$ and MSE. + +$$ +\begin{align} +\label{eq:ex-2.5-epe-expection} +EPE\left(x_0\right) +&= E_{y_0|x_0}E_{\mathcal{T}} \left[y_0 - \hat{y}_0\right]^2 \\ +&= E_{y_0|x_0}E_{\mathcal{T}} \left[\left(y_0 - f\left(x_0\right)\right) - \left(\hat{y}_0- f\left(x_0\right)\right)\right]^2 \\ +&= E_{y_0|x_0}E_{\mathcal{T}} \left[y_0 - f\left(x_0\right)\right]^2 -2 E_{y_0|x_0}E_{\mathcal{T}} \left[\left(y_0 - f\left(x_0\right)\right)\left(\hat{y}_0- f\left(x_0\right)\right)\right] + E_{y_0|x_0}E_{\mathcal{T}} \left[\hat{y}_0- f\left(x_0\right)\right]^2 \\ +&= E_{y_0|x_0} \left[y_0 - f\left(x_0\right)\right]^2 -2 E_{y_0|x_0} \left(y_0 - f\left(x_0\right)\right) \times E_{\mathcal{T}} \left[\left(\hat{y}_0- f\left(x_0\right)\right)\right] + E_{\mathcal{T}} \left[\hat{y}_0- f\left(x_0\right)\right]^2 \\ +&= Var\left(y_0|x_0\right) -2 \times 0 \times E_{\mathcal{T}} \left[\left(\hat{y}_0- f\left(x_0\right)\right)\right] + MSE\left(x_0\right) \\ +&= Var\left(y_0|x_0\right) + MSE\left(x_0\right) \\ +\end{align} +$$ + +Also note that in the proof above, the only necessary assumption is that the expectation of the noise term $\epsilon$ in $y=f\left(x\right)+\epsilon$ is $0$. We do not need any further assumptions like linear models or unbiased estimation. + +Finally we get the EPE equation: + +$$ +\begin{equation} +\label{eq:ex-2.5-epe} +EPE\left(x_0\right) = Var\left(y_0|x_0\right) + Var_{\mathcal{T}}\left(\hat{y}_0\right) + Bias^2\left(\hat{y}_0\right) +\end{equation} +$$ + +**Step a.3** Now we need to prove equation (2.27) under the assumptions that $\epsilon$ follows $\mathcal{N}\left(0, \sigma^2\right)$, the relationship between $Y$ and $X$ is linear, and the estimator is a linear regression model. + +For a linear regression model, the estimated parameter is given by (see equation(3.6) on page 45): + +$$ +\begin{align} +\hat{\beta} +&= \left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{y} \\ +&= \left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\left(\mathbf{X}\beta + \mathbf{\epsilon}\right) \\ +&= \beta + \left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon} +\end{align} +$$ + +Then $\hat{y}_0$ is + +$$ +\begin{align} +\hat{y}_0 +&= x_0^T\hat{\beta} \\ +&= x_0^T\beta + x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon} +\end{align} +$$ + +and $E_{\mathcal{T}}\left(\hat{y}_0\right)$ is + +$$ +\begin{align} +E_{\mathcal{T}} \left(\hat{y}_0\right) +&= E_{\mathcal{T}} \left(x_0^T\hat{\beta}\right) \\ +&= E_{\mathcal{T}} \left(x_0^T\beta\right) + E_{\mathcal{T}} \left[x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon}\right] \\ +&= x_0^T\beta + E_{\mathcal{X}}E_{\mathcal{\epsilon}|\mathcal{X}} \left[x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon}\right] \\ +&= x_0^T\beta + E_{\mathcal{X}}0 \\ +&= x_0^T\beta +\end{align} +$$ + +Now look at bias and variance of $\hat{y}_0$: + +$$ +\begin{align} +Bias^2\left(\hat{y}_0\right) +&= \left[E_{\mathcal{T}}\left(\hat{y}_0\right) - f\left(x_0\right)\right]^2 \\ +&= \left[x_0^T\beta - x_0^T\beta\right]^2 \\ +\label{eq:ex-2.5-bias} +&= 0 \\ +Var_{\mathcal{T}}\left(\hat{y}_0\right) +&= E_{\mathcal{T}} \left[\hat{y}_0 - E_{\mathcal{T}}\left(\hat{y}_0\right)\right]^2 \\ +&= E_{\mathcal{T}} \left[x_0^T\beta + x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon} - x_0^T\beta\right]^2 \\ +&= E_{\mathcal{T}} \left[x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon}\right]^2 \\ +&= E_{\mathcal{T}} \left[\left(x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon}\right) \left(x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon}\right)^T\right] \\ +&= E_{\mathcal{T}} \left[x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{\epsilon}\mathbf{\epsilon}^T\mathbf{X}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}x_0\right] \\ +&= E_{\mathcal{T}} \left[x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\sigma^2I_N\mathbf{X}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}x_0\right] \\ +&= \sigma^2E_{\mathcal{T}} \left[x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{X}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}x_0\right] \\ +\label{eq:ex-2.5-variance} +&= \sigma^2E_{\mathcal{T}} \left[x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}x_0\right]^2 +\end{align} +$$ + +Putting $\eqref{eq:ex-2.5-epe}$, $\eqref{eq:ex-2.5-bias}$ and $\eqref{eq:ex-2.5-variance}$ together, we can finally prove equation (2.27): + +$$ +\begin{align} +EPE\left(x_0\right) +&= Var\left(y_0|x_0\right) + Var_{\mathcal{T}}\left(\hat{y}_0\right) + Bias^2\left(\hat{y}_0\right) \\ +&= \sigma^2 + \sigma^2E_{\mathcal{T}} \left[x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}x_0\right] + 0 +\end{align} +$$ + +**Proof (b)** + +In the proof we will use the following properties: + +1. If $N$ is large and $\mathcal{T}$ were selected at random, and assuming +$E\left(X\right) = 0$, then $\mathbf{X}^T\mathbf{X} \rightarrow NCov\left(\mathbf{X}\right)$. +1. Cyclic property of the trace operator: $\mathrm{trace}\left(AB\right) = \mathrm{trace}\left(AB\right)$. +1. Both the trace and expectation operators are linear, so they can be interchanged: $E \circ trace = trace \circ E$. + +$$ +\begin{align} +E_{x_0}EPE\left(x_0\right) +&\sim \sigma^2/N \cdot E_{x_0}\left[x_0^TCov\left(X\right)^{-1}x_0\right] + \sigma^2 \\ +&= \sigma^2/N \cdot E_{x_0}\left[trace\left(x_0^TCov\left(X\right)^{-1}x_0\right)\right] + \sigma^2 \\ +&= \sigma^2/N \cdot E_{x_0}\left[trace\left(x_0x_0^TCov\left(X\right)^{-1}\right)\right] + \sigma^2 \\ +&= \sigma^2/N \cdot trace\left[E_{x_0}\left(x_0x_0^TCov\left(X\right)^{-1}\right)\right] + \sigma^2 \\ +&= \sigma^2/N \cdot trace\left[E_{x_0}\left(x_0x_0^T\right)Cov\left(X\right)^{-1}\right] + \sigma^2 \\ +&= \sigma^2/N \cdot trace\left[Cov\left(X\right)Cov\left(X\right)^{-1}\right] + \sigma^2 \\ +&= \sigma^2/N \cdot trace I_p + \sigma^2 \\ +&= \sigma^2\left(p/N\right) + \sigma^2 \\ +\end{align} +$$ + +--- + +## Ex. 2.6 weighted-least-squares-problem + +Item | Description +--- | --- +Authors | [xdwangkai](https://github.com/xdwangkai) +Date | 2015/9/9 +Reference | [Researchgate: A Solution Manual and Notes for: The Elements of Statistical Learning](http://www.researchgate.net/publication/237116664_A_Solution_Manual_and_Notes_for_the_Text_The_Elements_of_Statistical_Learning) + +**Ex. 2.6** Consider a regression problem with inputs $x_i$ and outputs $y_i$, and a parameterized model $f_\theta{\left(x\right)}$ to be fit by least squares. Show that if there are observations with _tied_ or _identical_ values of $x$, then the fit can be obtained from a reduced weighted least squares problem. + +**Proof** + +To fit the model $f_\theta{\left(x\right)}$ by least squares, we minimize +$$ +\begin{equation} +RSS\left(\theta\right)=\sum_{k=1}^N\left(y_k-f_\theta\left(x_k\right)\right)^2 +\label{eq1} +\end{equation} +$$ +as a function of $\theta$. + +As _reducible error_ and _irreducible error_ exist, even the _same_ input value of $x$ generate _different_ outputs value of $y$. Denote by $N_u$ the number of _unique_ inputs $x$, and assume that the $i$th $x$ will give $n_i$ different $y$, denote by $y_{ij}$, $1\le j\le n_i$. Rewrite Eq. $\eqref{eq1}$ as +$$ +\begin{equation} +RSS\left(\theta\right)=\sum_{i=1}^{N_u}\sum_{j=1}^{n_i}\left(y_{ij}-f_\theta\left(x_i\right)\right)^2. +\label{eq2} +\end{equation} +$$ + +By expanding the quadratic in Eq. $\eqref{eq2}$, we have +$$ +\begin{align} +RSS\left(\theta\right)&= \sum_{i=1}^{N_u}\sum_{j=1}^{n_i}\left(y_{ij}^2-2f_\theta\left(x_i\right)y_{ij}+f_\theta\left(x_i\right)^2\right) \\ +&= \sum_{i=1}^{N_u}n_i\left(\frac{1}{n_i}\sum_{j=1}^{n_i}y_{ij}^2-2f_\theta\left(x_i\right)\left(\frac{1}{n_i}\sum_{j=1}^{n_i}y_{ij}\right)+f_\theta\left(x_i\right)^2\right) +\label{eq3} +\end{align} +$$ + +Now we get the _weighted_ item $n_i$. Next, we will rewrite the expressions in the bracket to be consistent with Eq. $\eqref{eq1}$. + +In Eq. $\eqref{eq3}$ we notice the term $\frac{1}{n_i}\sum_{j=1}^{n_i}y_{ij}$, which means the average of all responses $y$ resulting from the same input $x_i$. To be briefly expressed, we define $\bar{y}_i=\frac{1}{n_i}\sum_{j=1}^{n_i}y_{ij}$ and rewrite Eq. $\eqref{eq3}$ as +$$ +\begin{align} +RSS\left(\theta\right)&= \sum_{i=1}^{N_u}n_i\left(\frac{1}{n_i}\sum_{j=1}^{n_i}y_{ij}^2-2f_\theta\left(x_i\right)\bar{y}_i+f_\theta\left(x_i\right)^2\right) \\ +&= \sum_{i=1}^{N_u}n_i\left(\bar{y}_i^2-2f_\theta\left(x_i\right)\bar{y}_i+f_\theta\left(x_i\right)^2\right)+\sum_{i=1}^{N_u}\sum_{j=1}^{n_i}y_{ij}^2-\sum_{i=1}^{N_u}{n_i\bar{y}_i^2} \\ +&= \sum_{i=1}^{N_u}n_i\left(\bar{y}_i-f_\theta\left(x_i\right)\right)^2+\sum_{i=1}^{N_u}\sum_{j=1}^{n_i}y_{ij}^2-\sum_{i=1}^{N_u}{n_i\bar{y}_i^2} +\label{eq4} +\end{align} +$$ + +Once we get the measurements, i.e., the inputs $x_i$ and outputs $y_i$, the expression $\sum_{i=1}^{N_u}\sum_{j=1}^{n_i}y_{ij}^2-\sum_{i=1}^{N_u}{n_i\bar{y}_i^2}$ in Eq. $\eqref{eq4}$ won't change. Thus minimizing Eq. $\eqref{eq1}$ with respect to $\theta$ is equivalent to minimizing: +$$ +\begin{equation} +RSS\left(\theta\right)=\sum_{i=1}^{N_u}n_i\left(\bar{y}_i-f_\theta\left(x_i\right)\right)^2 +\end{equation} +\label{eq5} +$$ + +Now we compare Eq. $\eqref{eq5}$ with Eq. $\eqref{eq1}$: + +1. The number of items in Eq. $\eqref{eq5}$ is $N_u$, which is less than the number of inputs value $N$ in Eq. $\eqref{eq1}$. So this problem can be regarded as a _reduced_ one. + +2. Each residual error is weighted by $n_i$ in Eq. $\eqref{eq5}$, so this is a _weighted_ least squares problem. + +Therefore, the fit of parameterized model $f_\theta\left(x\right)$ can be obtained from a reduced weighted least squares problem. + +--- + +## Ex. 2.7 conditional-unconditional-bias-variance + +Item | Description +--- | --- +Authors | [squall1988](https://github.com/squall1988), [PengjuYan](https://github.com/PengjuYan) +Date | 2015/10/28 + +**Ex. 2.7 ** Suppose we have a sample of $N$ pairs $x_i$, $y_i$ drawn i.i.d. from the distribution characterized as follows: + +$x_i \sim h\left(x\right)$, the design density + +$y_i = f\left(x_i\right) + \epsilon_i$, $f$ is the regression function + +$\epsilon_i \sim \left(0, \sigma^2\right)$ (mean zero, variance $\sigma_2$) + +We construct an estimator for $f$ linear in the $y_i$, + +$$ +\begin{equation} +\hat{f}\left(x_0\right) = \sum_{i=1}^{N} \mathcal{l}_i\left(x_0; \mathcal{X}\right)y_i +\end{equation} +$$ + +where the weights $\mathcal{l}_i\left(x_0; \mathcal{X}\right)$ do not depend on the $y_i$, but do depend on the entire training sequence of $x_i$, denoted here by $\mathcal{X}$. + +\(a) Show that linear regression and $k$-nearest-neighbor regression are members of this class of estimators. Describe explicitly the weights $\mathcal{l}_i\left(x_0; \mathcal{X}\right)$ in each of these cases. + +\(b) Decompose the conditional mean-squared error + +$$ +\begin{align} +\label{eq:ex-2.7-conditional-mse} +E_{\mathcal{Y}|\mathcal{X}} \left(f\left(x_0\right) − \hat{f}\left(x_0\right)\right)^2 +\end{align} +$$ + +into a conditional squared bias and a conditional variance component. Like $\mathcal{X}$, $\mathcal{Y}$ represents the entire training sequence of $y_i$. + +\(c) Decompose the (unconditional) mean-squared error + +$$ +\begin{align} +\label{eq:ex-2.7-unconditional-mse} +E_{\mathcal{Y},\mathcal{X}} \left(f\left(x_0\right) − \hat{f}\left(x_0\right)\right)^2 +\end{align} +$$ + +into a squared bias and a variance component. + +\(d) Establish a relationship between the squared biases and variances in the above two cases. + +**Proof (a)** + +When we use least square method to estimate the relationship between the $X$ and $Y$ + +$$ +\begin{equation} +\hat \beta = \left(\textbf{X}^T\textbf{X}\right)^{-1}\textbf{X}^T\textbf{Y} +\end{equation} +$$ + +and the $\hat{f}\left(x_0\right)$ can be written as below: + +$$ +\begin{align} +\hat{f}\left(x_0\right) &= x_0^T \hat \beta \\ +& = x_0^T \left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T\mathbf{Y} +\end{align} +$$ + +so the $\mathcal{l}\left(x_0; \mathcal{X}\right)$ is the $i$th element of the $x_0^T\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T$. + +When we use $k$-nearest-neighbor to estimate the relationship between $\mathbf{X}$ and $\mathbf{Y}$, the $\mathcal{l}\left(x_0; \mathcal{X}\right)$ can be written as below: + +$$ +\begin{align} +\mathcal{l}\left(x_0; \mathcal{X}\right) = \frac{1}{k}\sum_{i=1}^{N} I\left(x_0,k;x_i\right)y_i +\end{align} +$$ + +where $I\left(x_0,k; x_i\right)$ is an indicator function which is used to indicate if $x_i$ is one of the $k$-nearest-neighbor of $x_0$. + +**Proof (b)** + +Similar to what we have proven in $\eqref{eq:ex-2.5-epe-expection}$, equation $\eqref{eq:ex-2.7-conditional-mse}$ can be reshaped as below: + +$$ +\begin{align} +\label{eq:ex-2.7-conditional-mse-decomposed} +E_{\mathcal{Y}|\mathcal{X}}\left (f \left(x_0\right) - \hat{f}\left(x_0\right)\right)^2 +& = \left(f\left(x_0\right) - E_{\mathcal{Y}|\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)\right)^2 + \left(E_{\mathcal{Y}|\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)^2 - {E_{\mathcal{Y}|\mathcal{X}}}^2\left(\hat{f}\left(x_0\right)\right)\right) \\ +&= {Bias_{\mathcal{Y}|\mathcal{X}}}^2\left(f\left(x_0\right)\right)+ Var_{\mathcal{Y}|\mathcal{X}}\left(\hat{f}\left(x_0\right)\right) +\end{align} +$$ + +**Proof (c)** + +Similar to what we have proven in $\eqref{eq:ex-2.5-epe-expection}$, equation $\eqref{eq:ex-2.7-unconditional-mse}$ can be reshaped as below: + +$$ +\begin{align} +\label{eq:ex-2.7-unconditional-mse-decomposed} +E_{\mathcal{Y},\mathcal{X}}\left(f\left(x_0\right) - \hat{f}\left(x_0\right)\right)^2 +& = \left(f\left(x_0\right) - E_{\mathcal{Y},\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)\right)^2 + \left(E_{\mathcal{Y},\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)^2 - {E_{\mathcal{Y},\mathcal{X}}}^2\left(\hat{f}\left(x_0\right)\right)\right) \\ +&= {Bias_{\mathcal{Y},\mathcal{X}}}^2\left(f\left(x_0\right)\right)+ Var_{\mathcal{Y},\mathcal{X}}\left(\hat{f}\left(x_0\right)\right) +\end{align} +$$ + +**Proof (d)** + +Let's calculate the expectation of the squared bias and variance of $\eqref{eq:ex-2.7-conditional-mse-decomposed}$ on $\mathcal{X}$ and then compare them against the counterparts of $\eqref{eq:ex-2.7-unconditional-mse-decomposed}$. + +$$ +\begin{align} +E_{\mathcal{X}} {Bias_{\mathcal{Y}|\mathcal{X}}}^2\left(f\left(x_0\right)\right) - {Bias_{\mathcal{Y},\mathcal{X}}}^2\left(f\left(x_0\right)\right) +&= E_{\mathcal{X}} \left(f\left(x_0\right) - E_{\mathcal{Y}|\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)\right)^2 - \left(f\left(x_0\right) - E_{\mathcal{Y},\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)\right)^2 \\ +&= \left[f\left(x_0\right)^2 - 2f\left(x_0\right)E_{\mathcal{X},\mathcal{Y}}\hat{f}\left(x_0\right) + E_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)^2\right] - \left[f\left(x_0\right)^2 - 2f\left(x_0\right)E_{\mathcal{X},\mathcal{Y}}\hat{f}\left(x_0\right) + \left(E_{\mathcal{X}}E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)^2\right] \\ +&= E_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)^2 - \left(E_{\mathcal{X}}E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)^2 \\ +&= Var_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right) +\end{align} +$$ + +$$ +\begin{align} +E_{\mathcal{X}} Var_{\mathcal{Y}|\mathcal{X}}\left(\hat{f}\left(x_0\right)\right) - Var_{\mathcal{Y},\mathcal{X}}\left(\hat{f}\left(x_0\right)\right) +&= E_{\mathcal{X}} \left(E_{\mathcal{Y}|\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)^2 - {E_{\mathcal{Y}|\mathcal{X}}}^2\left(\hat{f}\left(x_0\right)\right)\right) - \left(E_{\mathcal{Y},\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)^2 - {E_{\mathcal{Y},\mathcal{X}}}^2\left(\hat{f}\left(x_0\right)\right)\right) \\ +&= \left[E_{\mathcal{Y},\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)^2 - E_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)^2\right] - \left[E_{\mathcal{Y},\mathcal{X}}\left(\hat{f}\left(x_0\right)\right)^2 - \left(E_{\mathcal{X}}E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)^2\right]\\ +&= \left(E_{\mathcal{X}}E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)^2 - E_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)^2 \\ +&= -Var_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right) +\end{align} +$$ + +From the above, we can see that the order of calculation matters. If we calculate the conditional squared bias on fixed training input points then calculate the expectation of that by varying training input points, the expected conditional squared bias is **greater** than the unconditional squared bias by $Var_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)$. The same result applies to the variance, except that the expected conditional variance is **lesser** than the unconditional variance by $Var_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right)$. + +When the true relationship between input and response variables is linear, then the estimation $\hat{f}\left(x_0\right)$ is (both conditional and unconditional) unbiased, then $E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right) = 0$ and hence $Var_{\mathcal{X}}\left(E_{\mathcal{Y}|\mathcal{X}}\hat{f}\left(x_0\right)\right) = 0$. + +--- + +## Ex. 2.8 performance-of-lr-and-knn + +Item | Description +--- | --- +Authors | [Yang-Zhou](https://github.com/Yang-Zhou) +Date | 2015/9/17 + +**Ex. 2.8** +Compare the classification performance of linear regression and k–nearest neighbor classification on the zipcode data. In particular, consider only the $2$’s and $3$’s, and $k$ = $1$, $3$, $5$, $7$ and $15$. Show both the training and test error for each choice. The zipcode data are available from the book website http://www-stat.stanford.edu/ElemStatLearn. + +**Code** + +```{r, eval=FALSE} +# Load knn classifier +library(class) + +get.preprocessed <- function(url) { + # Get file + temp <- tempfile() + download.file(url, temp) + file <- read.table(temp, sep = ' ') + # filter the dependent variable y + file2 <- file[file[, 1] %in% c(2, 3), ] + # filter the independent variable X + file3 <- file2[, 1:257] +} + +lr.predict <- function(model, testset) { + predset <- predict(model, newdata = testset) + predset[predset >= 2.5] = 3 + predset[predset < 2.5] = 2 + accuracy <- sum(predset == testset[, 1]) / length(predset) +} + +knn.performance <- function(trainset, testset, k) { + knn.fit <- knn(trainset, testset, cl=trainset[, 1], k=k, prob=F) + accuracy <- sum(knn.fit == testset[, 1]) / length(knn.fit) +} + +# Url of trainset and testset +train.url <- paste('http://statweb.stanford.edu/~tibs/', + 'ElemStatLearn/datasets/zip.train.gz', sep='') +test.url <- paste('http://statweb.stanford.edu/~tibs/', + 'ElemStatLearn/datasets/zip.test.gz', sep='') + +# Get proprocessed trainset and testset +trainset <- get.preprocessed(train.url) +testset <- get.preprocessed(test.url) + +# Performance of Linear Regression +lm.fit <- lm(V1 ~ ., data = trainset) +accuracy.train <- lr.predict(lm.fit, trainset) +accuracy.test <- lr.predict(lm.fit, testset) +sprintf(paste('The accuracy of LR\'s train accuracy is %.3f,', + 'test acccuracy is %.3f'), accuracy.train, accuracy.test) + +# Performance of Knn with K = 1, 3, 5, 7, 15 +for (i in c(1, 3, 5, 7, 15)) { + accuracy.train <- knn.performance(trainset, trainset, i) + accuracy.test <- knn.performance(trainset, testset, i) + accuracy.str <- sprintf(paste('The accuracy of %2d-nn\'s train', + 'accuracy is %.3f, test acccuracy is %.3f'), + i, accuracy.train, accuracy.test) + print(accuracy.str) +} +``` + +The results are: + +``` +The accuracy of LR's train accuracy is 0.994, test acccuracy is 0.959 +The accuracy of 1-nn's train accuracy is 1.000, test acccuracy is 0.975 +The accuracy of 3-nn's train accuracy is 0.996, test acccuracy is 0.970 +The accuracy of 5-nn's train accuracy is 0.994, test acccuracy is 0.970 +The accuracy of 7-nn's train accuracy is 0.994, test acccuracy is 0.970 +The accuracy of 15-nn's train accuracy is 0.991, test acccuracy is 0.962 +``` + +--- + +## Ex. 2.9 error-low-on-train + +Item | Description +--- | --- +Authors | [PengjuYan](https://github.com/PengjuYan) +Date | 2015/10/22 +Reference | [Wikipedia: Idempotent matrix][wikipedia-idempotent-matrix], [Wikipedia: Positive-definite matrix][wikipedia-positive-definite-matrix] + +[wikipedia-idempotent-matrix]:https://en.wikipedia.org/wiki/Idempotent_matrix +[wikipedia-positive-definite-matrix]:https://en.wikipedia.org/wiki/Positive-definite_matrix + +**Ex. 2.9** Consider a linear regression model with $p$ parameters, fit by least squares to a set of training data $\left(x_1, y_1\right)$, ..., $\left(x_N, y_N\right)$ drawn at random from a population. Let $\hat{\beta}$ be the least squares estimate. Suppose we have some test data $\left(\tilde{x}_1, \tilde{y}_1\right)$, ..., $\left(\tilde{x}_M, \tilde{y}_M\right)$ drawn at random from the same population as the training data. If $R_{tr}\left(\beta\right) = \frac{1}{N}\sum_1^N\left(y_i-\beta^Tx_i\right)^2$ and $R_{te}\left(\beta\right) = \frac{1}{M}\sum_1^M\left(\tilde{y}_i-\beta^T\tilde{x}_i\right)^2$, prove that + +$$ +\begin{equation} +E\left[R_{tr}\left(\hat{\beta}\right)\right] \le E\left[R_{te}\left(\hat{\beta}\right)\right], +\end{equation} +$$ + +where the expectations are over all that is random in each expression. [This exercise was brought to our attention by Ryan Tibshirani, from a homework assignment given by Andrew Ng.] + +**Proof** + +Note that our proof below is based on the strong assumption that the ralationship between $Y$ and $X$ is linear, i.e., equation (2.26) holds: + +$$ +\begin{equation} +Y = X^T\beta + \epsilon, +\end{equation} +$$ + +and the random error $\epsilon$ has $E\left(\epsilon\right) = 0$ and is independent of $X$. + +Let's simplify the training RSS first. + +$$ +\begin{align} +RSS\left(\hat{\beta}\right) +&= \left(\mathbf{y} - \hat{\mathbf{y}}\right)^T \left(\mathbf{y} - \hat{\mathbf{y}}\right) \\ +&= \left(\mathbf{X}\beta + \mathbf{\epsilon} - \mathbf{X}\hat{\beta}\right)^T \left(\mathbf{y} - \hat{\mathbf{y}}\right) \\ +&= \left(\mathbf{X}\beta + \mathbf{\epsilon} - \mathbf{X}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T \left(\mathbf{X}\beta + \mathbf{\epsilon}\right)\right)^T \left(\mathbf{y} - \hat{\mathbf{y}}\right) \\ +&= \left(\mathbf{X}\beta + \mathbf{\epsilon} - \mathbf{X}\beta - H\mathbf{\epsilon}\right)^T \left(\mathbf{y} - \hat{\mathbf{y}}\right) \\ +&= \left(\mathbf{\epsilon} - H\mathbf{\epsilon}\right)^T \left(\mathbf{y} - \hat{\mathbf{y}}\right) \\ +&= \left(\mathbf{\epsilon} - H\mathbf{\epsilon}\right)^T \left(\mathbf{\epsilon} - H\mathbf{\epsilon}\right) \\ +&= \mathbf{\epsilon}^T\mathbf{\epsilon} - 2\mathbf{\epsilon}^TH\mathbf{\epsilon} + \mathbf{\epsilon}^TH^TH\mathbf{\epsilon} \\ +&= \mathbf{\epsilon}^T\mathbf{\epsilon} - 2\mathbf{\epsilon}^TH\mathbf{\epsilon} + \mathbf{\epsilon}^TH\mathbf{\epsilon} \\ +&= \mathbf{\epsilon}^T\mathbf{\epsilon} - \mathbf{\epsilon}^TH\mathbf{\epsilon} +\end{align} +$$ + +In the derivation above, we use the following compact notations: the training data is represented by the $N \times \left(p+1\right)$ matrix $\mathbf{X}$, the true responses by $\mathbf{y} = \left(y_1, y_2, \dots, y_N\right)^T$, and the noises by $\mathbf{\epsilon} = \left(\epsilon_1, \epsilon_2, \dots, \epsilon_N\right)^T$. + +On page 46 the _hat_ matrix $H$ is defined as $H = \mathbf{X}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T$. It is easy to show that $H$ is: + +1. symmetric: $H^T = H$; +1. [idempotent][wikipedia-idempotent-matrix]: $HH = H$; and +1. [positive semi-definite][wikipedia-positive-definite-matrix]: $z^THz = z^TH^THz = \left(Hz\right)^T\left(Hz\right) \ge 0$. + +Then the expected training error is: + +$$ +\begin{align} +E\left[R_{tr}\left(\hat{\beta}\right)\right] +&= \frac{1}{N} E\left[RSS\left(\hat{\beta}\right)\right] \\ +&= \frac{1}{N} E\left[\mathbf{\epsilon}^T\mathbf{\epsilon} - \mathbf{\epsilon}^TH\mathbf{\epsilon}\right] \\ +&= \frac{1}{N} \left\{E\left[\mathbf{\epsilon}^T\mathbf{\epsilon}\right] - E\left[\mathbf{\epsilon}^TH\mathbf{\epsilon}\right]\right\} \\ +&= \frac{1}{N} \left\{N\sigma^2 - E\left[\mathbf{\epsilon}^TH\mathbf{\epsilon}\right]\right\} \\ +&\le \frac{1}{N} \left\{N\sigma^2 - 0\right\} \\ +&= \sigma^2, +\end{align} +$$ + +where the last inequality holds because $H$ is positive semi-definite. + +Then we look at the testing RSS: + +$$ +\begin{align} +\widetilde{RSS}\left(\hat{\beta}\right) +&= \left(\tilde{\mathbf{y}} - \hat{\tilde{\mathbf{y}}}\right)^T \left(\tilde{\mathbf{y}} - \hat{\tilde{\mathbf{y}}}\right) \\ +&= \left(\tilde{\mathbf{X}}\beta + \tilde{\mathbf{\epsilon}} - \tilde{\mathbf{X}}\hat{\beta}\right)^T \left(\tilde{\mathbf{y}} - \hat{\tilde{\mathbf{y}}}\right) \\ +&= \left(\tilde{\mathbf{X}}\beta + \tilde{\mathbf{\epsilon}} - \tilde{\mathbf{X}}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T \left(\mathbf{X}\beta + \mathbf{\epsilon}\right)\right)^T \left(\tilde{\mathbf{y}} - \hat{\tilde{\mathbf{y}}}\right) \\ +&= \left(\tilde{\mathbf{X}}\beta + \tilde{\mathbf{\epsilon}} - \tilde{\mathbf{X}}\beta - \tilde{\mathbf{X}}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T \mathbf{\epsilon}\right)^T \left(\tilde{\mathbf{y}} - \hat{\tilde{\mathbf{y}}}\right) \\ +&= \left(\tilde{\mathbf{\epsilon}} - \tilde{\mathbf{X}}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T \mathbf{\epsilon}\right)^T \left(\tilde{\mathbf{y}} - \hat{\tilde{\mathbf{y}}}\right) \\ +&= \left(\tilde{\mathbf{\epsilon}} - \tilde{H}\mathbf{\epsilon}\right)^T \left(\tilde{\mathbf{y}} - \hat{\tilde{\mathbf{y}}}\right) \\ +&= \left(\tilde{\mathbf{\epsilon}} - \tilde{H}\mathbf{\epsilon}\right)^T \left(\tilde{\mathbf{\epsilon}} - \tilde{H}\mathbf{\epsilon}\right) \\ +&= \tilde{\mathbf{\epsilon}}^T\tilde{\mathbf{\epsilon}} - 2\tilde{\mathbf{\epsilon}}^T\tilde{H}\mathbf{\epsilon} + \mathbf{\epsilon}^T\tilde{H}^T\tilde{H}\mathbf{\epsilon} +\end{align} +$$ + +where $\tilde{H} = \tilde{\mathbf{X}}\left(\mathbf{X}^T\mathbf{X}\right)^{-1}\mathbf{X}^T$. + +Then we get the expected testing error as follows: + +$$ +\begin{align} +E\left[R_{te}\left(\hat{\beta}\right)\right] +&= \frac{1}{M} E\left[\widetilde{RSS}\left(\hat{\beta}\right)\right] \\ +&= \frac{1}{M} E\left[\tilde{\mathbf{\epsilon}}^T\tilde{\mathbf{\epsilon}} - 2\tilde{\mathbf{\epsilon}}^T\tilde{H}\mathbf{\epsilon} + \mathbf{\epsilon}^T\tilde{H}^T\tilde{H}\mathbf{\epsilon}\right] \\ +&= \frac{1}{M} \left\{E\left[\tilde{\mathbf{\epsilon}}^T\tilde{\mathbf{\epsilon}}\right] - 2E\left[\tilde{\mathbf{\epsilon}}^T\tilde{H}\mathbf{\epsilon}\right] + E\left[\mathbf{\epsilon}^T\tilde{H}^T\tilde{H}\mathbf{\epsilon}\right]\right\} \\ +&= \frac{1}{M} \left\{M\sigma^2 - 2E\left[\tilde{\mathbf{\epsilon}}^T\tilde{H}\mathbf{\epsilon}\right] + E\left[\mathbf{\epsilon}^T\tilde{H}^T\tilde{H}\mathbf{\epsilon}\right]\right\} \\ +\label{eq:ex-2.9-independence} +&= \frac{1}{M} \left\{M\sigma^2 - 0 + E\left[\mathbf{\epsilon}^T\tilde{H}^T\tilde{H}\mathbf{\epsilon}\right]\right\} \\ +&\ge \frac{1}{M} \left\{M\sigma^2 - 0 + 0\right\} \\ +&= \sigma^2, +\end{align} +$$ + +where $\eqref{eq:ex-2.9-independence}$ holds because $\mathbf{X}$, $\mathbf{\epsilon}$, $\tilde{\mathbf{X}}$ and $\tilde{\mathbf{\epsilon}}$ are independent of each other, and last inequality holds because $\mathbf{\epsilon}^T\tilde{H}^T\tilde{H}\mathbf{\epsilon} = \left(\tilde{H}\mathbf{\epsilon}\right)^T\left(\tilde{H}\mathbf{\epsilon}\right) \ge 0$. + +Finally we proved the result. diff --git a/markup/math/component_implementing_streaming_2ffd4c.adoc b/markup/math/component_implementing_streaming_2ffd4c.adoc new file mode 100644 index 0000000..a33d21a --- /dev/null +++ b/markup/math/component_implementing_streaming_2ffd4c.adoc @@ -0,0 +1,180 @@ += Implementing streaming on a component +:page-partial: +:stem: +:description: How to make your input component ready for a continuous flow of data. +:keywords: stream, infinite, partition mapper, input + +By default, input components are designed to receive a one-time batch of data to process. By enabling the streaming mode, you can instead set your component to process a continuous incoming flow of data. + +When streaming is enabled on an input component, the component tries to pull data from its producer. When no data is pulled, it waits for a defined period of time before trying to pull data again, and so on. This period of time between tries is defined by a strategy. + +This document explains how to configure this strategy and the cases where it can fit your needs. + +== Choosing between batch and streaming + +Before enabling streaming on your component, make sure that it fits the scope and requirements of your project and that regular batch processing cannot be used instead. + +Streaming is designed to help you dealing with real-time or near real-time data processing cases, and should be used only for such cases. +Enabling streaming will impact the performance when processing batches of data. + +== Enabling streaming from the Component Kit starter + +You can enable streaming right from the design phase of the project by enabling the *Stream* toggle in the basic configuration of your future component in the Component Kit Starter. + +Doing so adds a default streaming-ready configuration to your component when generating the project. + +This default configuration implements a constant pause duration of 500 ms between retries, with no limit of retries. + +image::starter/starter_enabling_streaming.png[Stream Toggle,window="_blank",link=self,80%] + +== Enabling limitations (stop conditions) for Streaming components +Without any configuration, streaming components have an infinite lifecycle and will never stop. +Sometimes, you may need to stop component after a certain amount of records read or time elapsed. + +You can add configuration that helps you to stop the data reading in your input component when it reaches required limitations. To enable it you need to set `true` in `PartitionMapper#stoppable`. An important condition is that `PartitionMapper#infinite` should also be `true`. + +Here's a sample code: + +[source,java,indent=0] +---- +@PartitionMapper(name = "Input", + infinite = true, <1> + stoppable = true) <2> +public class YourPartitionMapper { + ... +} +---- + +<1> Define your component as a streaming component. +<2> Define that your component may be stopped under conditions. + + +There are two reading stop conditions (can be combined): + +- `maxDurationMs` : stop after _n_ milliseconds elapsed. +- `maxRecords` : stop after _n_ records read. + +See next subsections for configuring those values. + + +WARNING: If you choose to use a `stoppable` streaming component, you will have certainly to adapt your code according the backend technology and how to read values. For instance, if in your component you read 100 values at once and the `maxRecords` value is 50, you may lose 50 values (if the 100 values were acknowledged). + +In that case, to build a correct strategy in your component, you can access to stop condition values. +To access these informations use the `@PostConstruct` method with `@Option` annotation in your Emitter class. + +Available options: + +- `Option.MAX_DURATION_PARAMETER` : reflects the `maxDurationMs` parameter. +- `Option.MAX_RECORDS_PARAMETER` : reflects the `maxRecords` parameter. + +Here a code sample: + +[source,java,indent=0] +---- +@Version +@PartitionMapper(name = "Input", infinite = true, stoppable = true) +public class YourPartitionMapper { + // partition mapper code + + @Emitter + public YourEmitter createWorker() { + return new YourEmitter(configuration); + } +} + +public class YourEmitter { + + @PostConstruct + public void init(@Option(Option.MAX_DURATION_PARAMETER) long maxDurationMs, @Option(Option.MAX_RECORDS_PARAMETER) long maxRecords ) { + // connector's specific logic here + } + // other component's code +} +---- + +=== Configuring streaming stop strategy during job design time + +If your streaming connector (`infinite=true`) is defined with the `stoppable=true`, you will have a design time UI for specifying stop strategy: + +- Cloud + +image:streaming-limits-ui-cloud.png[Stream Toggle,window="_blank",link=self,80%] + +- Studio + +image:streaming-limits-ui-studio.png[Stream Toggle,window="_blank",link=self,80%] + + +By default, in the setting those values are set to *-1*. It means _infinity_ behavior. + + +=== Other ways for configuring streaming stop strategy + +At runtime, you can set system properties to apply the strategy. You need to prefix properties with the component's family. + +- `.talend.input.streaming.maxRecords` +- `.talend.input.streaming.maxDurationMs` + +You can also use the xref:services-built-in.adoc#_localconfiguration[LocalConfiguration] (see next section) with the following properties: + +- `talend.input.streaming.maxRecords` +- `talend.input.streaming.maxDurationMs` + + +== Configuring streaming from the project + +If streaming was not enabled at all during the project generation or if you need to implement a more specific configuration, you can change the default settings according to your needs: + +. Add the `infinite=true` parameter to your component class. +. Define the number of retries allowed in the component family xref:services-built-in.adoc#_localconfiguration[LocalConfiguration], using the `talend.input.streaming.retry.maxRetries` parameter. It is set by default to `Integer.MAX_VALUE`. +. Define the pausing strategy between retries in the component family `LocalConfiguration`, using the `talend.input.streaming.retry.strategy` parameter. Possible values are: +** `constant` (default). It sets a constant pause duration between retries. +** `exponential`. It sets an exponential backoff pause duration. + ++ +NOTE: See the tables below for more details about each strategy. + +=== Constant strategy + +[options="header, autowidth",role="table-striped table-hover table-ordered",width="100%",cols="1,2,1"] +|=== +|Parameter|Description|Default value +|`talend.input.streaming.retry.constant.timeout`|Pause duration for the `constant` strategy, in ms.|`500` +|=== + +=== Exponential strategy + +[options="header, autowidth",role="table-striped table-hover table-ordered",width="100%",cols="1,2,1"] +|==== +|Parameter|Description|Default value +|`talend.input.streaming.retry.exponential.exponent`|Exponent of the exponential calculation.|`1.5` +|`talend.input.streaming.retry.exponential.randomizationFactor`|Randomization factor used in the calculation.|`0.5` +|`talend.input.streaming.retry.exponential.maxDuration`|Maximum pausing duration between two retries.|`5*60*1000` (5 minutes) +|`talend.input.streaming.retry.exponential.initialBackOff`|Initial backoff value.|`1000` (1 second) +|==== + +The values of these parameters are then used in the following calculations to determine the exact pausing duration between two retries. + +NOTE: For more clarity in the formulas below, parameter names have been replaced with variables. + +First, the current interval duration is calculated: + +asciimath:[A = min(B xx E^I, F)] + +Where: + +* A: currentIntervalMillis +* B: initialBackOff +* E: exponent +* I: current number of retries +* F: maxDuration + +Then, from the current interval duration, the next interval duration is calculated: + +asciimath:[D = min(F, A + ((R xx 2-1) xx C xx A))] + +Where: + +* D: nextBackoffMillis +* F: maxDuration +* A: currentIntervalMillis +* R: random +* C: randomizationFactor diff --git a/markup/math/formula_0225f1.fodp b/markup/math/formula_0225f1.fodp new file mode 100644 index 0000000..67ae72f --- /dev/null +++ b/markup/math/formula_0225f1.fodp @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + e + + i + π + + + + + 1 + + = + 0 + + {func e}^{i %pi} + 1 = 0 + + + + + + + + \ No newline at end of file diff --git a/markup/math/from_7b6cac.adoc b/markup/math/from_7b6cac.adoc new file mode 100644 index 0000000..46ee963 --- /dev/null +++ b/markup/math/from_7b6cac.adoc @@ -0,0 +1,682 @@ +[[sec:from]] +== `FROM` Clause Semantics + +The formal semantics of a `FROM` clause describe the collection of +binding tuples stem:[B_"FROM"^"out"] that is output by the `FROM` +clause. The semantics specify three cases and essentially extend the +tuple calculus that underlies the SQL semantics. + +1. The semantics specify what is the core semantics of a clause with a +single item (<> and <>). The term +"`semantics of the item stem:[f]`" is synonymous to the term +"`semantics of a clause with the single item stem:[f]`". In either +case, we refer to the specification of the collection of binding +tuples stem:[B^{out}_{\from}] that results from the evaluation of +"`stem:[f]`". + +2. Then the semantics specify how multiple items combine, according to +the core semantics, using the join and outerjoin operations +(<>, +<> and +<>). + +3. Finally, the semantics specify the syntactic sugar structures that are +overlaid over the core semantics. Their primary purpose is SQL +compatibility. + +[[sec:single-item-from]] +=== Ranging Over Bags and Arrays + +Next we define the semantics of a `FROM` clause that has a single +`FROM` item and such item ranges over a bag or array. First consider +the `FROM` clause: + + +[source%unbreakable, partiql] +---- +FROM a AS v AT p +---- + +Let us call stem:[v] to be the _element variable_ and stem:[p] to be +the _position variable_. In the normal case, stem:[a] is an array +stem:[ \[ e_0, ..., e_{n-1} \] ]. The `FROM` clause outputs a bag of +binding tuples. For each stem:[e_i], the bag has a binding tuple +stem:[< < v: e_i, p:i > >]. + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[#xmpl:single-from-item-with-order%unbreakable] +[subs="+normal"] +==== +Consider the following stem:[p_0] (database environment): + +stem:[ p_0 = << ] + +stem:[ "someOrderedTable" : \[ ] + +stem:[ {'a':0, 'b':0}, ] + +stem:[ {'a':1, 'b':1} ] + +stem:[ \] ] + +stem:[ >> ] + +then the following `FROM` clause: + +[source%unbreakable, partiql] +---- +FROM someOrderedTable AS x AT y +---- + +outputs the bag of binding tuples: + +stem:[B_"FROM"^"out" =] stem:[< <] + +stem:[" " << x: {'a':0, 'b':0}, y:0 >> ] + +stem:[" " << x: {'a':1, 'b':1}, y:1 >> ] + +stem:[ > > ] +==== + + + +As in SQL, the `AS` keyword is optional. The same applies to all cases below +where `AS` appears. If there is no `AT` clause, then the binding tuples have only +the element variable. In particular, consider: + +[source%unbreakable, partiql] +---- +FROM a AS v +---- + +Normally stem:[a] is a collection, i.e, an array stem:[ +\[e_0,...,e_{n-1}\] ] or a bag stem:[ < < e_0,...,e_{n-1} > > ]. In +either case, the `FROM` clause outputs a bag. For each stem:[e_i], the bag +has a binding tuple stem:[ << v:e_i >> ]. + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== + +Consider again the database of <> +and then the `FROM` clause + +[source%unbreakable, partiql] +---- +FROM someOrderedTable AS x +---- + +this clause outputs: + +stem:[B_"FROM"^"out" =] stem:[< <] + +stem:[" " << x: {'a':0, 'b':0} >> ] + +stem:[" " << x: {'a':1, 'b':1} >> ] + +stem:[ > > ] +==== + + + + +[[sec:bag-array-mistypings]] +==== Mistyping Cases + +In the following cases the expression in the `FROM` clause item has the wrong +type. Under the type checking option, all of these cases raise an error +and the query fails. Under the permissive option, the cases proceed as +follows + + + +Position variable on bags:: Consider the clause: ++ +[source%unbreakable, partiql] +---- +FROM b AS v AT p +---- ++ +and assume that stem:[b] is a bag stem:[< < e_0, ..., e_{n-1} > > +]. The output is a bag with binding tuples stem:[<< v: e_i, p: +"MISSING" >>]. The value `MISSING` for the variable stem:[p] indicates +that the order of elements in the bag was meaningless. + + + +Iteration over a scalar value:: Consider the query: ++ +[source%unbreakable, partiql] +---- +FROM s AS v AT p +---- ++ +or the query: ++ +[source%unbreakable, partiql] +---- +FROM s AS v +---- ++ +where stem:[s] is a scalar value. Then stem:[s] coerces into the bag +stem:[< < s > >], i.e., the bag that has a single element, the +stem:[s]. The rest of the semantics is identical to what happens when +the lhs of the `FROM` item is a bag. + + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== + +Consider again the database of <> +and the `FROM` clause: + +[source%unbreakable, partiql] +---- +FROM someOrderedTable[0].a AS x +---- + +The expression `someOrderedTable[0].a` evaluates to `0` and, +consequently, the `FROM` clause outputs a single binding tuple: + +stem:[B_"FROM"^"out" =] stem:[< <] stem:[ << x: 0 >> ] stem:[ > > ] +==== + + + + +Iteration over a tuple value:: Consider the query: ++ +[source%unbreakable, partiql] +---- +FROM t AS v AT p +---- ++ +or the query: ++ +[source%unbreakable, partiql] +---- +FROM t AS v +---- ++ +where stem:[t] is a tuple. Then stem:[t] coerces into the +bag stem:[< < t > >] + + + +Iteration over an absent value:: Consider the query ++ +[source%unbreakable, partiql] +---- +FROM a AS v AT p +---- ++ +or the query ++ +[source%unbreakable, partiql] +---- +FROM a AS v +---- ++ +whereas stem:[a] evaluates into an _absent value_ (i.e., either +`MISSING` or `NULL`). In either case the _absent value_ stem:[a] +coerces into the bag stem:[< < a > >]. Then the semantics follow the +normal case. + + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== +Consider again the database of <> +and the clause + +[source%unbreakable, partiql] +---- +FROM someOrderedTable[0].c AS x +---- + +The expression `someOrderedTable[0].c` evaluates to `MISSING` and, +consequently, the `FROM` clause outputs the binding tuple: + +stem:[B_"FROM"^"out" =] stem:[< <] stem:[ << x: "MISSING" >> ] stem:[ > > ] +==== + + + + +[[sec:unpivot]] +=== Ranging over Attribute-Value Pairs + +The `UNPIVOT` clause enables ranging over the attribute-value pairs of a tuple. +The `FROM` clause + +[source%unbreakable, partiql] +---- +FROM UNPIVOT t AS v AT a +---- + +normally expects stem:[t] to be a tuple, with attribute/value pairs +stem:[ a_1:v_1, ..., a_n,v_n ]. It does not matter whether the tuple +is ordered or unordered. The `FROM` clause outputs the collection of binding +tuples + +stem:[B_"FROM"^"out" = < < <> ... <> > >] + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== +Consider the stem:[p_0]: + +stem:[p_0 = << "justATuple" : {'amzn': 840.05, 'tdc': 31.06} >>] + +The clause: + +[source%unbreakable, partiql] +---- +FROM UNPIVOT justATuple AS price AT symbol +---- + +outputs: + +stem:[B_"FROM"^"out" =] stem:[< <] + +stem:[ << price: 840.05, symbol: 'amzn' >> ] + +stem:[ << price: 31.06, symbol: 'tdc' >> ] + +stem:[ > > ] +==== + +[[sec:unpivot-mistypings]] +==== Mistyping Cases + +In the following cases the expression in the `FROM` `UNPIVOT` clause +item has the "`wrong`" type, i.e., it is not a tuple. Under the type +checking option, all of these cases raise an error and the query +fails. Under the permissive option, the cases proceed as follows: + +[source%unbreakable, partiql] +---- +FROM UNPIVOT x AS v AT n +---- + +whereas stem:[x] is not a tuple and is not `MISSING`, is equivalent to: + +[source%unbreakable, partiql] +---- +FROM UNPIVOT {'_1': x} AS v AT n +---- + +Effectively, a tuple is generated for the non-tuple value. When +stem:[x] is `MISSING` then the above is equivalent to: + +[source%unbreakable, partiql] +---- +FROM UNPIVOT {} AS v AT n +---- + +remember that a tuple cannot contain `MISSING`. So the present case is equivalent +to the empty tuple case. + +[[sec:combining-multiple-item-join]] +=== Combining Multiple `FROM` Items with Comma, `CROSS JOIN` , or `JOIN` + +The `FROM` clause expressions: + + +[subs="+normal", unbreakable] +==== +[source%unbreakable, partiql] +---- +l,r +---- +stem:[<=>] +[source%unbreakable, partiql] +---- +l CROSS JOIN r +---- +stem:[<=>] +[source%unbreakable, partiql] +---- +l JOIN r ON TRUE +---- +==== + + +have the same semantics. They combine the bag of bindings produced +from the `FROM` item stem:[l] with the bag of binding tuples produced +by the `FROM` item stem:[r], whereas the expression stem:[r] may +utilize variables defined by stem:[l]. Again, the term “the semantics +of `l CROSSJOIN r`” is equivalent to the term “the semantics of +`FROM l CROSSJOIN r`”. In both cases, the semantics specify a bag of +binding tuples. + +==== Associativity of `CROSS JOIN` + +We explain the `CROSS JOIN` and `,` as if they are left associative +binary operators, despite the fact that one can write more than two +`FROM` items without specifying grouping with parenthesis. Since the +`,` and `CROSS JOIN` operators are associative, we may write (as is +common in SQL): + + +[subs="+normal"] +[%unbreakable] +==== +[source%unbreakable, partiql] +---- +f1, f2, f3 +---- +stem:[<=>] +[source%unbreakable, partiql] +---- +f1 CROSS JOIN f2 CROSS JOIN f3 +---- +stem:[<=>] +[source%unbreakable, partiql] +---- +f1 JOIN f2 ON TRUE JOIN f3 ON TRUE +---- +stem:[<=>] +[source%unbreakable, partiql] +---- +(f1, f2), f3 +---- +stem:[<=>] +[source%unbreakable, partiql] +---- +(f1 CROSS JOIN f2) CROSS JOIN f3 +---- +stem:[<=>] +[source%unbreakable, partiql] +---- +(f1 JOIN f2 ON TRUE) JOIN f3 ON TRUE +---- +==== + + +==== Semantics + +Consider the following: + +[source%unbreakable, partiql] +---- +l CROSS JOIN r +---- + +unlike SQL, the rhs stem:[r] of the expression may use variables +defined by the lhs item stem:[l]. The result of this expression for a +database environment stem:[p_0] and variables environment stem:[p] is +the bag of binding tuples produced by the following pseudo-code. The +pseudo-code uses the function stem:["eval"(p_0,p,e)] that evaluates +the expression stem:[e] within the environments stem:[p_0] and +stem:[p], i.e., stem:[p_0,p |-- e -> "eval"(p_0,p,e)]. + +[source] +---- +for each binding tuple b_l in eval(p0,p,l) + for each binding tuple b_r in eval(p0, (p || b_l), r) + add (b_l || b_r) to the output bag +---- + +In other words, the `l CROSS JION r` outputs all binding tuples +stem:[b = b^l || b^r], where stem:[b^l in "eval"(p_0,p,l)] and +stem:[b^r in "eval"(p_0, (p || b^l), r)]. The key extension to SQL +is that stem:[r] is evaluated in the variables environment stem:[p || +b^l], i.e., it can use the variables that were defined by +stem:[l]. The details of the variable scoping aspects are described in +<>. + + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== +This example simply reminds the tuple calculus explanation of the `FROM` SQL +semantics. It does not yet endeavor into special aspects of PartiQL. +Consider the following database, which is conventional SQL: + + +stem:[ p_0 = << ] + +stem:[ "customers": \[ ] + +stem:[ {"'id'": 5, "'name'": "'Joe'"}, ] + +stem:[ {"'id'": 7, "'name'": "'Mary'"} ] + +stem:[ \], ] + +stem:[ "orders": \[ ] + +stem:[ { "'custId'": 7, "'productId'" : 101}, ] + +stem:[ { "'custId'": 7, "'productId'" : 523} ] + +stem:[ \] ] + +stem:[ >> ] + + +Then consider the following `FROM` clause, which could be coming from a +conventional SQL query: + +[source%unbreakable, partiql] +---- +FROM customers AS c, orders AS o +---- + +Note that in PartiQL this could also be written using the `CROSS JOIN` +keyword, and presumably, one would put the sensible equality condition +`c.id = o.custId` in the `WHERE` clause. At any rate, this `FROM` +clause outputs the bag of binding tuples: + +stem:[B_"FROM"^"out" = < <] + +stem:[ << c: {"'id'": 5, "'name'": "'Joe'"}, o: {"'custId'": 7, "'productId'": 101} >> ] + +stem:[ << c: {"'id'": 5, "'name'": "'Joe'"}, o: {"'custId'": 7, "'productId'": 523} >> ] + +stem:[ << c: {"'id'": 7, "'name'": "'Mary'"}, o: {"'custId'": 7, "'productId'": 101} >> ] + +stem:[ << c: {"'id'": 7, "'name'": "'Mary'"}, o: {"'custId'": 7, "'productId'": 523} >> ] + +stem:[> >] +==== + + + + +Due to scoping rules that will be justified and elaborated in +<>, when the rhs of a `CROSS JOIN` is a path or +a function that uses a variable named stem:[n], such variable must be +referred as stem:[\@n]. + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== +Consider the database: + +stem:[ p_0 = << ] + +stem:[ "sensors": \[ ] + +stem:[ {"'readings'": [{"'v'": 1.3}, {"'v'": 2}]}, ] + +stem:[ {"'readings'": [{"'v'": 0.7}, {"'v'": 0.8}, {"'v'": 0.9}]} ] + +stem:[ \] ] + +stem:[ >> ] + +Intuitively, the following `FROM` clause unnests the tuples that are nested +within the `readings`. + +[source%unbreakable, partiql] +---- +FROM sensors AS s, s.readings AS r +---- + +stem:[B_"FROM"^"out" = < <] + +stem:[ s: {"'readings'": \[{"'v'": 1.3}, {"'v'": 2}\]}, r: {v:1.3} ] + +stem:[ s: {"'readings'": \[{"'v'": 1.3}, {"'v'": 2}\]}, r: {v:2} ] + +stem:[ s: {"'readings'": \[{"'v'": 0.7}, {"'v'": 0.8}, {"'v'": 0.9}\]}, r: {"'v'":0.7} ] + +stem:[ s: {"'readings'": \[{"'v'": 0.7}, {"'v'": 0.8}, {"'v'": 0.9}\]}, r: {"'v'":0.8} ] + +stem:[ s: {"'readings'": \[{"'v'": 0.7}, {"'v'": 0.8}, {"'v'": 0.9}\]}, r: {"'v'":0.9} ] + +stem:[> >] +==== + + + + +[[sec:combining-multiple-item-leftjoin]] +=== Combining Multiple Items with + +The `FROM` clause expression: + + +[subs="+normal"] +[%unbreakable] +==== +[source%unbreakable, partiql] +---- +l LEFT CROSS JOIN r +---- +stem:[<=>] +[source%unbreakable, partiql] +---- +l LEFT JOIN r ON TRUE +---- +==== + +replicates SQL’s `LEFT JOIN` functionality and, in addition, it also +works for the case where the lhs of stem:[r] uses variables defined +from stem:[l]. + +Let’s assume that the variables defined by stem:[r] are +stem:[v_1^r, ..., v_n^r]. The result of evaluating `l LEFT CROSS JOIN r` in +environments stem:[p_0] and stem:[p] is the bag of binding tuples +produced by the following pseudocode, which also uses the +stem:["eval"] function (See <>). + +[source%unbreakable] +---- +for each binding bl in eval(p0, p, l) + Br = eval(p0,(p||bl),r) + if Br is the empty bag + add (bl || ⟨v1r : NULL . . . vnr : NULL⟩) to the output bag + else + for each binding br in Br + add (bl || br) to the output bag +---- + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== +Consider the database: + +stem:[ p_0 = << ] + +stem:[ "sensors": \[ ] + +stem:[ {"'readings'": \[{"'v'":1.3}, {"'v'":2}\]} ] + +stem:[ {"'readings'": \[{"'v'":0.7}, {"'v'":0.8}, {"'v'":0.9}\]}, ] + +stem:[ {"'readings'": \[\]} ] + +stem:[ \] ] + +stem:[ >> ] + +Notice that the value of the last tuple’s `reading` attribute is the +empty array. The following `FROM` clause unnests the tuples that are +nested within the `readings` but will also keep around the tuple with +the empty `readings`. (See the last binding tuple.) + +[source%unbreakable, partiql] +---- +FROM sensors AS s LEFT CROSS JOIN s.readings AS r +---- + +stem:[B_"FROM"^"out" = < <] + +stem:[ s: {"'readings'": \[{"'v'":1.3}, {"'v'":2}\]}, r: {"'v'":1.3} ] + +stem:[ s: {"'readings'": \[{"'v'":1.3}, {"'v'":2}\]}, r: {"'v'":2} ] + +stem:[ s: {"'readings'": \[{"'v'":0.7}, {"'v'":0.8}, {"'v'":0.9}\]}, r: {"'v'":0.7} ] + +stem:[ s: {"'readings'": \[{"'v'":0.7}, {"'v'":0.8}, {"'v'":0.9}\]}, r: {"'v'":0.8} ] + +stem:[ s: {"'readings'": \[{"'v'":0.7}, {"'v'":0.8}, {"'v'":0.9}\]}, r: {"'v'":0.9} ] + +stem:[ s: {"'readings'": \[\]}, r: "NULL" ] + +stem:[ >> ] +==== + + + + +[[sec:combining-multiple-item-full-outerjoin]] +=== Combining Multiple `FROM` Items with `FULL JOIN` + +The clause expression: + +[source%unbreakable, partiql] +---- +l FULL JOIN r ON c +---- + +replicates SQL’s `FULL JOIN` functionality. It assumes that (alike +SQL) the lhs of stem:[r] does not use variables defined from +stem:[l]. Thus, we do not discuss further. + +[[sec:rewriting-on]] +=== Expanding `JOIN` and `LEFT JOIN` with `ON` + +In compliance to SQL, the and have an optional clause. The semantics +of can be explained as syntactic sugar over the core PartiQL. They can +also be explained by a simple extension of the semantics of +<>, +<>, and +<>. The semantics of: + +[source%unbreakable, partiql] +---- +l JOIN r ON c +---- + +are the following modification of the pseudocode of +<>. + + +[source%unbreakable] +---- +for each binding tuple b_l in eval(p0,p,l) + for each binding tuple b_r in eval(p0, (p || b_l), r) + if eval(p0, (p || b_l || b_r), c) is true <1> + add (b_l || b_r) to the output bag +---- +<1> The modification for `ON` + + +The semantics of: + +[source%unbreakable, partiql] +---- +l LEFT JOIN r ON c +---- + +are the following modification of the pseudocode of +<>. In essence, the outputs a +tuple padded with whenever there is no binding of stem:[r] that +satisfies the condition stem:[c]. + +[source%unbreakable] +---- +for each binding bl in eval(p0, p, l) + Br = eval(p0,(p||bl),r) + Qr = <<>> + for each binding br in Br + if eval(p0, (p || bl || br), c) is true + add br in Qr + if Qr is the empty bag + add (bl || ⟨v1r : NULL . . . vnr : NULL⟩) to the output bag + else + for each binding br in Qr + add (bl || br) to the output bag +---- + +[[sec:lateral]] +=== SQL’s `LATERAL` + +SQL 2003 used the `LATERAL` keyword to correlate clause items. In the +interest of compatibility with SQL, PartiQL also allows the use of the +keyword `LATERAL`, though it does not do anything more than the comma itself +would do. That is `l, LATERAL r` is equivalent `l, r`. diff --git a/markup/math/inline_quoted_5ede1e.adoc b/markup/math/inline_quoted_5ede1e.adoc new file mode 100644 index 0000000..5345631 --- /dev/null +++ b/markup/math/inline_quoted_5ede1e.adoc @@ -0,0 +1,59 @@ +// .basic +[why]#chunky bacon# + +// .emphasis +_chunky bacon_ + +// .emphasis-with-role +[why]_chunky bacon_ + +// .strong +*chunky bacon* + +// .strong-with-role +[why]*chunky bacon* + +// .monospaced +`hello world!` + +// .monospaced-with-role +[why]`hello world!` + +// .superscript +^super^chunky bacon + +// .superscript-with-role +[why]^super^chunky bacon + +// .subscript +~sub~chunky bacon + +// .subscript-with-role +[why]~sub~chunky bacon + +// .mark +#chunky bacon# + +// .double +"`chunky bacon`" + +// .double-with-role +[why]"`chunky bacon`" + +// .single +'`chunky bacon`' + +// .single-with-role +[why]'`chunky bacon`' + +// .asciimath +asciimath:[sqrt(4) = 2] + +// .latexmath +latexmath:[C = \alpha + \beta Y^{\gamma} + \epsilon] + +// .with-id +[#why]_chunky bacon_ + +// .mixed-monospace-bold-italic +`*_monospace bold italic phrase_*` and le``**__tt__**``ers diff --git a/markup/math/licao_6_feba57.qmd b/markup/math/licao_6_feba57.qmd new file mode 100644 index 0000000..4ba6bee --- /dev/null +++ b/markup/math/licao_6_feba57.qmd @@ -0,0 +1,263 @@ +--- +title: "Modelos lineares generalizados: linearidade com esteróides" +author: "" +format: + pdf: + mathspec: true + fig-pos: H +--- + +::: hidden +```{=tex} +\def\pr{\operatorname{Pr}} +\def\vr{\operatorname{Var}} +\def\cv{\operatorname{Cov}} +\def\bY{\boldsymbol{Y}} +\def\bX{\boldsymbol{X}} +\def\by{\boldsymbol{y}} +\def\bx{\boldsymbol{x}} +\def\bb{\boldsymbol{\beta}} +\def\sM{\bar{X}_n} +\def\indep{\perp \!\!\! \perp} +\def\bth{\boldsymbol{\theta}} +\def\bmu{\boldsymbol{\mu}} +``` +::: + +## Motivação + +Como vimos até aqui, o modelo linear é bastante flexível e poderoso. +No entanto, o modelo normal tem uma limitação importante: o suporte da distribuição dos dados, que fica limitado a $\mathbb{R}$. +Como muitos fenômenos de interesse podem ser modelados como variáveis aleatórias com suporte restrito (e.g. $(0, 1)$ ou $\mathbb{R}_{+}$) e também discreto, como é o caso do modelos de contagem. + +A solução se encontra na formulação dos chamados **modelos lineares generalizados** (_generalised linear models_, GLM), em que o preditor linear é conectado à esperança condicional por meio de uma função especial, chamada função de ligação. + +# A estrutura básica de um GLM + +Sejam $\bY = (Y_1, \ldots, Y_n)$ e $\bX$ o vetor de variáveis dependentes e a matriz ($n \times P$) de desenho, respectivamente. +Defina $\mu_i(\bX) = \mu_i := E[Y_i \mid \bX]$ como a média condicional de cada $Y_i$. +Em um GLM, escrevemos +\begin{equation*} +\label{eq:glm_I} +g(\bmu) = \bX\bb, +\end{equation*} +onde $g(\cdot)$ é uma função monotônica e diferenciável, chamada de **função de ligação**. +Além disso, suponha que cada $Y_i$ tenha distribuição da família exponencial com parâmetro canônico $\theta_i$, isto é, +\begin{equation*} +\label{eq:exp_fam_I} +f(y_i ; \theta_i) = \exp\left\{y_i \theta_i - b(\theta_i) + c(y_i) \right\}. +\end{equation*} +Logo, +\begin{align*} +\label{eq:exp_fam_II} +f(\by ; \bth) &= \prod_{i=1}^{n} f(y_i ; \theta_i), \\ +&= \exp\left\{\sum_{i=1}^{n} y_i \theta_i - \sum_{i=1}^{n} b(\theta_i) + \sum_{i=1}^{n} c(y_i) \right\}. +\end{align*} + +Suponha que $g$ é a função de ligação canônica, isto é, que $g(\mu_i) = \bx_i^T \bb = \theta_i$. Então, a log-verossimilhança para $\bb$ é + +\begin{align*} +\ell(\bb) &= \sum_{i=1}^{n} y_i \theta_i - \sum_{i=1}^{n} b(\theta_i) + \sum_{i=1}^{n} c(y_i), \\ +&= \sum_{i=1}^{n} y_i \bx_i^T\bb - \sum_{i=1}^{n} b(\bx_i^T\bb) + \sum_{i=1}^{n} c(y_i). +\end{align*} + +Em notação matricial, temos + +\begin{align*} +\ell(\bb) &= \by^T\bX\bb - \boldsymbol{1}^T b(\bX\bb) + \boldsymbol{1}^T c(\by), +\end{align*} + +onde $\boldsymbol{1}$ é um vetor de uns de dimensão $n$. Logo, + +\begin{align*} +\frac{\partial \ell(\bb)}{\partial \beta_k} &= \sum_{i=1}^{n} y_i x_{ik} - \sum_{i=1}^{n} x_{ik} b'(\bx_i^T\bb), \\ +\frac{\partial^2 \ell(\bb)}{\partial \beta_k \partial \beta_l} &= -\sum_{i=1}^{n} x_{ik} x_{il} b''(\bx_i^T\bb), +\end{align*} + +ou seja, + +\begin{align*} +\nabla \ell(\bb) &= \bX^T(\by - b'(\bX\bb)), \\ +\nabla^2 \ell(\bb) &= -\bX^T \text{diag}\left\{b''(\bX\bb)\right\} \bX. +\end{align*} + +# Ajustando um GLM: métodos numéricos + + + + +Para estimar $\bb$ por máxima verossimilhança, podemos usar o método de Newton-Raphson ou o método de Fisher scoring. Dado um valor inicial $\bb^{(0)}$, a iteração $t$ do primeiro é dada por + +\begin{align*} +\bb^{(t+1)} &= \bb^{(t)} - \left[\nabla^2 \ell(\bb^{(t)})\right]^{-1} \nabla \ell(\bb^{(t)}), +\end{align*} + +enquanto a iteração $t$ do segundo é dada por + +\begin{align*} +\bb^{(t+1)} &= \bb^{(t)} + \left[\mathcal{I}(\bb^{(t)})\right]^{-1} \nabla \ell(\bb^{(t)}), +\end{align*} + +onde $\mathcal{I}(\bb^{(t)})$ é a informação de Fisher. Se a função de ligação for canônica, então os métodos são equivalentes. + +Para maior eficiência computacional, podemos definir $\bX_t = \text{diag}\left\{b''(\bX\bb^{(t)})\right\}^{1/2} \bX$ e obter a decomposição QR, $\bX_t = Q_t R_t$. Definindo $w_t = b''(\bX\bb^{(t)})$ e $z_t = \by - b'(\bX\bb^{(t)})$, é possível mostrar que + +\begin{align*} +\bb^{(t+1)} &= \bb^{(t)} + R_t^{-1} Q_t^T \left\langle \text{diag}\{w_t\}^{-1/2}, z_t \right\rangle, +\end{align*} + +o que resulta no seguinte sistema linear: + +\begin{align*} +R_t (\bb^{(t+1)} - \bb^{(t)}) &= Q_t^T \left\langle \text{diag}\{w_t\}^{-1/2}, z_t \right\rangle. +\end{align*} + +# Exemplo: regressão Poisson + +Considere $Y_i \mid \bX \sim \text{Poisson}(\theta_i)$. Primeiro, vamos expressar a f.d.p. em termos da família exponencial. Temos + +\begin{align*} +f(y ; \theta) &= \frac{\exp\{-\theta\} \theta^{y}}{y!}, \\ +&= \exp\left\{y \log(\theta) - \theta - \log(y!)\right\}, +\end{align*} + +ou seja, o parâmetro canônico é $\eta = \log(\theta)$, $b(\eta) = \exp(\eta)$ e $c(y) = -\log(y!)$. Lembre-se que a função de ligação canônica é aquela que conecta o parâmetro canônico $\eta_i$ com $\mu_i$ e $\bx_i^T \beta$ de modo que $\eta_i = \bx_i^T \beta$. Logo, como $\mu_i = \exp(\eta_i)$, temos que $g(t) = \log(t)$ e, portanto, $\mu_i = \exp(\bx_i^T \beta)$. + +Agora vamos obter a função score e a Hessiana, necessárias para a estimação dos parâmetros. Pelos cálculos anteriores, a função score é dada por + +\begin{align*} +\nabla \ell(\bb) &= \bX^T(\by - \exp(\bX\bb)) +\end{align*} + +e a Hessiana, + +\begin{align*} +\nabla^2 \ell(\bb) &= -\bX^T \text{diag}\left\{\exp(\bX\bb)\right\} \bX. +\end{align*} + +Por fim, basta usar o método de Newton-Raphson: + +\begin{align*} +\bb^{(t+1)} &= \bb^{(t)} + \left[\bX^T \text{diag}\left\{\exp(\bX\bb^{(t)})\right\} \bX\right]^{-1} \bX^T(\by - \exp(\bX\bb^{(t)})), +\end{align*} + +o que leva ao seguinte sistema, como visto anteriormente: + +\begin{align*} +R_t (\bb^{(t+1)} - \bb^{(t)}) &= Q_t^T \left\langle \exp\left( -\frac{1}{2} \bX\bb^{(t)} \right), \by - \exp(\bX\bb^{(t)}) \right\rangle. +\end{align*} + +Para fazer isso no R, vamos implmentar uma função que ajusta um modelo GLM para distribuições com um parâmetro: + +```{r} +# função para ajustar um GLM para distribuições com um parâmetro +glm1 <- function(y, X, bp, bpp) { + # pega o número de variáveis + p <- NCOL(X) + # inicializa o vetor de parâmetros + beta_k <- rep(0, p) + # inicializa a lista de parâmetros + list_beta <- list() + # critério de parada + stop_error <- 1e-6 + # inicializa o contador + j <- 1L + # inicializa o erro + current_error <- 1 + + while (current_error > stop_error) { + # define variaveis auxiliares + eta_k <- X %*% beta_k + z_k <- y - bp(eta_k) + w_k <- bpp(eta_k) + X_k <- drop(w_k^(1/2)) * X + wz_k <- w_k^(-1/2) * z_k + # calcula a decomposição QR + qr_out <- qr(X_k) + Q_k <- qr.Q(qr_out) + R_k <- qr.R(qr_out) + # calcula a solução do sistema + a_k <- backsolve(R_k, crossprod(Q_k, wz_k)) + + # guarda o valor de beta_k + list_beta[[j]] <- a_k + beta_k + # atualiza o erro + current_error <- max(abs(beta_k - list_beta[[j]])) + # atualiza o valor de beta_k + beta_k <- list_beta[[j]] + # atualiza o contador + j <- j + 1L + } + + do.call(cbind, list_beta) +} +``` + +Agora, vamos construir uma função para o GLM Poisson: + +```{r} +# função para ajustar um GLM Poisson +poiReg <- function(formula, data) { + # constroi o modelo + mf <- model.frame(formula, data = data) + # pega a variável resposta + y <- model.response(mf) + # pega a matriz de desenho + X <- model.matrix(formula, mf) + # define a derivada de b(eta) + bp <- function(theta) exp(theta) + # define a segunda derivada de b(eta) + bpp <- function(theta) exp(theta) + glm1(y, X, bp, bpp) +} +``` + +Para checar as funções, vamos simular dados:: + +```{r} +# define a semente +set.seed(20032025) + +# define os parâmetros +n <- 500 +X <- cbind(1, rnorm(n), runif(n)) +betas <- c(1, -0.5, 0.5) +eta <- drop(X %*% betas) +lambda <- exp(eta) +# simula os dados +y <- rpois(n, lambda) +sim_data <- data.frame(y = y, x1 = X[, 2], x2 = X[, 3]) +``` + +Agora, vamos comparar os resultados: + +```{r} +# ajusta o modelo com a função poiReg +out_poiReg <- poiReg(formula = y ~ x1 + x2, data = sim_data) +# ajusta o modelo com a função nativa glm +out_glm <- glm(formula = y ~ x1 + x2, data = sim_data, family = "poisson") +cbind(true = betas, + logReg = out_poiReg[, ncol(out_poiReg)], + glm = coef(out_glm)) +``` + +# Exercícios de fixação: **Regressão logística** + +Seja $Y_i \mid \bX \sim \text{Bernoulli}(\theta_i)$, com $E[Y_i \mid \bX] = \mu_i = g^{-1}(\bx_i^\top \bb)$. + +1. Mostre que a distribuição de $Y_i$ pertence à família exponencial e encontre a função de ligação canônica. + +2. Encontre a log-verossimilhança e exiba a função score e a Hessiana. + +3. Mostre como obter o estimador de máxima verossimilhança para $\bb$. + +4. Implemente uma função para ajustar uma regressão logística e compare os resultados com a função `glm` usando dados de sua escolha. + +5. (**Desafio**) Mostre como obter intervalos de confiança para $\bb$ usando o método de Wald -- ver +Seção 5.4 de Dobson (2018). +Calcule os intervalos para um exemplo empírico e compare com o output da função `confint()` do R. + +## Referências + +- Dobson, A. J., & Barnett, A. G. (2018). [An introduction to generalized linear models](https://books.google.com.br/books/about/An_Introduction_to_Generalized_Linear_Mo.html?id=YOFstgEACAAJ&redir_esc=y). CRC press. (Caps 3, 4 e 5) +- Gelman, A., Hill, J., & Vehtari, A. (2020). [Regression and other stories](https://avehtari.github.io/ROS-Examples/). Cambridge University Press. (Cap 15) diff --git a/markup/math/paths_32d458.adoc b/markup/math/paths_32d458.adoc new file mode 100644 index 0000000..dc6682a --- /dev/null +++ b/markup/math/paths_32d458.adoc @@ -0,0 +1,419 @@ +[[section:paths]] +== Path Navigation + +[discrete] +==== Tuple path navigation + +A _tuple path navigation_ stem:[t.a] from the tuple stem:[t] to its +attribute stem:[a] (<<#figure:query:bnf>> line 27) returns the value +of the attribute stem:[a]. (We discuss below the corner case where a +tuple has multiple attributes `a`.) stem:[t] is an expression but +stem:[a] is always an identifier (<<#figure:names:bnf>> lines +5-6). For example: + +[subs="+normal"] +[%unbreakable] +==== +[source, partiql] +---- +{'a': 1, 'b':2}.a +---- +stem:[<=>] +[source, partiql] +---- +{'a': 1, 'b': 2}."a" +---- +stem:[->] +[source,partiql] +---- +1 +---- +==== + +Even if there were a variable `a`, bound to `'b'`, the result of the +above expression would still be `1`, because the identifier `a` (or +`"a"`) is interpreted as the "`look for the attribute named `a` `" +when it follows the dot in a tuple path navigation. The semantics of +tuple path navigation do not depend on whether the tuple is ordered or +unordered by schema. + +[discrete] +==== Array navigation + +An _array navigation_ stem:[a\[i\]] returns the stem:[i]-th element +_when_ it is applied on an array stem:[a] (<<#figure:query:bnf>> line +28) and stem:[i] is an expression that evaluates into an integer. Both +stem:[a] and stem:[i] are expressions. For example: + +[subs="+normal"] +[%unbreakable] +==== +[source, partiql] +---- +[2, 4, 6][1+1] +---- +stem:[->] +[source,partiql] +---- +6 +---- +==== + +[discrete] +==== Tuple navigation with array notation + +The expression stem:[a\[s\]] is a shorthand for the tuple path +navigation stem:[a.s] when the expression stem:[s] is either (a) a +string literal or (b) an expression that is explicitly `CAST` into a +string. For example: + +[subs="+normal"] +[%unbreakable] +==== +[source, partiql] +---- +{'a': 1, 'b': 2}['a'] +---- +stem:[<=>] +[source, partiql] +---- +{'a': 1, 'b': 2}.'a' +---- +stem:[->] +[source,partiql] +---- +1 +---- +==== + +Similarly: + +[subs="+normal"] +==== +[source, partiql] +---- +{'attr': 1, 'b':2}[CAST('at' || 'tr' AS STRING)] +---- +stem:[->] +[source,partiql] +---- +1 +---- +==== + + +If stem:[s] is not a string literal or an expression that is cast into +a string, then stem:[a\[s\]] is evaluated as an array path +navigation. Notice that in the absence of an explicit cast, the +navigation stem:[a\[e\]] evaluates as an array navigation, even if +stem:[e] ends up evaluating to a string. For example, let us assume +that the variable `v` is bound to `at` and the variable `w` is bound +to `tr`. Still, the expression: + +// TODO determine if cases where static type is known requires a CAST. + +[source, partiql] +---- +{'attr': 1, 'b':2}[v || w] +---- + +does not evaluate to `1`. It is treated as an array navigation with wrongly +typed index and it will return `MISSING`, for reasons explained below. + +[discrete] +==== Composition of navigations + +Notice that consecutive tuple/array navigations (e.g. `r.no[1]`) +navigate deeply into complex values. Notice further that paths +consisting of plain tuple and array path navigations evaluate to a +unique value. + +// TODO verify that this is correct for unordered tuples. + +[discrete] +==== Tuple navigation in tuples with duplicate attributes + +When the tuple `t` has multiple attributes `a`, the tuple path navigation `t.a` will +return the first instance of `a`. Note that for tuples whose order is +defined by schema, this is well-defined, for unordered tuples, it is +implementation defined which attribute is returned in _permissive mode_ +or an error in _type checking mode_, which is described in +<>. + +If one wants to access all instances of `a`, she should use the +`UNPIVOT` feature instead (see <>). For example, the +following query returns the list of all `a` values in a tuple `t`. + +[source%unbreakable, partiql] +---- +SELECT VALUE v +FROM UNPIVOT t AS v AT attr +WHERE attr = 'a' +---- + +[[sec:tuple-path-on-wrong]] +=== Tuple path evaluation on wrongly typed data + +In the case of tuple paths, since PartiQL does not assume a schema, the +semantics must also specify the return value when: + +1. stem:[t] is not a tuple (i.e., when the expression stem:[t] does +not evaluate into a tuple), or + +2. stem:[t] is a tuple that does not have an stem:[a] attribute. + +[discrete] +==== Permissive mode + +PartiQL can operate in a permissive mode or in a conventional type +checking mode, where the query fails once typing errors (such as the +above mentioned ones) happen. In the permissive mode, typing errors are +typically neglected by using the semantics outlined next. + +In all of the above cases PartiQL returns the special value +`MISSING`. Recall, the `MISSING` is different from `NULL`. The +distinction enables PartiQL to be able to distinguish between a tuple +(JSON object) that lacked an attribute `a` and a tuple (JSON object) +whose `a` attribute was `NULL`. This distinction, coupled with +appropriate features on how result tuples are constructed (see +`SELECT` clause in <>), enables PartiQL to easily +preserve (when needed) the distinction between absent attribute and +null-valued attribute. + +For example, the expression ` 'not a tuple'.a ` and the expression +`{'a':1, 'b':2}.noSuchAttribute` evaluate to `MISSING`. + +The above semantics apply regardless of whether the tuple navigation +is accomplished via the dot notation or via the array notation. For +example, the expression `{'a':1, 'b':2}['noSuchAttribute']` will also +evaluate to `MISSING`. + +[discrete] +==== Type checking mode + +In the type checking mode and in the absence of schema, PartiQL will +fail when tuple path navigation is applied on wrongly typed data. + +[[sec:schema-in-tuple-path]] +==== Role of schema in type checking + +In the presence of schema, PartiQL may return a compile-time error when +the query processor can prove that the path expression is guaranteed to +_always_ produce `MISSING`. The extent of error detection is +implementation-specific. + +For example, in the presence of schema validation, an PartiQL query +processor can throw a compile-time error when given the path expression +`{a:1, b:2}.c`. In a more important and common case, an PartiQL implementation can +utilize the input data schema to prove that a path expression _always_ +returns `MISSING` and thus throw a compile-time error. For example, assume that `sometable` is +an SQL table whose schema does not include an attribute `c`. Then, an +PartiQL implementation may throw a compile-time error when evaluating +the query: + +[source, partiql] +---- +SELECT t.a, t.c FROM sometable AS t +---- + +Apparently, such an PartiQL implementation is fully compatible with the +behavior of an SQL processor. Generally, if a rigid schema is explicitly +present, a tuple path navigation error can be caught during compilation +time; this is the case in SQL itself, where referring to a non-existent +attribute leads to a compilation error for the query. + +Notice that operating with schema validation may not prevent all tuple +path navigations from being applied to wrongly typed data. The choice +between permissive mode versus type checking mode dictates what happens +next in these cases: If permissive, the tuple path navigation evaluates +into `MISSING`. If in type checking mode, the query fails. + +[[sec:array-on-wrong]] +=== Array navigation evaluation on wrongly typed data + +In the permissive mode, an array navigation evaluation +stem:[a\[i\]] will result into `MISSING` in each of the following cases: + +* stem:[a] does not evaluate into an array, or +* stem:[i] does not evaluate into a positive integer within the +array’s bounds. + +For example, `[1,2,3][1.0]` evaluates to `MISSING` since `1.0` is not +an integer - even though it is coercible to an integer. + +In type checking mode, the query will fail in each one of the cases +above. + +[[sec:deep-navigation]] +=== Additional Path Syntax + +The following additional path functionalities are explained by reduction +to the basic tuple navigation and array navigation. + +[discrete] +==== Wildcard steps + +The expression stem:[e\[**\]] reduces to (i.e., is equivalent to): + +[source%unbreakable, partiql] +---- +SELECT VALUE v FROM e AS v +---- + +where stem:[v] is a _fresh variable_, i.e., a variable that does not +already appear in the query. Similarly, when the expression stem:[e.**] +is not a `SELECT` clause item of the form stem:[t.*], where stem:[t] is a +variable, it reduces to: + +[source%unbreakable, partiql] +---- +SELECT VALUE v FROM UNPIVOT e AS v +---- + +where stem:[v] is a fresh variable. An expression stem:[t.**], where +stem:[t] is a variable and the expression appears as a `SELECT` clause +item, is interpreted according to the `SELECT` clause semantics +(<>). + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== +The expression: + +[source, partiql] +---- +[1,2,3][*] +---- +stem:[<=>] +[source, partiql] +---- +SELECT VALUE v FROM [1, 2, 3] AS v +---- +stem:[->] +[source, partiql] +---- +<< 1,2,3 >> +---- + +The expression: + +[source, partiql] +---- +{'a':1, 'b':2}.* +---- +stem:[<=>] +[source, partiql] +---- +SELECT VALUE v FROM UNPIVOT {'a':1, 'b':2} AS v +---- +stem:[->] +[source, partiql] +---- +<<1,2>> +---- + +Whereas the following query: + +[source, partiql] +---- +SELECT t.* FROM <<{'a':1, 'b':1}, {'a':2, 'b':2}>> AS t +---- +stem:[->] +[source, partiql] +---- +<< {'a':1, 'b':1}, {'a':2, 'b':2} >> +---- + +does not do the transformation with `UNPIVOT`. If one does not want +this behavior, `SELECT VALUE` can be used (<>). +==== + + + + +[discrete] +==== Path Expressions with Wildcards + +PartiQL also provides multi-step path expressions, called _path +collection expressions_. Their semantics is a generalization of the +semantics of a path expression with a single stem:[\[**\]] or +stem:[.**]. Consider the path collection expression: + +[stem] +++++ +e w_1 p_1...w_n p_n +++++ + +where stem:[e] is any expression; stem:[n>0]; each _wildcard step_ +stem:[w_i] is either stem:[\[**\]] or stem:[.**]; each _series of +plain path steps_ stem:[p_i] is a sequence of zero or more tuple path +navigations or array navigations (potentially mixed). + +Then the path collection expression is equivalent to the SFW query + + +[source%unbreakable, partiql, subs="+normal"] +---- +SELECT VALUE vn.pn +FROM + u1 e AS v1, + u2 v1.p1 AS v1, + . . . + un @vn-1.pn-1 AS vn +---- + +where each stem:[v_i] is a fresh variable and each stem:[u_i] is +`UNPIVOT` if stem:[w_i] is a stem:[.**] and it is nothing if +stem:[w_i] is a stem:[\[**\]]. Intuitively stem:[v_i] corresponds to +the stem:[i]-th star. + + + +// .{nbsp} generates a `Figure X.` caption with no 'label' +.{nbsp} +[%unbreakable] +[subs="+normal"] +==== +According to the above, consider the following query: + +[source, partiql] +---- +SELECT VALUE foo FROM e.* AS foo +---- + +reduces to + +[source, partiql] +---- +SELECT VALUE foo FROM (SELECT VALUE v FROM UNPIVOT e AS v) AS foo +---- + +which is equivalent to + +[source, partiql] +---- +SELECT VALUE foo FROM UNPIVOT e AS foo +---- + +Next, consider the path collection expression: + +[source%unbreakable, partiql] +---- +tables.items[*].product.*.nest +---- + +This expression reduces to + +[source%unbreakable, partiql] +---- +SELECT + VALUE v2.nest +FROM + tables.items AS v1, + UNPIVOT @v1.product AS v2 +---- +==== diff --git a/markup/math/sensorlib_spec_f243ef.adoc b/markup/math/sensorlib_spec_f243ef.adoc new file mode 100644 index 0000000..c22526b --- /dev/null +++ b/markup/math/sensorlib_spec_f243ef.adoc @@ -0,0 +1,5961 @@ += MOSS-FW Arithmetic Processing Library Specification +Copyright 2023 Sony Semiconductor Solutions Corporatation +v1.0.0, 2023-03-07 +:sectnums: +:toc: +:table-caption: Table +:figure-caption: figure +:stem: +:doctype: book +:mathematical-format: svg +:scripts: cjk +:pdf-theme: sensorlib_theme.yml +:chapter-signifier: +:xrefstyle: short +:toc-title: Table of Contents +:chapter-refsig: Chapter +:section-refsig: +:appendix-caption: Appendix +:appendix-refsig: Appendix +:toclevels: 4 +:sectnumlevels: 4 +:docinfo: shared +:data-uri: + +== Summary + +=== Purpose + +This paper describes the SensorLIB Argo signal processing function specifications. +Up to chapter 3, we describe the behavior from the outside. +Chapter 5 and later describe the API. + +=== License + +All the source code, including documentation, is licensed under the Apache License, Version 2.0. + +=== Possible Readers + +<> lists the probable readers of this book. + +[#tableid_reader] +[cols="1,2"] +.Possible readers +|=== +|Reader |Description + +|Application creator +|A person who creates applications using sensors such as IMUs +|=== + +=== Notation + +<> lists the notations used in this manual. + +[#tableid_description] +[cols="1,2"] +.List of notations +|=== +|Notation |Description + +|FIXME +|Indicates that listed specifications will change + +|TODO +|indicates that it will be described later + +|NOTE +|Show information + +|IMPORTANT +|Show important information +|=== + +=== Definitions and Abbreviations + +<> <> provides a list of definitions and abbreviations used in this document. + +[#tableid_efinition] +[cols="1,3"] +.List of project-specific definitions and abbreviations +|=== +|Notation |Description + +|len +|length + +|num +|number + +|param +|parameter, parameters + +|rot +|rotation +|=== + +[#tableid_General] +[cols="1,4"] +.List of General Terms +|=== +|Notation |Description + +|IMU +|inertial measurement unit + +|API +|Application Programming Interface +|=== + +=== Related Documents + +<> contains related text from this book. + +[#tableid_RelatedText] +[cols="3,1,1,1"] +.Related Articles +|=== +|Sentence name |Abbreviation |Association type |Description + +|SensorLIB Requirements Document +|None +| +| + +|SensorLIB Framework Feature Specification +| +| +| +|=== + +== System configuration + +=== SW Configuration + +SensorLIB Argo signal processing is a software library that takes sensor data such as IMUs as input and the data processed on that data as output. It is hardware and OS independent. However, in some execution environments, SensorLIB Argo signal processing may call another library for speed. +It can also be used with this library alone, but is intended to be used within the SensorLIB Framework. + +SW configuration for use within SensorLIB Framework + +Frameworks +[#graphid_framework] +[graphviz, format=svg, align=center] +-- +digraph framework { + rankdir=LR + compound=true + sensor0 [shape=box, + label="Sensor"] + sensor1 [shape=box, + label="Sensor"] + output [shape=box, label="Application"] + subgraph cluster0 { + in0 [shape=box, + label="Component"] + in1 [shape=box, + label="Component"] + op0 [shape=box, label="Component"] + in0 -> op0 + in1 -> op0 + style=rounded; + label="Framework"; + } + sensor0 -> in0; + sensor1 -> in1; + op0 -> output; +} +-- +Component internal structure +[#graphid_component] +[graphviz, format=svg, align=center] +SW configuration for use within the .SensorLIB Framework +-- +digraph component { + rankdir=LR + compound=true + subgraph cluster1 { + in2 [shape=box, + label="Input Interface"] + lib [shape=box, + label="SensorLIB Argo Signal Processing"] + output2 [shape=box, label="Output Interface"] + in2 -> lib + lib -> output2 + style=rounded; + label="Component"; + } +} +-- + +=== Resources + +When an error occurs, the variable errno, which has a unique value for each thread, stores the cause of the error. + +== Functional specifications + +=== List of functions + +<> lists the functions. + +[#tableid_Function] +[cols="1,4"] +.List of functions +|=== +|Feature |Overview + +|Calibration +|Calibrate sensor data + +|Multiplexing +|Multiplex sensor data + +|Axis conversion +|Transform the axis of sensor data + +|Posture expression conversion +|Convert posture data to 3-axis rotation + +|Quaternion operation +|Performs an operation on the posture data + +|Filter +|Filter for time series data + +|Resampling +|Resample time series data + +|Statistic +|Calculates the average and variance of data + +|Integral +|Integrate sensor data + +|=== + +=== Basic Operation + +<> to <> Each API described in the function specification has an independent function. When an API is called, it takes sensor data such as IMU as input, outputs the data processed on that data, and returns the processing to the caller. If an error occurs, errno stores the cause of the error. +All APIs are thread-safe. + +== Constant + +=== Common + +==== Status Code + +[#tableid_StatusCode] +[cols="1,1,1"] +.Status code +|=== +|Macro name |Definition |Description + +|ERROR +|-1 +|Error +|=== + +==== Error Codes + +[#tableid_ErrorCode] +[cols="1,1,3"] +.Error code +|=== +|Macro name |Definition |Description + +|EDOM +| +|Parameter value out of range + +|ERANGE +| +|Result value out of range + +|EILSEQ +| +|Bad input byte string +|=== + + +== Structural type + +=== Sensor Data + +==== mossfw_data_v3s_t + +[#tableid_mossfw_data_v3s_t] +[cols="1,1,3"] +.mossfw_data_v3s_t +|=== +|Type |Member name |Description + +|int16_t +|x +|x component of a three-dimensional vector + +|int16_t +|y +|y component of a three-dimensional vector + +|int16_t +|z +|z component of a three-dimensional vector +|=== + +==== mossfw_data_v3f_t + +[#tableid_mossfw_data_v3f_t] +[cols="1,1,3"] +.mossfw_data_v3f_t +|=== +|Type |Member name |Description + +|float +|x +|x component of a three-dimensional vector + +|float +|y +|y component of a three-dimensional vector + +|float +|z +|z component of a three-dimensional vector +|=== + +==== vector3ia_s + +[#tableid_vector3ia_s] +[cols="1,1,3"] +.vector3ia_s +|=== +|Type |Member name |Description + +|int16_t * +|x +|x component of a three-dimensional vector + +|int16_t * +|y +|y component of a three-dimensional vector + +|int16_t * +|z +|z component of a three-dimensional vector +|=== + +==== vector3fa_s + +[#tableid_vector3fa_s] +[cols="1,1,3"] +.vector3fa_s +|=== +|Type |Member name |Description + +|float * +|x +|x component of a three-dimensional vector + +|float * +|y +|y component of a three-dimensional vector + +|float * +|z +|z component of a three-dimensional vector +|=== + +==== mossfw_data_v3ts_t + +[#tableid_mossfw_data_v3ts_t] +[cols="1,1,3"] +.mossfw_data_v3ts_t +|=== +|Type |Member name |Description + +|int16_t +|x +|x component of a three-dimensional vector + +|int16_t +|y +|y component of a three-dimensional vector + +|int16_t +|z +|z component of a three-dimensional vector + +|uint16_t +|t +|Time +|=== + +==== mossfw_data_v3tf_t + +[#tableid_mossfw_data_v3tf_t] +[cols="1,1,3"] +.mossfw_data_v3tf_t +|=== +|Type |Member name |Description + +|float +|x +|x component of a three-dimensional vector + +|float +|y +|y component of a three-dimensional vector + +|float +|z +|z component of a three-dimensional vector + +|uint32_t +|t +|Time +|=== + +==== vector3tia_s + +[#tableid_vector3tia_s] +[cols="1,1,3"] +.vector3tia_s +|=== +|Type |Member name |Description + +|int16_t * +|x +|x component of a three-dimensional vector + +|int16_t * +|y +|y component of a three-dimensional vector + +|int16_t * +|z +|z component of a three-dimensional vector + +|uint16_t * +|t +|Time +|=== + +==== vector3tfa_s + +[#tableid_vector3tfa_s] +[cols="1,1,3"] +.vector3tfa_s +|=== +|Type |Member name |Description + +|float * +|x +|x component of a three-dimensional vector + +|float * +|y +|y component of a three-dimensional vector + +|float * +|z +|z component of a three-dimensional vector + +|uint32_t * +|t +|Time +|=== + +==== mossfw_data_qf_t + +[#tableid_mossfw_data_qf_t] +[cols="1,1,3"] +.mossfw_data_qf_t +|=== +|Type |Member name |Description + +|float +|w +|Quaternion real part + +|float +|x +|i component of the imaginary part of the quaternion + +|float +|y +|the j component of the imaginary part of the quaternion + +|float +|z +|k component of the imaginary part of the quaternion +|=== + +==== mossfw_data_qtf_t + +[#tableid_mossfw_data_qtf_t] +[cols="1,1,3"] +.mossfw_data_qtf_t +|=== +|Type |Member name |Description + +|float +|w +|Quaternion real part + +|float +|x +|i component of the imaginary part of the quaternion + +|float +|y +|the j component of the imaginary part of the quaternion + +|float +|z +|k component of the imaginary part of the quaternion + +|uint32_t +|t +|Time +|=== + +==== sqmatrix3i_s + +[#tableid_sqmatrix3i_s] +[cols="1,1,3"] +.sqmatrix3i_s +|=== +|Type |Member name |Description + +|mossfw_data_v3s_t +|x +|1st row of cubic square matrix + +|mossfw_data_v3s_t +|y +|2nd row of cubic square matrix + +|mossfw_data_v3s_t +|z +|3rd row of a cubic square matrix +|=== + +==== sqmatrix3f_s + +[#tableid_sqmatrix3f_s] +[cols="1,1,3"] +.sqmatrix3f_s +|=== +|Type |Member name |Description + +|mossfw_data_v3f_t +|x +|1st row of cubic square matrix + +|mossfw_data_v3f_t +|y +|2nd row of cubic square matrix + +|mossfw_data_v3f_t +|z +|3rd row of a cubic square matrix +|=== + +=== Parameters + +==== mosscalib_gyrbias_param_s +The structure represents the parameters of mosscalib_gyrbias_param_s. + +|=== +|Type |Member name |Description + +|union +|average +|Upper limit of absolute value of mean value when judging stationary + +|float +|usd +|Upper bound of unbiased standard deviation when judging stationary + +|unsigned int +|num +|Number of data used for one quiesce judgment +|=== + +Use the following union for member average: + +|=== +|Type |Member name |Description + +|float +|f +|Expression as float + +|int16_t +|i +|Representation with type int 16_t +|=== + +==== mosscalib_gravity_param_s + +This structure represents the parameters of mosscalib_gravity. + +|=== +|Type |Member name |Description + +|mossfw_data_v3f_t +|vaxis +|Unit vector representing the axis to match the acceleration + +|mossfw_data_v3f_t +|haxis +|Vector representing horizontal axis of rotation perpendicular to vaxis +|=== + +==== mosscalib_adjust_param_s + +This structure represents the parameters of mosscalib_adjust. + +|=== +|Type |Member name |Description + +|union +|bias +|Bias + +|struct sqmatrix3f_s +|misalignment +|Misalignment + +|struct sqmatrix3f_s +|scalefactor +|Scale factor +|=== + +Use the following union for member bias: + +|=== +|Type |Member name |Description + +|mossfw_data_v3f_t +|f +|Representation with type vector3f + +|mossfw_data_v3s_t +|i +|Representation by type vector3i +|=== + +==== mossdsp_firfilter_param_s + +This structure represents the parameters of firfilter. + +|=== +|Type |Member name |Description + +|union fircoef_u +|coeffients +|Filter factor + +|unsigned int +|cnum +|Number of filter factors + +|union lastdata_u +|lastdata +|Previous input + +|unsigned int +|lnum +|Number of previous inputs + +|uint16_t +|delay +|Delay +|=== + +Use the following union for member fircoef_u: + +|=== +|Type |Member name |Description + +|float * +|f +|Array of type float + +|struct fircoefi_s +|i +|Array of type int 16_t +|=== + +Use the following structure for member fircoefi_s: + +|=== +|Type |Member name |Description + +|int16_t * +|coef +|Filter factor + +|unsigned int +|scale +|Number of decimal bits in the filter factor +|=== + +Use the following union for member lastdata_u: + +|=== +|Type |Member name |Description + +|int16_t * +|i +|Array of type float + +|float +|f +|Array of type int16_t + +|mossfw_data_v3s_t * +|v3i +|Array of type mossfw_data_v3s_t + +|mossfw_data_v3f_t * +|v3f +|Array of type mossfw_data_v3f_t + +|struct vector3ia_s * +|v3ia +|Array of type mossfw_data_v3ts_t + +|struct vector3fa_s * +|v3fa +|Array of type mossfw_data_v3tf_t + +|mossfw_data_v3ts_t * +|v3ti +|Address of a variable of type struct vector3ia_s + +|mossfw_data_v3tf_t * +|v3tf +|Address of a variable of type struct vector3fa_s + +|struct vector3tia_s * +|v3tia +|Address of a variable of type struct vector3tia_s + +|struct vector3tfa_s * +|v3tfa +|Address of a variable of type struct vector3tfa_s + +|mossfw_data_qf_t * +|qf +|Address of a variable of type mossfw_data_qf_t + +|mossfw_data_qtf_t * +|qft +|Address of a variable of type mossfw_data_qtf_t +|=== + +==== mossdsp_iirfilter_param_s + +This structure represents the iirfilter parameters. + +|=== +|Type |Member name |Description + +|union iircoef_u +|coef +|Filter factor + +|union lastdata_u +|fflastdata +|Output just before feedforward + +|unsigned int +|fflnum +|Number of inputs just before feedforward + +|union lastdata_u +|fblastdata +|Output just before feedback + +|unsigned int +|fblnum +|Number of outputs immediately before feedback + +|uint16_t +|delay +|Delay +|=== + + +Use the following union for member iircoef_u: + +|=== +|Type |Member name |Description + +|struct iircoeff_s +|f +|Factor of type float + +|struct iircoefi_s +|i +|Factor of type int +|=== + + +Use the following structure for member iircoeff_s: + +|=== +|Type |Member name |Description + +|float * +|ff +|Feedforward filter factor + +|float * +|fb +|Feedback filter factor + +|unsigned in +|ffnum +|Number of feedforward filter coefficients + +|unsigned in +|fbnum +|Number of feedback filter coefficients +|=== + + +Use the following structure for member iircoefi_s: + +|=== +|Type |Member name |Description + +|int16_t * +|ff +|Feedforward filter factor + +|int16_t * +|fb +|Feedback filter factor + +|unsigned in +|ffnum +|Number of feedforward filter coefficients + +|unsigned in +|fbnum +|Number of feedback filter coefficients + +|unsigned in +|scale +|Scale factor of the filter factor +|=== + +==== mossdsp_decimate_param_s + +This structure represents the parameters of a decimate. + +|=== +|Type |Member name |Description + +|struct mossdsp_iirfilter_param_s +|filterparam +|Filter factor + +|unsigned int +|factor +|Decimation factor + +|unsigned int +|offset +|Output data offset +|=== + +==== mossdsp_interpolate_param_s + +This structure represents the parameters of interpolate. + +|=== +|Type |Member name |Description + +|uint32_t +|t +|Time of output (assumed to be uint16_t when used in interpolate_v3 ti) + +|uint32_t +|t0 +|Time of input in0 (Not used in interpolate_v3ti and interpolate_v3tf) + +|uint32_t +|t1 +|Time of day of input in1 (Not used in interpolate_v3ti and interpolate_v3tf) +|=== + +==== mossdsp_integrategyr_param_s + +This structure represents the parameters of a decimate. + +|=== +|Type |Member name |Description + +|union +|lastout +|Previous output data + +|unsigned long +|dt +|Time interval + +|struct timespec +|res +|When dt1 counts + +|float +|scale_factor +|Magnification when input angular velocity is an integer +|=== + +Use the following union for member lastout: + +|=== +|Type |Member name |Description + +|mossfw_data_qf_t +|f +|Quaternion + +|mossfw_data_qtf_t +|tf +|Time and Quaternion +|=== + +== Function specification + +[[Calibration]] +=== Calibration + +[[mosscalib_gyrbiasv3i]] +==== mosscalib_gyrbiasv3i() + +[Features] + +Generates calibration parameters for angular velocity bias correction values. +Let the input be the three-dimensional vector data of angular velocity at rest asciimath:[g_i=((g_(xi)),(g_(yi)),(g_(zi)))] (i=0,1,2,⋯,mn-1). Let the output be the three-dimensional vector data of bias correction value of angular velocity asciimath:[b_(g0), b_(g1), b_(g2), b_(g3)] and the result of judgment that the data is at rest. Let the parameters be the upper limit c of the absolute value of the mean and the upper limit σ of the standard deviation when determining the resting state. + +Calculate as follows: + +[asciimath] +++++ +b_(g0)=1/(mn)sum_(i=0)^(mn-1)g_i +++++ + +asciimath:[b_(g0),b_(g1),b_(g2),b_(g3)] is 0 because temperature is not taken into account.For the input data of input data asciimath:[g_(mj)] to asciimath:[g_(mj+m-1)] (j=0, 1, ⋯, n-1), if the average value of each vector component is asciimath:[barg_(xj)] , asciimath:[barg_(yj)] , asciimath:[barg_(zj)] and the unbiased standard deviation is asciimath:[barsigma_(xj)] , asciimath:[barsigma_(yj)] , asciimath:[barsigma_(zj)], and if all the following conditions are satisfied for all j and all vector components .ξ(Elements of {x, y, z}), it is judged that the input data is at rest. + +[asciimath] +++++ +|barg_(xii)|leC +++++ + +[asciimath] +++++ +|sigma_(xii)|lesigma +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Three-dimensional vector data of bias-corrected value of angular velocity +|OUT + +|const mossfw_data_v3s_t * +|in +|Three-dimensional vector data of angular velocity at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gyrbias_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gyrbiasv3f() + +[Features] + +Generates calibration parameters for angular velocity bias correction values. + +For details, see <>. + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Three-dimensional vector data of bias-corrected value of angular velocity +|OUT + +|const mossfw_data_v3f_t * +|in +|Three-dimensional vector data of angular velocity at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gyrbias_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gyrbiasv3ia() + +[Features] + +Generates calibration parameters for angular velocity bias correction values. + +For details, see <>. + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Three-dimensional vector data of bias-corrected value of angular velocity +|OUT + +|const struct vector3ia_s * +|in +|Three-dimensional vector data of angular velocity at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gyrbias_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + + +==== mosscalib_gyrbiasv3fa() + +[Features] + +Generates calibration parameters for angular velocity bias correction values. + +For details, see <>. + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Three-dimensional vector data of bias-corrected value of angular velocity +|OUT + +|const struct vector3fa_s * +|in +|Three-dimensional vector data of angular velocity at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gyrbias_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gyrbiasv3ti() + +[Features] + +Generates calibration parameters for angular velocity bias correction values. + +For details, see <>. + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Three-dimensional vector data of bias-corrected value of angular velocity +|OUT + +|mossfw_data_v3ts_t * +|in +|Three-dimensional vector data of angular velocity at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gyrbias_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gyrbiasv3tf() + +[Features] + +Generates calibration parameters for angular velocity bias correction values. + +For details, see <>. + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Three-dimensional vector data of bias-corrected value of angular velocity +|OUT + +|const mossfw_data_v3tf_t * +|in +|Three-dimensional vector data of angular velocity at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gyrbias_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gyrbiasv3tia() + +[Features] + +Generates calibration parameters for angular velocity bias correction values. + +For details, see <>. + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Three-dimensional vector data of bias-corrected value of angular velocity +|OUT + +|const struct vector3tia_s * +|in +|Three-dimensional vector data of angular velocity at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gyrbias_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gyrbiasv3tfa() + +[Features] + +Generates calibration parameters for angular velocity bias correction values. + +For details, see <>. + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Three-dimensional vector data of bias-corrected value of angular velocity +|OUT + +|const struct vector3tfa_s * +|in +|Three-dimensional vector data of angular velocity at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gyrbias_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mosscalib_gravityv3i]] +==== mosscalib_gravityv3i() + +[Features] + +Calibration at rest generates calibration parameters that match the direction of gravity to any axis. +Let the input be the acceleration data at rest asciimath:[a_i]. Let the output be a quaternion q that aligns the direction of gravitational acceleration with the specified axis. Let asciimath:[z=((Z_0), (Z_1), (Z_2))] be the unit vector representing the axis along which the parameter should match the acceleration, and asciimath:[x=((X_0), (X_1), (X_2))] be the vector perpendicular to z and representing the axis of horizontal rotation (see figure). + +image::point_parameter.png[width="30%", align="center", title=Polar Coordinate Parameters] + +Let the average of the input acceleration data be asciimath:[bara]. Let y be the z-axis of rotation and x be the vector rotated asciimath:[pi/2]. + +[asciimath] +++++ +theta=cos^(-1)(baracdotz)/(||bara||) +++++ + +[asciimath] +++++ +phi=sgn(baracdoty)cos^(-1)(baracdotx)/sqrt((baracdotx)^2+(baracdoty)^2) +++++ + +Let asciimath:[q_0] be the quaternion that rotates φ on the z-axis and asciimath:[y^'= barq_0yq_0] be the y-axis after rotation, and let asciimath:[q_1] be the quaternion that rotates θ on the z-axis. + +[asciimath] +++++ +q_0=cosphi/2+Z_0sinphi/2i+Z_1sinphi/2j+Z_2sinphi/2k +++++ + +[asciimath] +++++ +q_1=costheta/2+y_0^'sintheta/2i+y_1^'sintheta/2j+y_2^'sintheta/2k +++++ + +[asciimath] +++++ +q=barq_0barq_1 +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Quaternion to match the direction of gravitational acceleration to the specified axis +|OUT + +|const mossfw_data_v3s_t * +|in +|Acceleration data at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gravity_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gravityv3f() + +[Features] + +Calibration at rest generates calibration parameters that match the direction of gravity to any axis. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Quaternion to match the direction of gravitational acceleration to the specified axis +|OUT + +|const mossfw_data_v3f_t * +|in +|Acceleration data at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gravity_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gravityv3ia() + +[Features] + +Calibration at rest generates calibration parameters that match the direction of gravity to any axis. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Quaternion to match the direction of gravitational acceleration to the specified axis +|OUT + +|const struct vector3ia_s * +|in +|Acceleration data at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gravity_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gravityv3fa() + +[Features] + +Calibration at rest generates calibration parameters that match the direction of gravity to any axis. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Quaternion to match the direction of gravitational acceleration to the specified axis +|OUT + +|const struct vector3fa_s * +|in +|Acceleration data at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gravity_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gravityv3ti() + +[Features] + +Calibration at rest generates calibration parameters that match the direction of gravity to any axis. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Quaternion to match the direction of gravitational acceleration to the specified axis +|OUT + +|mossfw_data_v3ts_t * +|in +|Acceleration data at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gravity_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gravityv3tf() + +[Features] + +Calibration at rest generates calibration parameters that match the direction of gravity to any axis. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Quaternion to match the direction of gravitational acceleration to the specified axis +|OUT + +|const mossfw_data_v3tf_t * +|in +|Acceleration data at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gravity_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gravityv3tia() + +[Features] + +Calibration at rest generates calibration parameters that match the direction of gravity to any axis. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Quaternion to match the direction of gravitational acceleration to the specified axis +|OUT + +|const struct vector3tia_s * +|in +|Acceleration data at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gravity_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_gravityv3tfa() + +[Features] + +Calibration at rest generates calibration parameters that match the direction of gravity to any axis. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Quaternion to match the direction of gravitational acceleration to the specified axis +|OUT + +|const struct vector3tfa_s * +|in +|Acceleration data at rest +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mosscalib_gravity_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mosscalib_adjustv3i]] +==== mosscalib_adjustv3i() + +[Features] + +Calibration parameters are used to adjust the sensor data. +3-D vector data with input at angular velocity g, three-dimensional vector data of acceleration a, and temperature data T. Let the output be three-dimensional vector data g' for angular velocity and three-dimensional vector data a' for acceleration. parameter, σ=a, g i=0,1,2,3 then misalignment +asciimath:[A_sigmai=((1,(a_(sigmai))_(yz),(a_(sigmai))_(zy)),((a_(sigmai))_(xy),1,(a_(sigmai))_(zx)),((a_(sigmai))_(xy),(a_(sigmai))_(yz),1))], scale factor +asciimath:[S_sigmai=(((S_(sigmai))x,0,0),(0,(S_(sigmai))y,0),(0,0,(S_(sigmai))z))] , and the three-dimensional vector of biases asciimath:[b_(sigmai)]. + +The data from the IMU sensor is corrected by the following operations + +asciimath:[a^'=(T^3A_(a3)+T^2A_(a2)+TA_(a1)+A_(a0))(T^3S_(a3)+T^2S_(a2)+TS_(a1)+S_(a0))(a-T^3b_(a3)-T^2b_(a2)-Tb_(a1)-b_(a0))] + +asciimath:[g^'=(T^3A_(g3)+T^2A_(g2)+TA_(g1)+A_(g0))(T^3S_(g3)+T^2S_(g2)+TS_(g1)+S_(g0))(g-T^3b_(g3)-T^2b_(g2)-Tb_(g1)-b_(g0))] + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Three-dimensional vector data +|OUT + +|const mossfw_data_v3s_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|int16_t +|temperature +|Temperature +|IN + +|const struct mosscalib_adjust_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_adjustv3f() + +[Features] + +Calibration parameters are used to adjust the sensor data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Three-dimensional vector data +|OUT + +|const mossfw_data_v3f_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|float +|temperature +|Temperature +|IN + +|const struct mosscalib_adjust_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_adjustv3ia() + +[Features] + +Calibration parameters are used to adjust the sensor data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3ia_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3ia_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|int16_t +|temperature +|Temperature +|IN + +|const struct mosscalib_adjust_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_adjustv3fa() + +[Features] + +Calibration parameters are used to adjust the sensor data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3fa_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3fa_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|float +|temperature +|Temperature +|IN + +|const struct mosscalib_adjust_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_adjustv3ti() + +[Features] + +Calibration parameters are used to adjust the sensor data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3ts_t * +|out +|Three-dimensional vector data +|OUT + +|mossfw_data_v3ts_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|int16_t +|temperature +|Temperature +|IN + +|const struct mosscalib_adjust_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_adjustv3tf() + +[Features] + +Calibration parameters are used to adjust the sensor data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Three-dimensional vector data +|OUT + +|const mossfw_data_v3tf_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|int16_t +|temperature +|Temperature +|IN + +|const struct mosscalib_adjust_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_adjustv3tia() + +[Features] + +Calibration parameters are used to adjust the sensor data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tia_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3tia_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|int16_t +|temperature +|Temperature +|IN + +|const struct mosscalib_adjust_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mosscalib_adjustv3tfa() + +[Features] + +Calibration parameters are used to adjust the sensor data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tfa_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3tfa_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|int16_t +|temperature +|Temperature +|IN + +|const struct mosscalib_adjust_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +=== Multiplexing + +pass:[FIXME] + +pass:[(note) Depending on the Framework specification, this may not be necessary for the Argo signal processing library. ] + + +=== Axis Conversion + +[[mossdsp_transformaxismv3i]] +==== mossdsp_transformaxismv3i() + +[Features] + +Transform the coordinate axes of sensor data by matrix. +Let the input be the three-dimensional vector data asciimath:[x=((x_0), (x_1), (x_2))]. Let the output be the three-dimensional vector data asciimath:[y=((y_0), (y_1), (y_2))]. Let the parameter be a 3x3 transformation matrix T. +Make the following calculation: + +[asciimath] +++++ +y=Tx +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Three-dimensional vector data +|OUT + +|const mossfw_data_v3s_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct sqmatrix3i_s * +|param +|3x3 transformation matrix +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxismv3f() + +[Features] + +Transform the coordinate axes of sensor data by matrix. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Three-dimensional vector data +|OUT + +|const mossfw_data_v3f_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct sqmatrix3f_s * +|param +|3x3 transformation matrix +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxismv3ia() + +[Features] + +Transform the coordinate axes of sensor data by matrix. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3ia_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3ia_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct sqmatrix3i_s * +|param +|3x3 transformation matrix +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxismv3fa() + +[Features] + +Transform the coordinate axes of sensor data by matrix. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3fa_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3fa_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct sqmatrix3f_s * +|param +|3x3 transformation matrix +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxismv3ti() + +[Features] + +Transform the coordinate axes of sensor data by matrix. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3ts_t * +|out +|Three-dimensional vector data +|OUT + +|mossfw_data_v3ts_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct sqmatrix3i_s * +|param +|3x3 transformation matrix +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxismv3tf() + +[Features] + +Transform the coordinate axes of sensor data by matrix. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Three-dimensional vector data +|OUT + +|const mossfw_data_v3tf_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct sqmatrix3f_s * +|param +|3x3 transformation matrix +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxismv3tia() + +[Features] + +Transform the coordinate axes of sensor data by matrix. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tia_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3tia_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct sqmatrix3i_s * +|param +|3x3 transformation matrix +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxismv3tfa() + +[Features] + +Transform the coordinate axes of sensor data by matrix. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tfa_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3tfa_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct sqmatrix3f_s * +|param +|3x3 transformation matrix +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mossdsp_transformaxisqv3f]] +==== mossdsp_transformaxisqv3f() + +[Features] + +Transform the coordinate axes of sensor data by quaternion. +Let the input be three-dimensional vector data asciimath:[x=((x_0),(x_1),(x_2))]. Let the output be three-dimensional vector data asciimath:[x=((y_0),(y_1),(y_2))]. Let the parameter be Quaternion asciimath:[q=q_0+q_1i+q_22j+q_3k] (|q|=1), which represents a coordinate transformation. +With the conjugate asciimath:[x=x_0i+x_1j+x_2k],asciimath:[y=y_0i+y_1j+y_2k] of quaternion asciimath:[barq=q_0-q_1i-q_2j-q_3k], q + +[asciimath] +++++ +y=qxbarq +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Three-dimensional vector data +|OUT + +|const mossfw_data_v3f_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const mossfw_data_qf_t * +|param +|Quaternion representing coordinate transformation +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxisqv3fa() + +[Features] + +Transform the coordinate axes of sensor data by quaternion. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3fa_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3fa_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const mossfw_data_qf_t * +|param +|Quaternion representing coordinate transformation +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxisqv3tf() + +[Features] + +Transform the coordinate axes of sensor data by quaternion. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Three-dimensional vector data +|OUT + +|const mossfw_data_v3tf_t * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const mossfw_data_qf_t * +|param +|Quaternion representing coordinate transformation +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformaxisqv3tfa() + +[Features] + +Transform the coordinate axes of sensor data by quaternion. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tfa_s * +|out +|Three-dimensional vector data +|OUT + +|const struct vector3tfa_s * +|in +|Three-dimensional vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const mossfw_data_qf_t * +|param +|Quaternion representing coordinate transformation +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +=== Postural Expression Conversion + +[[mossdsp_transformqanglesf]] +==== mossdsp_transformqanglesf() + +[Features] + +Convert quaternion posture data to Euler angles. +Let the input be the attitude data asciimath:[q=q_0+q_1i+q2_j+q_3k]. Let the output be an Euler angle asciimath:[R_x,R_y,R_z(R_z\rightarrowR_y\rightarrowR_x)]. + +Make the following calculation: + +[asciimath] +++++ +(R_x,R_y,R_z) = (tan^(-1)(2(q_2q_3+q_0q_1))/(1-2(q_1^2+q_2^2)), -sin^(-1) 2(q_1q_3-q_0q_2), tan^(-1)(q_1q_2+q_0q_3)/(1-2(q_2^2+q_3^2)) ) +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Euler angle +|OUT + +|const mossfw_data_v3tf_t * +|in +|Attitude data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformqanglestf() + +[Features] + +Convert quaternion posture data to Euler angles. +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Euler angle +|OUT + +|const mossfw_data_v3tf_t * +|in +|Attitude data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mossdsp_transformqanglestf]] +==== mossdsp_transformqanglestf() + +[Features] + +Convert Euler angle posture data to quaternions. +Let the input be an Euler angle asciimath:[R_x,R_y,R_z(R_z\rightarrowR_y\rightarrowR_x)]. Let the output be the attitude data asciimath:[q=q_0+q_1i+q_2j+q_3k]. + +Make the following calculation: + +[asciimath] +++++ +q_0=cosR_x/2cosR_y/2cosR_z/2+sinR_x/2sinR_y/2sinR_z/2 +++++ + +[asciimath] +++++ +q_1=sinR_x/2cosR_y/2cosR_z/2-cosR_x/2sinR_y/2sinR_z/2 +++++ + +[asciimath] +++++ +q_2=sinR_x/2cosR_y/2sinR_z/2+cosR_x/2sinR_y/2cosR_z/2 +++++ + +[asciimath] +++++ +q_3=cosR_x/2cosR_y/2sinR_z/2-sinR_x/2sinR_y/2cosR_z/2 +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Attitude data +|OUT + +|const mossfw_data_v3f_t * +|in +|Euler angle +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformanglesf() + +[Features] + +Convert Euler angle posture data to quaternions. +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qtf_t * +|out +|Attitude data +|OUT + +|const mossfw_data_v3tf_t * +|in +|Euler angle +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mossdsp_transformqazimuthf]] +==== mossdsp_transformqazimuthf() + +[Features] + +Convert quaternion posture data to azimuth, pitch, and roll. +Let the input be the attitude data asciimath:[q=q_0+q_1i+q_2j+q_3k]. Let the output be azimuth, pitch, roll. + +matrix +[asciimath] +++++ +A=((q_0^2+q_1^2-q_2^2-q_3^2, 2(q_1q_2+q_0q_3), 2(q_1q_3-q_0q_2)), +(2(q_1q_2-q_0q_3), q_0^2-q_1^2+q_2^2-q_3^2, 2(q_2q_3+q_0q_1)), +(2(q_1q_3+q_0q_2), 2(q_2q_3-q_0q_1), q_0^2-q_1^2-q_2^2+q_3^2)) +++++ +as asciimath:[a_(ij)(i,j=0,1,2)]. +[latexmath] +++++ +(azimuh, pitch, roll)=(tan^{-1}\frac{a_12}{a_22}\ , +tan^{-1}\frac{-a_32}{sgn(a_33)\sqrt{a_12^2+a_22^2}}\ , +sin^{-1}(-a_31) ) +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|azimuth, pitch, roll +|OUT + +|const mossfw_data_qf_t * +|in +|Attitude data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_transformqazimuthtf() + +[Features] + +Convert quaternion posture data to azimuth, pitch, and roll. +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|azimuth, pitch, roll +|OUT + +|const mossfw_data_qtf_t * +|in +|Attitude data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +=== Quaternion Operations + +[[mossdsp_multiplyqf]] +==== mossdsp_multiplyqf() + +[Features] + +Composites posture data. +Let the input be the posture data asciimath:[p=p_0+p_1i+p_2j+p_3k, q=q_0+q_1i+q_2j+q_3k]. Let the output be the synthesized attitude data pq. +Make the following calculation: + +[asciimath] +++++ +pq=(p_0q_0-p_1q_1-p_2q_2-p_3q_3)+(p_1q_0+p_0q_1+p_2q_3-p_3q_2)i+ +(p_0q_2+p_2q_0+p_3q_1-p_1q_3)j+(p_0q_3+p_3q_1+p_1q_2-p_2q_1)k +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Combined posture data +|OUT + +|const mossfw_data_qf_t * +|in0 +|Attitude data +|IN + +|const mossfw_data_qf_t * +|in1 +|Attitude data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_multiplyqtf() + +[Features] + +Composites posture data. +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qtf_t * +|out +|Combined posture data +|OUT + +|const mossfw_data_qtf_t * +|in0 +|Attitude data +|IN + +|const mossfw_data_qtf_t * +|in1 +|Attitude data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mossdsp_conjugateqf]] +==== mossdsp_conjugateqf() + +[Features] + +Find the reverse rotation of the posture data. +Let the input be the attitude data asciimath:[q=q_0+q_1i+q_2j+q_3k]. Let the output be Attitude Data Reverse Rotation asciimath:[barq]. +Make the following calculation: + +[asciimath] +++++ +barq=q_0-q_1i-q_2j-q_3k +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Attitude data reverse rotation +|OUT + +|const mossfw_data_qf_t * +|in +|Attitude data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_conjugateqtf() + +[Features] + +Find the reverse rotation of the posture data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qtf_t * +|out +|Attitude data reverse rotation +|OUT + +|const mossfw_data_qtf_t * +|in +|Attitude data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +=== Filter +[[mossdsp_firfilteri]] +==== mossdsp_firfilteri() + +[Features] + + +FIR filter on time series vector data. +Let the input be equally spaced time series vector data asciimath:[x(t_0-(P-1)Deltat),cdots,x(t_0),x(t_0+Deltatt),cdots,x(t_0+(N-1)Deltatt)]. Let the output be the time series vector data asciimath:[y(t_0-d),y(t_0-d+Deltatt),cdots,y(t_0-d+(N-1)Deltatt)]. Let the parameters be the filter order P (P≥1)), the filter factor asciimath:[A_0,A_1,cdots,A_(P-1)] (diagonal matrix), the delay d, and the number N of data to output. + +Let n=0, 1, 2, ⋯, N -1 and calculate as follows: + +[asciimath] +++++ +y(t_0-d+nDeltat)=sum_(i=0)^(P-1)A_ix(t_0+(n-i)Deltat) +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|int16_t * +|out +|Time series vector data +|OUT + +|const int16_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + + +==== mossdsp_firfilterf() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|float * +|out +|Time series vector data +|OUT + +|const float * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_firfilterv3i() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3s_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_firfilterv3f() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3f_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_firfilterv3ia() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3ia_s * +|out +|Time series vector data +|OUT + +|const struct vector3ia_s * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_firfilterv3fa() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3fa_s * +|out +|Time series vector data +|OUT + +|const struct vector3fa_s * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_firfilterv3ti() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3ts_t * +|out +|Time series vector data +|OUT + +|mossfw_data_v3ts_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_firfilterv3tf() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3tf_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_firfilterv3tia() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tia_s * +|out +|Time series vector data +|OUT + +|const struct vector3tia_s * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_firfilterv3tfa() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tfa_s * +|out +|Time series vector data +|OUT + +|const struct vector3tfa_s * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_firfilter_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mossdsp_iirfilteri]] +==== mossdsp_iirfilteri() + +[Features] + +IIR filter over time series vector data. +Let the input be the equally spaced time series vector data asciimath:[x(t_0-(P-1)Deltat),cdots,x(t_0),x(t_0+Deltat),cdots,x(t_0+(N-1)Deltat)] and the output vector data of the IIR filter asciimath:[y(t-d-QDeltat),cdots,y(t_0-d-Deltat),y(t_0-d)]. Let the output be the time series vector data asciimath:[y(t-d),y(t-d+Deltat),cdots,y(t-d+(N-1)Deltat)]. Let the parameters be the feedforward filter order P (P≥1), the feedforward filter coefficient asciimath:[a_0,a_1,cdots,a_(P-1)], the feedback filter order Q (Q≥1, the feedback filter coefficient asciimath:[b_1,b_1,cdots,b_Q], the delay d, and the number N of data to be output. + +Let n=0, 1, 2, ⋯, N and calculate as follows: + +[asciimath] +++++ +y(t_0-d+nDeltat)=sum_(i=0)^(P-1)a_ix(t_0+(n-i)Deltat)+sum_(i=0)^(Q)b_iy(t_0-d+(n-i)Deltat) +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|int16_t * +|out +|Time series vector data +|OUT + +|const int16_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterf() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|float * +|out +|Time series vector data +|OUT + +|const float * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterv3i() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3s_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterv3f() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3f_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterv3ia() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3ia_s * +|out +|Time series vector data +|OUT + +|const struct vector3ia_s * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterv3fa() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3fa_s * +|out +|Time series vector data +|OUT + +|const struct vector3fa_s * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterv3ti() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3ts_t * +|out +|Time series vector data +|OUT + +|mossfw_data_v3ts_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterv3tf() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3tf_t * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterv3tia() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tia_s * +|out +|Time series vector data +|OUT + +|const struct vector3tia_s * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_iirfilterv3tfa() + +[Features] + +FIR filter on time series vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tfa_s * +|out +|Time series vector data +|OUT + +|const struct vector3tfa_s * +|in +|Equally spaced vector time series data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_iirfilter_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +=== Resampling +[[mossdsp_decimatei]] +==== mossdsp_decimatei() + +[Features] + +Decimate vector data. +Let the inputs be the time series vector data asciimath:[x(t_0-(P-1)Deltat),cdots,x(t_0),x(t_0+Deltat),cdots,x(t_0+MNDeltat)] and the output vector data of the IIR filter asciimath:[y(t-d-QDeltat),cdots,y(t_0-d-Deltat)]. Let the output be the time series vector data asciimath:[y(t_0-d), y(t_0-d+MDeltat),cdots,y(t_0-d+MNDeltat)]. Let the parameters be:Decimation factor M, number of feedforward filter taps P (P≥1, filter factor asciimath:[A_0, A_1,cdots, A_P] (diagonal matrix), feedback filter order Q (Q≥0), feedback filter factor asciimath:[B_1,B_1,cdots,B_Q] (diagonal matrix), delay d, number of output data N. + +Let m=0, 1, 2, ⋯, MN -1 and calculate as follows: + +[asciimath] +++++ +y(t_0-d+mDeltat)=sum_(i=0)^(P-1)A_ix(t_0+(m-i)Deltat)+sum_(i=0)^(Q)B_iy(T_0-d+(m-i)Deltat) +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|int16_t * +|out +|Time series vector data +|OUT + +|const int16_t * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatef() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|float * +|out +|Time series vector data +|OUT + +|const float * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatev3i() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3s_t * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatev3f() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3f_t * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatev3ia() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3ia_s * +|out +|Time series vector data +|OUT + +|const struct vector3ia_s * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatev3fa() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3fa_s * +|out +|Time series vector data +|OUT + +|const struct vector3fa_s * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatev3ti() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3ts_t * +|out +|Time series vector data +|OUT + +|mossfw_data_v3ts_t * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatev3tf() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_v3tf_t * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatev3tia() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tia_s * +|out +|Time series vector data +|OUT + +|const struct vector3tia_s * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimatev3tfa() + +[Features] + +Decimate vector data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|struct vector3tfa_s * +|out +|Time series vector data +|OUT + +|const struct vector3tfa_s * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mossdsp_decimateqf]] +==== mossdsp_decimateqf() + +[Features] + +Decimate the quaternion data. +Let the input be the chronological quaternion data asciimath:[x(t_0-(P-1)Deltat),cdots,x(t_0),x(t_0+Deltat),cdots,x(t_0+MNDeltat)] and the output data asciimath:[y(t-d-QDeltat),cdots,y(t_0-d-Deltat)]. Let the output be the chronological quaternion data asciimath:[y(t_0-d), y(t_0-d+MDeltat),cdots,y(t_0-d+MNDeltat)]. Let the parameters be:Decimation factor M, number of feedforward filter taps P (P≥1), feedforward filter factor asciimath:[a_0,0, a_0,1,cdots, a_(0,P-1),a_1,0, a_1,1,cdots, a_(1,P-1),a_2,0, a_2,1,cdots, a_(2,P-1),a_3,0, a_3,1,cdots, a_(3,P-1)], number of feedback filter taps Q (Q≥0), feedback filter factor asciimath:[b_0,1, b_0,2,cdots, b_(0,Q),b_1,1, b_1,2,cdots, b_(1,Q),b_2,1, b_2,2,cdots, b_(3,Q),b_3,1, b_3,2,cdots, b_(3,Q)], delay d, number of output data N. + +asciimath:[x(t)=x_0 (t)+x_1 (t)i+x_2 (t)j+x_3(t)k, y(t)=y_0 (t)+y_1 (t)i+y_2 (t)j+y_3 (t)k, m=0, 1, 2,cdots,MN-1] as follows: + +[asciimath] +++++ +y(t_0-d+mDeltat)=sum_(i=0)^(P-1)(a_(0,l) x_0 (t_0+(m-l)Deltat)+a_(1,l) x_1 (t_0+(m-l) Deltat)i+a_(2,l) x_2 (t_0+(m-l)Deltat)j+a_(3,l) x_3 (t_0+(m-l)Deltat)k) +++++ +[asciimath] +++++ ++ +sum_(i=0)^(Q)(b_(0,l) y_0 (t_0-d+(m-l)Deltat)+b_(1,l) y_1 (t_0-d+(m-l) Deltat)i+b_(2,l) y_2 (t_0-d+(m-l)Deltat)j+b_(3,l) y_3 (t_0-d+(m-l) Deltat)k) +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_qf_t * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_decimateqtf() + +[Features] + +Decimate the quaternion data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Time series vector data +|OUT + +|const mossfw_data_qf_t * +|in +|Time series vector data +|IN + +|unsigned int +|num +|Number of input data +|IN + +|struct mossdsp_decimate_param_s * +|param +|Parameters +|IN/OUT +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mossdsp_interpolatei]] +==== mossdsp_interpolatei() + +[Features] + +Interpolates vector data to change the period of the data. +Let the input be two sets of vector data asciimath:[x(t_i),x(t_(i+1))] and the time of the data to be output asciimath:[t(t_i≤t≤t_(i+1))]. Let the output be the vector data x(t). +Finds a value by linear interpolation over time. + +[asciimath] +++++ +x(t)=(t_(i+1)-t)/(t_(i+1)-t_i ) x(t_i )+(t-t_i)/(t_(i+1)-t_i ) x(t_(i+1)) +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|int16_t +|in0 +|Input data at time t0 +|IN + +|int16_t +|in1 +|Input data at time t1 +|IN + +|const struct mossdsp_interpolate_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Output data +|=== + +==== mossdsp_interpolatef() + +[Features] + +Interpolates vector data to change the period of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|float +|in0 +|Input data at time t0 +|IN + +|float +|in1 +|Input data at time t1 +|IN + +|const struct mossdsp_interpolate_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Output data +|=== + +==== mossdsp_interpolatev3i() + +[Features] + +Interpolates vector data to change the period of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Output data +|OUT + +|const mossfw_data_v3s_t * +|in0 +|Input data at time t0 +|IN + +|const mossfw_data_v3s_t * +|in1 +|Input data at time t1 +|IN + +|const struct mossdsp_interpolate_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Output data +|=== + +==== mossdsp_interpolatev3f() + +[Features] + +Interpolates vector data to change the period of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Output data +|OUT + +|const mossfw_data_v3f_t * +|in0 +|Input data at time t0 +|IN + +|const mossfw_data_v3f_t * +|in1 +|Input data at time t1 +|IN + +|const struct mossdsp_interpolate_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Output data +|=== + +==== mossdsp_interpolatev3ti() + +[Features] + +Interpolates vector data to change the period of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3ts_t * +|out +|Output data +|OUT + +|mossfw_data_v3ts_t * +|in0 +|Input data at time t0 +|IN + +|mossfw_data_v3ts_t * +|in1 +|Input data at time t1 +|IN + +|const struct mossdsp_interpolate_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Output data +|=== + +==== mossdsp_interpolatev3tf() + +[Features] + +Interpolates vector data to change the period of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3tf_t * +|out +|Output data +|OUT + +|const mossfw_data_v3tf_t * +|in0 +|Input data at time t0 +|IN + +|const mossfw_data_v3tf_t * +|in1 +|Input data at time t1 +|IN + +|const struct mossdsp_interpolate_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Output data +|=== + +[[mossdsp_interpolateqf]] +==== mossdsp_interpolateqf() + +[Features] + +Interpolates the quaternion data to change the period of the data. +We input two sets of quaternion data and the time asciimath:[(t_i,q(t_i) ),(t_(i+1), q(t_(i+1))) (t_i≤t_(i+1))], and the time of the data to be output asciimath:[t(t_i≤t≤t_(i+1))]. Let the output be the quaternion data q(t) at time t. +Let the quaternion representing the posture be q=a+bi+cj+d, and define the inner product of the quaternion as q DW q⋅q'=aa'+bb'+cc'+dd'. And put asciimath:[theta=arccos(|q(t_i )cdotq(t_(i+1))|)] on the input. + +when asciimath:[|q(t_i )cdotq(t_(i+1))|≤0.95] + +[asciimath] +++++ +q(t)=1/sintheta(q(t_i ) sin((t_(i+1)-t)/(t_(i+1)-t_i ) theta)+(q(t_i )cdotq(t_(i+1)))/|q(t_i )cdotq(t_(i+1))| q(t_(i+1))sin((t-t_i)/(t_(i+1)-t_i ) theta) ) +++++ +when asciimath:[|q(t_i )cdotq(t_(i+1))|>0.95] +[asciimath] +++++ +q(t)=(t_(i+1)-t)/(t_(i+1)-t_i ) q(t_i )+(q(t_i )cdotq(t_(i+1)))/|q(t_i )cdotq(t_(i+1))| codt(t-t_i)/(t_(i+1)-t_i ) q(t_(i+1) ) +++++ +(note) The calculation is a linear interpolation of the angle formed by the two quaternions. + + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Output data +|OUT + +|const mossfw_data_qf_t * +|in0 +|Input data at time t0 +|IN + +|const mossfw_data_qf_t * +|in1 +|Input data at time t1 +|IN + +|const struct mossdsp_interpolate_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Output data +|=== + +==== mossdsp_interpolateqtf() + +[Features] + +Interpolates vector data to change the period of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qtf_t * +|out +|Output data +|OUT + +|const mossfw_data_qtf_t * +|in0 +|Input data at time t0 +|IN + +|const mossfw_data_qtf_t * +|in1 +|Input data at time t1 +|IN + +|const struct mossdsp_interpolate_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Output data +|=== + +=== Statistics +[[mossdsp_averagei]] +==== mossdsp_averagei() + +[Features] + +Calculates the average of the data. +Let the input be the vector data asciimath:[x_0,x_1,cdots,x_(n-1)]. Let the output be the mean value x. + +Make the following calculation: + +[asciimath] +++++ +x=1/(n)sum_(i=0)^(n-1)x_i +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|const int16_t * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Average +|=== + +==== mossdsp_averagef() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|const float * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Average +|=== + +==== mossdsp_averagev3i() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Average +|OUT + +|const mossfw_data_v3s_t * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_averagev3f() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Average +|OUT + +|const mossfw_data_v3f_t * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_averagev3ia() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Average +|OUT + +|const struct vector3ia_s * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_averagev3fa() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Average +|OUT + +|const struct vector3fa_s * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_averagev3ti() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Average +|OUT + +|mossfw_data_v3ts_t * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_averagev3tf() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Average +|OUT + +|const mossfw_data_v3tf_t * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_averagev3tia() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3s_t * +|out +|Average +|OUT + +|const struct vector3tia_s * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_averagev3tfa() + +[Features] + +Calculates the average of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_v3f_t * +|out +|Average +|OUT + +|const struct vector3tfa_s * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[[mossdsp_variancei]] +==== mossdsp_variancei() + +[Features] + +Calculates the variance of the data. +Let the input be data asciimath:[x_0,x_1,cdots,x_(n-1)]. Let the output be distributed asciimath:[sigma^2]. + +Make the following calculation: + +[asciimath] +++++ +x=1/nsum_(i=0)^(n-1)x_i +++++ +[asciimath] +++++ +sigma^2=1/nsum_(i=0)^(n-1)(x_i-x)^2 +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|const int16_t * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Variance +|=== + +==== mossdsp_variancef() + +[Features] + +Calculates the variance of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|const float * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|float +|Variance +|=== + +[[mossdsp_unbiasedsdi]] +==== mossdsp_unbiasedsdi() + +[Features] + +Calculates the unbiased standard deviation of the data. +Let the input be data asciimath:[x_0,x_1,cdots,x_(n-1)]. Let the output be an unbiased standard deviation ν +Make the following calculation: + +[asciimath] +++++ +x=1/nsum_(i=0)^(n-1)x_i +++++ +[asciimath] +++++ +upsilon=sqrt(1/(n-1)sum_(i=0)^(n-1)(x_i-x)^2) +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|const int16_t * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|int16_t +|Unbiased standard deviation +|=== + +==== mossdsp_unbiasedsdf() + +[Features] + +Calculates the unbiased standard deviation of the data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|const float * +|in +|Input data +|IN + +|unsigned int +|num +|Number of input data +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|float +|Unbiased standard deviation +|=== + +[[Integral]] +=== Integral +[[mossdsp_integrategyrv3i]] +==== mossdsp_integrategyrv3i() + +[Features] + +Integrates angular velocity data. + +Let the input be an angular velocity at time t as asciimath:[g_x (t),g_y (t), g_z (t)], a ∆t at time, and an attitude asciimath:[q(t-Deltat)=q_0 (t-Deltat)+q_1 (t-Deltat)i+q_1 (t-Deltat)j+q_2 (t-Deltat)k] at time ∆t. +Let the output be posture asciimath:[q(t)=q_0 (t)+q_1 (t)i+q_1 (t)j+q_2 (t)k] at time t. + +asciimath:[qprime(t)=qprime_0 (t)+qprime_1 (t)i+qprime_1 (t)j+qprime_2 (t)k] is determined as follows, and its value is normalized to q(t). + +[latexmath] +++++ +\begin{pmatrix} +q'_0(t) \\ +q'_1(t) \\ +q'_2(t) \\ +q'_3(t) \\ +\end{pmatrix} += +\begin{pmatrix} +\begin{pmatrix} +1 & 0 & 0 & 0\\ +0 & 1 & 0 & 0\\ +0 & 0 & 1 & 0\\ +0 & 0 & 0 & 1\\ +\end{pmatrix} ++\frac{1}{2}\Delta t +\begin{pmatrix} +0 & -g_x(t) & -g_y(t) & -g_z(t)\\ + g_x(t) & 0 & g_z(t) & -g_y(t)\\ + g_y(t) & -g_z(t) & 0 & g_x(t)\\ + g_z(t) & g_y(t) & -g_x(t) & 0\\ +\end{pmatrix} +\end{pmatrix} +\begin{pmatrix} +q_0(t-\Delta t) \\ +q_1(t-\Delta t) \\ +q_2(t-\Delta t) \\ +q_3(t-\Delta t) +\end{pmatrix} +++++ + +[latexmath] +++++ +q(t)=\frac{q'(t)}{|q'(t)|} +++++ + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Posture +|OUT + +|const mossfw_data_v3s_t * +|in +|Angular velocity +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_integrategyr_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_integrategyrv3f() + +[Features] + +Integrates angular velocity data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Posture +|OUT + +|const mossfw_data_v3f_t * +|in +|Angular velocity +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_integrategyr_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_integrategyrv3ia() + +[Features] + +Integrates angular velocity data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Posture +|OUT + +|const struct vector3ia_s * +|in +|Angular velocity +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_integrategyr_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_integrategyrv3fa() + +[Features] + +Integrates angular velocity data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Posture +|OUT + +|const struct vector3fa_s * +|in +|Angular velocity +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_integrategyr_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_integrategyrv3ti() + +[Features] + +Integrates angular velocity data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Posture +|OUT + +|mossfw_data_v3ts_t * +|in +|Angular velocity +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_integrategyr_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_integrategyrv3tf() + +[Features] + +Integrates angular velocity data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Posture +|OUT + +|const mossfw_data_v3tf_t * +|in +|Angular velocity +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_integrategyr_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_integrategyrv3tia() + +[Features] + +Integrates angular velocity data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Posture +|OUT + +|const struct vector3tia_s * +|in +|Angular velocity +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_integrategyr_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +==== mossdsp_integrategyrv3tfa() + +[Features] + +Integrates angular velocity data. + +For details, see <>. + +[Argument] + +[cols="3,1,5,1"] + +|=== +|Type |Argument Name |Description |IN/OUT + +|mossfw_data_qf_t * +|out +|Posture +|OUT + +|const struct vector3tfa_s * +|in +|Angular velocity +|IN + +|unsigned int +|num +|Number of input data +|IN + +|const struct mossdsp_integrategyr_param_s * +|param +|Parameters +|IN +|=== + +[Return value] + + +|=== +|Return value |Description + +|0 +|Normal termination + +|Other +|Error +|=== + +[Return value] + +None + +== Appendix +=== SensorLIB library API creation policy +The SensorLIB Argo Signal Processing C API was created along the following lines:+ + +. C functions are written according to feature specifications +. Use a specific data type and provide multiple copies of the same function for each data type +. The parameters of each function define a structure to avoid having too many arguments to the function +. The function arguments are first at the address where the output is stored, then at the address where the input data is stored, followed by the parameter +. For the return value of the function: +.. Functions whose output is a scalar return a value indicating the output or error in the return value, with details of the error stored in errno. +.. Functions whose output is an array or structure return an error with return and output to the address given in the first argument + +The following policy is tentative. As soon as the policy is decided, it will be reflected in the API specification. + +. API, Structure Naming Policy + + +:xrefstyle:short + +:sectnums!: +== Revision history + +[cols="1,1,5"] +|=== +|Version |Date |Description + +|1.0.0 +|2023-03-07 +|New + +|=== diff --git a/markup/math/var_982761.qmd b/markup/math/var_982761.qmd new file mode 100644 index 0000000..efda0ec --- /dev/null +++ b/markup/math/var_982761.qmd @@ -0,0 +1,438 @@ +--- +title: 変分法 +--- + +変分法は @Sasaki:1958 により、物理法則による拘束を課す解析手法として提案され、@Talagrand-Courtier:1987 に制御理論に基づく理論的な裏付けがされている。 +@Lorenc:1986 は、数値天気予報における様々な解析手法を比較し、変分法がベイズ推定から導かれることを指摘している。 +ここでは、@Tsuyuki-Miyoshi:2007 に基づいて、変分法データ同化について述べる。 + +## 3次元変分法 + +3次元変分法同化(3DVar: three-dimensional variational assimilation)は、第一推定値$\mathbf{x}^\mathrm{f}$及び観測$\mathbf{y}^\mathrm{o}$が与えらたときに、後験pdfを最大化するものを解析値$\mathbf{x}^\mathrm{a}$とする。 + +$$ +\DeclareMathOperator*{\argmax}{arg max} +\begin{aligned} +\mathbf{x}^\mathrm{a} &= \argmax_\mathbf{x}[p(\mathbf{x}|\mathbf{x}^\mathrm{f},\,\mathbf{y}^\mathrm{o})]\\ +&=\argmax_\mathbf{x}[p(\mathbf{x}^\mathrm{f}|\mathbf{x})p(\mathbf{y}^\mathrm{o}|\mathbf{x})p(\mathbf{x})] +\end{aligned} +$$ {#eq-var-3dvar-map} +ガウス型のpdfを仮定し、負の対数pdfでコスト函数$J(\mathbf{x})$を定義すると、 +$$ +J(\mathbf{x}) = \frac{1}{2}(\mathbf{x}-\mathbf{x}^\mathrm{f})^\mathrm{T}\mathbf{B}^{-1}(\mathbf{x}-\mathbf{x}^\mathrm{f}) + \frac{1}{2}(h(\mathbf{x})-\mathbf{y}^\mathrm{o})^\mathrm{T}\mathbf{R}^{-1}(h(\mathbf{x})-\mathbf{y}^\mathrm{o}) + J_\mathrm{c}(\mathbf{x}) +$$ {#eq-var-3dvar-J} +となる。 +ここで、$\mathbf{B},\,\mathbf{R}$はそれぞれ背景及び観測誤差共分散行列、$h(\mathbf{x})$は状態変数を観測変数に変換する観測演算子である。 +式(@eq-var-3dvar-J)の右辺第一、二項はそれぞれ第一推定値、観測値からのずれを表す。 +式(@eq-var-3dvar-J)の右辺第三項は、式(@eq-var-3dvar-map)の右辺第三項に対応し、制約項と呼ばれている。 + +3DVarでは、数値最適化により$J(\mathbf{x})$の最小値として解析値$\mathbf{x}^\mathrm{a}$を求める。 +$h(\mathbf{x})$の接線型演算子を$\mathbf{H}$で表すと、制約項を無視した解析値は +$$ +\mathbf{x}^\mathrm{a} = \mathbf{x}^\mathrm{f} + (\mathbf{B}^{-1} + \mathbf{H}^\mathrm{T}\mathbf{R}^{-1}\mathbf{H})^\mathrm{-1}\mathbf{H}^\mathrm{T}\mathbf{R}^{-1}[\mathbf{y}^\mathrm{o} - h(\mathbf{x}^\mathrm{f})] +$$ {#eq-var-3dvar-analysis} +となる。 + +## 4次元変分法 + +4次元変分法同化(4DVar: four-dimensional variational assimilation)では、同化窓と呼ばれる期間に対するMAP推定を行う。 +時刻レベル$i-1$から$i$までの数値モデルによる予報を +$$ +\mathbf{x}_i = M_{i-1,i}(\mathbf{x}_{i-1})\;i=1,\dots,n +$$ {#eq-4dvar-model} +で表す。 +4DVarのコスト函数は +$$ +J(\mathbf{x_0}) = \frac{1}{2}(\mathbf{x}_0-\mathbf{x}_0^\mathrm{f})^\mathrm{T}\mathbf{B}^{-1}(\mathbf{x}_0-\mathbf{x}_0^\mathrm{f}) + \frac{1}{2}\sum_{i=0}^n(h_i(\mathbf{x}_i)-\mathbf{y}_i^\mathrm{o})^\mathrm{T}\mathbf{R}_i^{-1}(h_i(\mathbf{x}_i)-\mathbf{y}_i^\mathrm{o}) + J_\mathrm{c}(\mathbf{x}_0,\dots,\mathbf{x}_n) +$$ {#eq-var-4dvar-J} +で表される。 +予報誤差共分散は、同化窓内において$M$の接線型演算子$\mathbf{M}$で時間発展し、解析値は式(@eq-var-3dvar-analysis)の$\mathbf{B}$を$\mathbf{M}^\mathrm{T}\mathbf{BM}$で置き換えたものとなる。 + +4DVarでは、解析値を効率的に求めるために、$J(\mathbf{x_0})$の勾配を用いた最適化を用いる[@Talagrand-Courtier:1987]。 +初期値$\mathbf{x}_0$に対する勾配 +$$ +\mathbf{p}_0 = \nabla_{\mathbf{x}_0}J(\mathbf{x}_0) +$$ {#eq-var-4dvar-nablaJ} +を随伴方程式を用いて求める。 +随伴変数$\mathbf{p}_{n+1} = \mathbf{0}$を初期値として、時間逆向きに +$$ +\mathbf{p}_i = \mathbf{M}_i^\mathrm{T}\mathbf{p}_{i+1} + \frac{\partial J}{\partial\mathbf{x}_i}\;i=n,\dots,0 +$$ {#eq-var-4dvar-adj} +右辺第一項は、接線型モデル$\mathbf{M}_i^\mathrm{T}$で一つ前の時間レベルまで、随伴変数を積分すること表している。 +以下に随伴モデルの作り方を示す。 + +## 随伴モデル + +次の形の常微分方程式を考える。 + +$$ +\frac{\mathrm{d}\mathbf{w}}{\mathrm{d}t} = N(\mathbf{w}) + \mathbf{Lw} + \mathbf{f} +$$ {#eq-adj-ode} + +状態変数を$\mathbf{w}$、非線型項を$N(\mathbf{w})$、線型項を$\mathbf{Lw}$、強制を$\mathbf{f}$で表している。 +状態変数に摂動を与えた$\mathbf{w}+\delta\mathbf{w}$を(@eq-adj-ode)に代入し、摂動の時間発展$\mathrm{d}\delta\mathbf{w}/\mathrm{d}t=\mathrm{d}(\mathbf{w}+\delta\mathbf{w})/\mathrm{d}t-\mathrm{d}\mathbf{w}/\mathrm{d}t$を求めると接線型モデル(TLM: tangent linear model)が得られる。 + +$$ +\frac{\mathrm{d}\delta\mathbf{w}}{\mathrm{d}t} = \left(\left.\frac{\partial N}{\partial\mathbf{w}}\right|_\mathbf{w} + \mathbf{L}\right)\delta\mathbf{w} +$$ {#eq-adj-tl} +ここで、摂動$\delta\mathbf{w}$が微小であると仮定し、その二次以上の項を無視した。 +強制項$\mathbf{f}$はTLMにはない。 + +$\partial N/\partial\mathbf{w}|_\mathbf{w} + \mathbf{L}$を改めて$\mathbf{L}$と置き、入力$\delta\mathbf{w}$及び出力$\dot{\delta\mathbf{w}}=\mathrm{d}\delta\mathbf{w}/\mathrm{d}t$を縦に並べたベクトルを用いて行列形式で表す。 + +$$ +\begin{bmatrix} +\delta\mathbf{w}\\ +\dot{\delta\mathbf{w}} +\end{bmatrix} = +\begin{bmatrix} +\mathbf{I} & \mathbf{0}\\ +\mathbf{L} & \mathbf{0} +\end{bmatrix} \begin{bmatrix} +\delta\mathbf{w}\\ +\dot{\delta\mathbf{w}} +\end{bmatrix} +$$ {#eq-adj-tl-matrix} +つまり +$$ +\begin{aligned} +\delta\mathbf{w} &= \delta\mathbf{w}\\ +\dot{\delta\mathbf{w}} &= \mathbf{L}\delta\mathbf{w} +\end{aligned} +$$ +である。 +随伴変数を$\mathbf{w}^\mathrm{a}$とすると、(@eq-adj-tl-matrix)の随伴モデル(ADM, adjoint model)は +$$ +\begin{bmatrix} +\mathbf{w}^\mathrm{a}\\ +\dot{\mathbf{w}}^\mathrm{a} +\end{bmatrix} = +\begin{bmatrix} +\mathbf{I} & \mathbf{L}^\mathrm{T}\\ +\mathbf{0} & \mathbf{0} +\end{bmatrix} \begin{bmatrix} +\mathbf{w}^\mathrm{a}\\ +\dot{\mathbf{w}}^\mathrm{a} +\end{bmatrix} +$$ {#eq-adj-adjoint} +と表すことができる。 +すなわち、 +$$ +\begin{aligned} +\mathbf{w}^\mathrm{a} &= \mathbf{w}^\mathrm{a} + \mathbf{L}^\mathrm{T}\dot{\mathbf{w}}^\mathrm{a}\\ +\dot{\mathbf{w}}^\mathrm{a} &= \mathbf{0} +\end{aligned} +$$ +である。 +$\dot{\mathbf{w}}^\mathrm{a} = \mathbf{0}$もADMの一部であり、忘れるとバグの原因となりうる。 + +## 随伴モデルの作成 + +上述のように、TLMが行列$\mathbf{L}$で表せる場合は、ADMはその転置$\mathbf{L}^\mathrm{T}$を取ればよい。 +明示的に行列で表さなくても、TLMのソースコードを行毎に逆順にたどりながらADMを作成することもできる。 +ここでは、後で用いる、いくつかの簡単な操作に対する随伴を求める。 + +### 代入 + +代入$A=B$の接線型は +$$ +\begin{bmatrix} +\delta B \\ \delta A +\end{bmatrix}= +\begin{bmatrix} +1 & 0 \\ 1 & 0 +\end{bmatrix} +\begin{bmatrix} +\delta B \\ \delta A +\end{bmatrix} +$$ {#eq-adj-copy-tl} +で、その随伴は +$$ +\begin{bmatrix} +B^\mathrm{a} \\ A^\mathrm{a} +\end{bmatrix}= +\begin{bmatrix} +1 & 1 \\ 0 & 0 +\end{bmatrix} +\begin{bmatrix} +B^\mathrm{a} \\ A^\mathrm{a} +\end{bmatrix} +$$ {#eq-adj-copy-ad} +つまり +$$ +\begin{aligned} +B^\mathrm{a} &= A^\mathrm{a} + B^\mathrm{a}\\ +A^\mathrm{a} &=0 +\end{aligned} +$$ +である。 + + +### 係数を掛けて和を取る操作 + +代入$C = \alpha A + \beta B + \gamma D$の接線型は +$$ +\begin{bmatrix} +\delta A\\ \delta B \\ \delta D \\ \delta C +\end{bmatrix} = +\begin{bmatrix} +1 & 0 & 0 & 0\\ +0 & 1 & 0 & 0\\ +0 & 0 & 1 & 0\\ +\alpha & \beta & \gamma & 0 +\end{bmatrix} +\begin{bmatrix} +\delta A\\ \delta B \\ \delta D \\ \delta C +\end{bmatrix} +$$ {#eq-adj-coeff-tl} +で、その随伴は +$$ +\begin{bmatrix} +A^\mathrm{a} \\ B^\mathrm{a} \\ D^\mathrm{a} \\ C^\mathrm{a} +\end{bmatrix} = +\begin{bmatrix} +1 & 0 & 0 & \alpha\\ +0 & 1 & 0 & \beta\\ +0 & 0 & 1 & \gamma\\ +0 & 0 & 0 & 0 +\end{bmatrix} +\begin{bmatrix} +A^\mathrm{a} \\ B^\mathrm{a} \\ D^\mathrm{a} \\ C^\mathrm{a} +\end{bmatrix} +$$ {#eq-adj-coeff-ad} +つまり +$$ +\begin{aligned} +A^\mathrm{a} &= A^\mathrm{a} + \alpha C^\mathrm{a} \\ +B^\mathrm{a} &= B^\mathrm{a} + \beta C^\mathrm{a} \\ +D^\mathrm{a} &= D^\mathrm{a} + \gamma C^\mathrm{a} \\ +C^\mathrm{a} &=0 +\end{aligned} +$$ +である。 + +### ループ + +TLMの最後の行から逆順にADMを作る。 +ループは添字を逆に回す。 +$i = 1, 2, \cdots, m,\,1\le j \le m$に対して + +$$ +\delta x_j = c_1\delta x_1 + c_2\delta x_2 + \cdots + c_ix_i + \cdots + c_m\delta x_m +$$ {#eq-adj-loop-tl} + +の随伴は + +$$ +\begin{aligned} + x_m^\mathrm{a} &= x_m^\mathrm{a} + c_m x_j^\mathrm{a}\\ + & \vdots \\ + x_i^\mathrm{a} &= x_i^\mathrm{a} + c_i x_j^\mathrm{a}\\ + & \vdots \\ + x_2^\mathrm{a} &= x_2^\mathrm{a} + c_2 x_j^\mathrm{a}\\ + x_1^\mathrm{a} &= x_1^\mathrm{a} + c_1 x_j^\mathrm{a}\\ + x_j^\mathrm{a} &= c_j x_j^\mathrm{a} +\end{aligned} +$$ {#eq-adj-loop-ad} + +TLMの行の右辺に現れる摂動変数$\delta x_i$に対応して、ADMの行では随伴変数$x_i^\mathrm{a}$が左辺に現れる。 +$x_i^\mathrm{a}$には$x_i^\mathrm{a}$自身に係数$c_i$とTLMの左辺に現れる摂動変数の随伴$x_j^\mathrm{a}$との積を加えたものになる。 +左辺の変数と右辺の変数が場所が入れ替わっている。 +$x_j^\mathrm{a}$は最後に現れる。 +$c_j=0$の場合のように、TLMの右辺に$x_j^\mathrm{a}$がない場合でも、$x_j^\mathrm{a}$に0を割り当てないと、他の部分でエラーを引き起こしうる。 + +ADMにおける変分演算は、微分演算とは異なり、ある時刻における状態ベクトル全体に対する摂動なので、状態ベクトルの一部が変化しないからといって、それを省略したものはADMとしては正しくない。 + +## Lorenz-96モデル + +Lorenz-96モデル[@Lorenz-Emanuel:1998] +$$ +\frac{\mathrm{d}X_i}{\mathrm{d}t} = (X_{i+1} - X_{i-2})X_{i-1} - X_i + F +$$ {#eq-adj-l96} +のTLMとADMを作る。 +非線型項を$N(X)=(X_{i+1} - X_{i-2})X_{i-1}$を線型化するには、掛け算の一方を順に摂動に置き換えるか、 +$$ +\begin{aligned} +\frac{\partial N}{\partial X_{i-2}} &= -X_{i-1}\\ +\frac{\partial N}{\partial X_{i-1}} &= X_{i+1}-X_{i-2}\\ +\frac{\partial N}{\partial X_{i-2}} &= X_{i-1} +\end{aligned} +$$ {#eq-adj-l96-dN} +のように微分を計算すれば、次のように求められる。 +$$ +\frac{\mathrm{d}\delta X_i}{\mathrm{d}t} = -X_{i-1}\delta X_{i-2} + (X_{i+1} - X_{i-2})\delta X_{i-1} + X_{i-1}\delta X_{i+1} - \delta X_i +$$ {#eq-adj-l96-tl} + +(@eq-adj-adjoint)に基づいて、随伴モデルを作る。 +(@eq-adj-l96-tl)の右辺が表す$\mathbf{L}$の随伴$\mathbf{L}^\mathrm{T}$は、$\delta X$の添字が$i$となる行における係数を考えればよい。 +右辺第1、2、3項の$\delta X_{i-2},\,\delta X_{i-1},\,\delta X_{i+1}$なので、それぞれ$+2,\,+1,\,-1$加えれば$i$行目になる。 +さらに、左辺の変数(時間微分)と右辺の変数を入れ替え$\mathbf{L}^\mathrm{T}\dot{\mathbf{w}}^\mathrm{a}$が得られる。 + +L96の随伴モデルを書き下すと +$$ +X_i^\mathrm{a} = X_i^\mathrm{a} - X_{i+1}\frac{\mathrm{d}X_{i+2}^\mathrm{a}}{\mathrm{d}t} + (X_{i+2} -X_{i-1})\frac{\mathrm{d}X_{i+1}^\mathrm{a}}{\mathrm{d}t} ++X_{i-2}\frac{\mathrm{d}X_{i-1}^\mathrm{a}}{\mathrm{d}t} - \frac{\mathrm{d}X_{i}^\mathrm{a}}{\mathrm{d}t}\\ +$$ {#eq-adj-l96-ad} +及び +$$ +\frac{\mathrm{d}X_{i}^\mathrm{a}}{\mathrm{d}t} = 0 +$$ +となる。 + +## 4次のRunge-Kutta法 + +$$ +\dot{y} = f(t, y) +$$ {#eq-adj-rk4-ode} + +を4次のRunge-Kutta(RK4)法で積分する。 +$$ +\begin{aligned} + y_{n+1} &= y_{n} + \frac{h}{6}(k_1 + 2k_2 + 2k_3 + k_4) \\ + k_1 &= f(t_n,\,y_n) \\ + k_2 &= f\left(t_n + \frac{h}{2},\,y_n + \frac{h}{2}k_1\right) \\ + k_3 &= f\left(t_n + \frac{h}{2},\,y_n + \frac{h}{2}k_2\right) \\ + k_4 &= f(t_n + h,\,y_n + hk_3) \\ +\end{aligned} +$$ {#eq-adj-rk4-k} + +$k$の係数はButcherの表[@Butcher-Wanner:1996] +$$ +\begin{array}{c|c} +\mathbf{c} &\mathbf{A}\\ +\hline + & \mathbf{b}^\mathrm{T} +\end{array} +$$ {#eq-adj-butcher} +に整理できる。 +$s$次の陽的Runge-Kutta法は +$$ +\begin{aligned} +y_{n+1} &= y_n + h\sum_{i=1}^sb_ik_i\\ +k_i &=f(t_n+c_ih, y_n+ h\sum_{j=1}^{i-1}a_{ij}k_j) +\end{aligned} +$$ +と書ける。 +$\mathbf{A}$は対角成分が0である下三角行列になる。 + +RK4に対するButcherの表は次のようになる。 +$$ +\begin{array}{c|ccccc} +0 \\ +1/2 & 1/2\\ +1/2 & 0 & 1/2\\ +1 & 0 & 0 & 1\\ +\hline + & 1/6 & 1/3 & 1/3 & 1/6 +\end{array} +$$ {#eq-adj-buther-rk4} + +RK4の接線型は次の通りである。 +$$ +\begin{aligned} + \delta y_{n+1} &= \delta y_{n} + \frac{h}{6}(\delta k_1 + 2\delta k_2 + 2\delta k_3 + \delta k_4) \\ + \delta k_1 &= \delta f(t_n,\,y_n,\,\delta y_n) \\ + \delta k_2 &= \delta f\left(t_n + \frac{h}{2},\,y_n + \frac{h}{2}k_1,\,\delta y_n + \frac{h}{2}\delta k_1\right) \\ + \delta k_3 &= \delta f\left(t_n + \frac{h}{2},\,y_n + \frac{h}{2}k_2,\,\delta y_n + \frac{h}{2}\delta k_2\right) \\ + \delta k_4 &= \delta f(t_n + h,\,y_n + hk_3,\,\delta y_n + h\delta k_3) +\end{aligned} +$$ {#eq-adj-rk4-tl} +ここで$\delta f=\partial f/\partial y$は接線型モデルである。 +$\delta k_1,\,\delta k_2,\,\delta k_3,\,\delta k_4$は出力しないので、$\delta y$を更新した後 +$$ +\delta\mathbf{k} \equiv [\delta k_1,\,\delta k_2,\,\delta k_3,\,\delta k_4]^\mathrm{T}=0 +$$ +と置くと、行列形式では +$$ +\begin{bmatrix} +\delta\mathbf{k} \\ \delta y +\end{bmatrix} += +\begin{bmatrix} +0 & 0 \\ +h\mathbf{b}^\mathrm{T} & 1 +\end{bmatrix} +\begin{bmatrix} +\delta\mathbf{k} \\ \delta y +\end{bmatrix} +$$ {#eq-adj-rk4-tl-matrix} +となる。 + +随伴は +$$ +\begin{bmatrix} +\mathbf{k}^\mathrm{a} \\ y^\mathrm{a} +\end{bmatrix} += +\begin{bmatrix} +0 & h\mathbf{b}\\ +0 & 1 +\end{bmatrix} +\begin{bmatrix} +\mathbf{k}^\mathrm{a} \\ y^\mathrm{a} +\end{bmatrix} +$$ {#eq-adj-rk4-ad-matrix} +つまり、$k_1^\mathrm{a} = hy^\mathrm{a}/6,\,k_2^\mathrm{a} = hy^\mathrm{a}/3,\,k_3^\mathrm{a} = hy^\mathrm{a}/3,\,k_4^\mathrm{a} = hy^\mathrm{a}/6$と初期化される。 + +$L$を線型演算子、$\alpha$をスカラ係数として +$C=L(A+\alpha B)$は +$$ +\begin{bmatrix} +A \\ B \\ C +\end{bmatrix} = +\begin{bmatrix} +1 & 0 & 0\\ +0 & 1 & 0\\ +L & \alpha L & 0 +\end{bmatrix} +\begin{bmatrix} +A \\ B \\ C +\end{bmatrix} +$$ +と書けるので、その随伴は +$$ +\begin{bmatrix} +A^\mathrm{a} \\ B^\mathrm{a} \\ C^\mathrm{a} +\end{bmatrix} = +\begin{bmatrix} +1 & 0 & L^\mathrm{T}\\ +0 & 1 & \alpha L^\mathrm{T}\\ +0 & 0 & 0 +\end{bmatrix} +\begin{bmatrix} +A^\mathrm{a} \\ B^\mathrm{a} \\ C^\mathrm{a} +\end{bmatrix} +$$ +つまり$A^\mathrm{a} = A^\mathrm{a} + LC^\mathrm{a},\,B^\mathrm{a} = B^\mathrm{a} + \alpha LC^\mathrm{a},\,C^\mathrm{a}=0$ +である。 +これを用いるとRK4の随伴は次の順序で計算される。 +$$ +\begin{aligned} +f_4^\mathrm{a} &\equiv f^\mathrm{a}(t_n + h,\,y_n + hk_3,\,k_4^\mathrm{a})\\ +y^\mathrm{a} &= y^\mathrm{a} + f_4^\mathrm{a}\\ +k_3^\mathrm{a} &= k_3^\mathrm{a} + hf_4^\mathrm{a} \\ +k_4^\mathrm{a} &= 0 \\ +f_3^\mathrm{a} &\equiv f^\mathrm{a}\left(t_n + \frac{h}{2},\,y_n + \frac{h}{2}k_2, \,k_3^\mathrm{a}\right)\\ +y^\mathrm{a} &= y^\mathrm{a} + f_3^\mathrm{a}\\ +k_2^\mathrm{a} &= k_2^\mathrm{a} + \frac{h}{2}f_3^\mathrm{a} \\ +k_3^\mathrm{a} &= 0 \\ +f_2^\mathrm{a} &\equiv \delta f^\mathrm{a}\left(t_n + \frac{h}{2},\,y_n + \frac{h}{2}k_1,\, k_2^\mathrm{a}\right)\\ +y^\mathrm{a} &= y^\mathrm{a} + f_2^\mathrm{a}\\ +k_1^\mathrm{a} &= k_1^\mathrm{a} + \frac{h}{2}f_2^\mathrm{a} \\ +k_2^\mathrm{a} &= 0 \\ +y^\mathrm{a} &= y^\mathrm{a} + f^\mathrm{a}(t_n,\,y_n,\,k_1^\mathrm{a})\\ +k_1^\mathrm{a} &= 0 +\end{aligned} +$$ + +## 接線型及び随伴の動作確認 + +接線型は +$$N(\mathbf{w}+\Delta\mathbf{w})-N(\mathbf{w})\approx \mathbf{L}(\mathbf{w})\Delta\mathbf{w}$$ {#eq-var-tlm_check} +が近似的に成り立つことを確認する。ここで$N$は非線型モデル、$\mathbf{L}$は接線型モデル +、$\mathbf{w}$は状態、$\Delta\mathbf{w}$は摂動を表す。精度は$\mathbf{w}$における$N$の非線型の強さや摂動$\Delta\mathbf{w}$の振幅に依存する。 + +随伴は +$$(\mathbf{L}(\mathbf{w})\Delta\mathbf{w})^\mathrm{T}(\mathbf{L}(\mathbf{w})\Delta\mathbf{w})=\Delta\mathbf{w}^\mathrm{T}[\mathbf{L}(\mathbf{w})^\mathrm{T}(\mathbf{L}(\mathbf{w})\Delta\mathbf{w})]$$ {#eq-var-adm_check} +が成り立つことを確認する。 +厳密に成り立つか、機械精度以下の誤差(下1〜2桁の差異)でなければバグが存在していることを示す。 diff --git a/org/math/00_introduccion_02ccfe.org b/org/math/00_introduccion_02ccfe.org new file mode 100644 index 0000000..80cf165 --- /dev/null +++ b/org/math/00_introduccion_02ccfe.org @@ -0,0 +1,510 @@ +#+TITLE: EST-25134: Aprendizaje Estadistico +#+AUTHOR: Prof. Alfredo Garbuno Iñigo +#+EMAIL: agarbuno@itam.mx +#+DATE: ~Introducción~ +:REVEAL_PROPERTIES: +# Template uses org export with export option +# Alternatives: use with citeproc +#+LANGUAGE: es +#+OPTIONS: num:nil toc:nil timestamp:nil +#+REVEAL_REVEAL_JS_VERSION: 4 +#+REVEAL_THEME: night +#+REVEAL_SLIDE_NUMBER: t +#+REVEAL_HEAD_PREAMBLE: +#+REVEAL_INIT_OPTIONS: width:1600, height:900, margin:.2 +#+REVEAL_EXTRA_CSS: ./mods.css +#+REVEAL_PLUGINS: (notes) +:END: +#+STARTUP: showall +#+PROPERTY: header-args:R :session intro-aprendizaje :exports both :results output org :tangle ../rscripts/00-introduccion.R :mkdirp yes :dir ../ +#+EXCLUDE_TAGS: toc github + + +#+BEGIN_NOTES +*Profesor*: Alfredo Garbuno Iñigo | Primavera, 2023 | Introducción.\\ +*Objetivo*. Dar un panorama de lo que rige los principios del curso de aprendizaje + estadístico y diferenciarlo de otras estrategias de modelado predictivo. Sentar + la notación base. +#+END_NOTES + + +* Contenido :toc: +:PROPERTIES: +:TOC: :include all :ignore this :depth 2 +:END: +:CONTENTS: +- [[#introducción][Introducción]] + - [[#caracteristicas-del-aprendizaje-estadístico][Caracteristicas del Aprendizaje Estadístico]] + - [[#filosofía-del-curso][Filosofía del curso]] + - [[#principios][Principios]] +- [[#distinciones-con-respecto-a-aprendizaje-de-máquina-ml][Distinciones con respecto a aprendizaje de máquina (ML)]] +- [[#métodos][Métodos]] + - [[#tareas-de-predicción][Tareas de predicción]] +- [[#notación][Notación]] + - [[#tipos-de-características][Tipos de características]] + - [[#notación-objetivos-y-muestras][Notación: objetivos y muestras]] +- [[#repaso-de-probabilidad][Repaso de probabilidad]] + - [[#definición-espacio-de-probabilidad][~Definición~ [Espacio de Probabilidad]:]] + - [[#definición-variable-aleatoria][~Definición~ [Variable aleatoria]:]] + - [[#definición-función-de-acumulación][~Definición~ [Función de acumulación]:]] + - [[#definición-función-de-densidad][~Definición~ [Función de densidad]:]] + - [[#teorema-ley-de-los-grandes-números][~Teorema~ [Ley de los Grandes Números]:]] + - [[#teorema-límite-central][~Teorema~ [Límite Central]:]] +- [[#control-de-versiones][Control de versiones]] +- [[#r-statistical-programming-language][R statistical programming language]] +- [[#ambiente-de-r][Ambiente de R]] + - [[#por-qué-utilizamos-el-tidyverse][¿Por qué utilizamos el tidyverse?]] + - [[#por-qué-utilizamos-tidymodels][¿Por qué utilizamos tidymodels?]] +- [[#código-de-r][Código de R.]] +:END: + +* Introducción + +Herramientas para ~entender reglas de asociación~. Con el objetivo de ~generar +predicciones acertadas~. No es ~estadística~. No es ~inferencia causal~. + +** Caracteristicas del Aprendizaje Estadístico +#+ATTR_REVEAL: :frag (appear) +- Flexibilidad. +- Procesamiento automático. +- Complejidad (en datos). +- Predicción. + +#+BEGIN_NOTES + +En aprendizaje estadístico usualmente consideramos menos suposiciones de los +datos en contraste con estadistica; pensamos que el procesamiento es automático; +que los datos son complejos; y que el interés primordial es la *predicción*. + +#+END_NOTES + +** Filosofía del curso + +Es importante entender los modelos, la intuición y fortalezas y debilidades de +los métodos que se utilizan en tareas de aprendizaje ~supervisadas~ y ~no +supervisadas~. + +** Principios + +Consideraremos los siguientes, tomados de citep:Kuhn2013. + +#+REVEAL: split + +- Muchos métodos de aprendizaje son relevantes para una gran variedad de aplicaciones. + +#+BEGIN_NOTES + +No encasillar en el ámbito académico o estadístico. Por supuesto hay muchos mas +modelos de los que veremos pero nos concentramos en los que no son de nicho. + +#+END_NOTES +#+REVEAL: split + +- Aprendizaje estadístico *no* es una colección de cajas negras. + +#+BEGIN_NOTES +Lamentablemente no hay un método que sea exitoso para cualquier tipo de +aplicación. Tenemos que conocer bien nuestras herramientas para saber cuál usar +en qué situación. +#+END_NOTES +#+REVEAL: split + +- Una cosa es entender cómo funciona; otra, implementarlo desde cero. + +#+BEGIN_NOTES + +No reinventaremos la rueda. En el curso nos concentraremos en las ideas, no en +la implementación. + +#+END_NOTES +#+REVEAL: split + +\newpage + +- Conocimiento de dominio. Obtención de información relevante. + +#+BEGIN_NOTES + +Espero poder transmitir la necesidad de pensar en la aplicación del modelo. Algo +que no se ve dentro de una formulación matemática. Pero la cual, si no se es +cuidadoso podría tener en consecuencia una herramienta inservible al +mediano/largo plazo. + +#+END_NOTES + + +* Distinciones con respecto a aprendizaje de máquina (ML) + +En aprendizaje estadístico nos interesa comprender el proceso que genera los +datos y su representatividad estadística. + + +* Métodos + +Aprendizaje ~supervisado~ y ~aprendizaje no supervisado~. + +** Tareas de predicción + +- Clasificación +- Regresión + +* Notación + +Denotamos por $x$ una ~variable aleatoria~ y por $\mathbb{P}(\cdot)$ una ~función +de distribución~. Escribimos $x \sim \mathbb{P}$ para denotar que la variable +aleatoria $x$ tiene distribución $\mathbb{P}(\cdot)$. Denotamos por +$\mathbb{E}[\cdot]$ el ~valor esperado~ del argumento con respecto a la +distribución que estamos considerando. Durante el curso seremos explícitos en la +variable aleatoria y usaremos +\begin{align} +\mathbb{E}_x[\cdot] = \int_\mathcal{X} \cdot \, \pi(x) \, \text{d}x\,, +\end{align} +o bien, haremos énfasis en la distribución por medio de lo siguiente +\begin{align} +\mathbb{E}_\pi[\cdot] = \int_\mathcal{X} \cdot \, \pi(x) \, \text{d}x\,, +\end{align} +de acuerdo al contexto. + +#+REVEAL: split +Denotamos por $n$ el ~número de observaciones~; $p$ para el ~número de +características~ de dichas observaciones. Así que, $x_{ij}$ con $i = 1, \ldots, +n$ y $j = 1, \ldots, p$ será un elemento de nuestras observaciones. + + +** Tipos de características +:PROPERTIES: +:reveal_background: #00468b +:END: + + +** Notación: objetivos y muestras + +Usualmente tendremos una característica que queremos predecir y la denotamos por $y$ . Consideraremos $y \in \mathbb{R}$ ó $y \in \{0,1\}$ ó $y \in \{1, 2, \ldots, K\}$. + +#+REVEAL: split + +El conjunto de datos que tenemos ~disponible para entrenar~ modelos lo denotamos por +\begin{align} +\mathcal{D}_n = \{ (x_1, y_1), \ldots (x_n, y_n) \}\,. +\end{align} + +#+REVEAL: split + +Es ideal considerar que además tenemos datos adicionales para ~hacer pruebas~. A este conjunto lo denotaremos por +\begin{align} +\mathcal{T}_m = \{ (x_1, y_1), \ldots (x_m, y_m) \}\,. +\end{align} + +#+REVEAL: split +Posiblemente necesitemos notación mas especializada para hacer distinciones +adicionales o el contexto nos ayude a requerir una notación mas laxa. Esto lo +definiremos sobre la marcha. + +* Repaso de probabilidad + +Consideraremos como requisitos el contenido de ~Cálculo de Probabilidades II~ y +~Álgebra Lineal~ (o equivalentes). En particular lo que requerimos como base es lo siguiente. + +*** *~Definición~ [Espacio de Probabilidad]*: +Un espacio de probabilidad está definido por la terna $(\Omega, \mathcal{X}, \mathbb{P})$: +1. El espacio muestral, $\Omega$ (elementos). +2. El espacio de eventos medibles, $\mathcal{X}$ (subconjuntos). +3. La medida de probabilidad, $\mathbb{P}: \mathcal{X} \rightarrow [0, 1]$. + +*** *~Definición~ [Variable aleatoria]*: +Una variable aleatoria es una función $X: +\mathcal{X} \rightarrow \mathbb{R}$ con la propiedad de que las pre-imágenes +bajo $X$ son eventos medibles. Es decir, +\begin{align} +\{w \in \mathcal{X} : X(w) \leq x \} \in \mathcal{X} \qquad \forall x \in \mathbb{R}. +\end{align} + +*** *~Definición~ [Función de acumulación]*: +Para toda variable aleatoria $X$ tenemos una función de acumulación +$\mathbb{P}_{_X}: \mathbb{R} \rightarrow [0, 1]$ dada por +\begin{align} +\mathbb{P}_{_X}(x) = \mathbb{P} \big( \{w \in \mathcal{X} : X(w) \leq x\} \big)\,. +\end{align} +Esto usualmente lo escribimos como $\mathbb{P}_{_X}(x) = \mathbb{P}\{X \leq x\}$. + +*** *~Definición~ [Función de densidad]*: +Una variable aleatoria es continua si su función de acumulación es ~absolutamente +continua~ y puede ser expresada por medio de +\begin{align} +\mathbb{P}_{_X} (x) = \int_{- \infty}^x \pi (s) \, \text{d}s\,, +\end{align} +donde la anti-derivada $\pi:\mathbb{R} \rightarrow [0, \infty)$ se llama la ~función de +densidad~ de la variable aleatoria $X$. + +#+REVEAL: split +Las propiedades generales de las distribuciones de probabilidad se pueden +especificar por medio de su centralidad (localización), su dispersión, su rango +de valores, su simetría y el comportamiento de valores extremos. + +#+REVEAL: split +En general esto lo podemos extraer de los momentos +\begin{align} +\mathbb{E}(X^p) = \int_{\mathbb{R}}^{} x^p \, \pi(x) \, \text{d}x\,, +\end{align} +o los momentos centrales. Por ejemplo: media y varianza. + +#+REVEAL: split +Uno de los resultados que espero recuerden bien de sus cursos anteriores es el +de la ~Ley de los Grandes Números~. La cual podemos enunciar como: + +*** *~Teorema~ [Ley de los Grandes Números]*: +Sea $X_1, X_2, \ldots$ una colección de variables aleatorias independientes e +idénticamente distribuidas ($\mathsf{iid}$) y sea $\bar X_n$ el promedio de un +subconjunto de $n$. Si denotamos por $\mu$ el valor promedio de $X_i$ +dentro de esa colección, entonces tenemos que +\begin{align} +\bar X_n \rightarrow \mu \quad (\text{casi seguramente})\,. +\end{align} + +*** *~Teorema~ [Límite Central]*: +Sea $X_1, \ldots, X_n$ una colección de $n$ variables aleatorias $\mathsf{iid}$ con $\mathbb{E}[X_i] = \mu$ y $\mathbb{V}[X_i] = \sigma^2 < \infty$. Entonces +\begin{align} +\bar X_n \sim \mathsf{N}\left( \mu, \frac{\sigma^2}{n} \right)\,, +\end{align} +para $n$ suficientemente grande. + + + +* Control de versiones + +Los /softwares/ de ~control de versiones~ nos permiten llevar un registro y +administración de cambios en archivos. Usualmente para proyectos de +programación. + +#+REVEAL: split +Ayudan a trabajar colaborativamente en ambientes de equipos de trabajo. + +#+REVEAL: split +Aunque no exploraremos /todo/ lo que se puede hacer con ~Git~ y ~GitHub~ lo usaremos +para llevar un control del desarrollo y de entrega de tareas. Usaremos los +principios mas básicos. + +# #+REVEAL: split +# #+DOWNLOADED: screenshot @ 2022-08-15 19:40:19 +# #+attr_html: :width 700 :align center +# #+attr_latex: :width .33 \linewidth +# [[file:images/20220815-194019_screenshot.png]] + +# #+REVEAL: split +# #+DOWNLOADED: screenshot @ 2022-08-15 19:37:37 +# #+attr_html: :width 200 :align center +# #+attr_latex: :width .33 \linewidth +# [[file:images/20220815-193737_screenshot.png]] + + +* ~R~ statistical programming language + +~R~ es un lenguaje de programación orientado a cómputo estadístico y generación de +gráficos estadísticos. Está escrito para interactuar por medio de ejecución de +/scripts/ (archivos de texto con instrucciones) o la consola interactiva. Ver +[[fig-terminal]]. + +#+DOWNLOADED: screenshot @ 2022-08-15 19:54:14 +#+attr_html: :width 1200 :align center +#+name: fig-terminal +#+caption: Dos ventanas, un editor de texto y una consola de ~R~. +[[file:images/20220815-195840_screenshot.png]] + +#+REVEAL: split +Es usual utilizar un ambiente de desarrollo para programar e interactuar con el +lenguaje. Para ~R~ el mas común es ~Rstudio~ el cual tiene además algunas +extensiones útiles para el desarrollo de análisis estadístico. Ver [[fig-ide]]. + +#+DOWNLOADED: screenshot @ 2022-08-15 19:56:38 +#+attr_html: :width 1200 :align center +#+name: fig-ide +#+caption: Un ambiente de desarrollo, ~Rstudio~. +[[file:images/20220815-195638_screenshot.png]] + +#+REVEAL: split +~Visual Studio Code~ es una alternativa multi-lenguaje para desarrollar proyectos +de análisis estadístico en ~R~. Ver [[fig-browser]]. + +#+DOWNLOADED: screenshot @ 2022-08-15 20:02:39 +#+attr_html: :width 1200 :align center +#+name: fig-browser +#+caption: Un ambiente de desarrollo general, ~Visual Code Studio~. En la imagen se muestra una sesión en un explorador de internet. +[[file:images/20220815-200239_screenshot.png]] + +#+REVEAL: split +Y habemos los que nos /conformamos/ con un buen editor de texto como ambiente de +desarrollo. Ver [[fig-emacs]]. + +#+DOWNLOADED: screenshot @ 2022-08-15 20:09:14 +#+attr_html: :width 1200 :align center +#+name: fig-emacs +#+caption: Ambiente de desarrollo basado en ~Emacs~. +[[file:images/20220815-200914_screenshot.png]] + +* Ambiente de ~R~ + +#+begin_src R :exports none :results none + ## Setup -------------------------------------------- + library(tidyverse) + library(patchwork) + library(scales) + + ## Cambia el default del tamaño de fuente + theme_set(theme_linedraw(base_size = 25)) + + ## Cambia el número de decimales para mostrar + options(digits = 4) + ## Problemas con mi consola en Emacs + options(pillar.subtle = FALSE) + options(rlang_backtrace_on_error = "none") + options(crayon.enabled = FALSE) + + ## Para el tema de ggplot + sin_lineas <- theme(panel.grid.major = element_blank(), + panel.grid.minor = element_blank()) + color.itam <- c("#00362b","#004a3b", "#00503f", "#006953", "#008367", "#009c7b", "#00b68f", NA) + + sin_leyenda <- theme(legend.position = "none") + sin_ejes <- theme(axis.ticks = element_blank(), axis.text = element_blank()) +#+end_src + + +#+begin_src R :exports code :results org + library(tidyverse) # Herramientas de procesamiento + library(tidymodels) # Herramientas de modelado + library(ISLR) # Datos del libro de texto + library(MASS) # Datos de Boston +#+end_src + +** ¿Por qué utilizamos el ~tidyverse~? + +#+DOWNLOADED: screenshot @ 2023-01-09 19:46:09 +#+attr_html: :width 1200 :align center +[[file:images/20230109-194609_screenshot.png]] + +#+REVEAL: split + +#+DOWNLOADED: screenshot @ 2023-01-09 20:08:58 +#+attr_html: :width 1200 :align center +[[file:images/20230109-200858_screenshot.png]] + + +** ¿Por qué utilizamos ~tidymodels~? + +#+begin_quote +La búsqueda ~CRAN Task View: Machine Learning & Statistical Learning~: +#+end_quote + +abess (core) +ahaz +arules +BART +bartMachine +BayesTree +BDgraph +biglasso +bmrm +Boruta +bst +C50 +caret +CORElearn +Cubist +deepnet +DoubleML +e1071 (core) +earth +effects +elasticnet +evclass +evtree +frbs +gamboostLSS +gbm (core) +ggRandomForests +glmnet +glmpath +GMMBoost +gradDescent +grf +grplasso +grpreg +h2o +hda +hdi +hdm +ICEbox +ipred +islasso +joinet +kernlab (core) +klaR +lars +lasso2 +LiblineaR +maptree +mboost (core) +mlpack +mlr3 +mlr3proba +mpath +naivebayes +ncvreg +nnet (core) +OneR +opusminer +pamr +party +partykit +pdp +penalized +penalizedLDA +picasso +plotmo +quantregForest +randomForest (core) +randomForestSRC +ranger +rattle +Rborist +RcppDL +rdetools +relaxo +rgenoud +RGF +RLT +Rmalschains +rminer +ROCR +RoughSets +rpart (core) +RPMM +RSNNS +RWeka +RXshrink +sda +SIS +splitTools +ssgraph +stabs +SuperLearner +svmpath +tensorflow +tgp +torch +tree +trtf +varSelRF +wsrf +xgboost + +bibliographystyle:abbrvnat +bibliography:references.bib + + +* Código de ~R~. :github: + +[[file:../rscripts/00-introduccion.R][Descarga]] el script de la clase. + + + diff --git a/org/math/01_montecarlo_c9ecc6.org b/org/math/01_montecarlo_c9ecc6.org new file mode 100644 index 0000000..8a709e5 --- /dev/null +++ b/org/math/01_montecarlo_c9ecc6.org @@ -0,0 +1,1043 @@ +#+TITLE: EST-46115: Modelación Bayesiana +#+AUTHOR: Prof. Alfredo Garbuno Iñigo +#+EMAIL: agarbuno@itam.mx +#+DATE: ~Integración Monte Carlo~ +:REVEAL_PROPERTIES: +# Template uses org export with export option +# Alternatives: use with citeproc +#+LANGUAGE: es +#+OPTIONS: num:nil toc:nil timestamp:nil +#+REVEAL_REVEAL_JS_VERSION: 4 +#+REVEAL_MATHJAX_URL: https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js +#+REVEAL_THEME: night +#+REVEAL_SLIDE_NUMBER: t +#+REVEAL_HEAD_PREAMBLE: +#+REVEAL_INIT_OPTIONS: width:1600, height:900, margin:.2 +#+REVEAL_EXTRA_CSS: ./mods.css +#+REVEAL_PLUGINS: (notes) +:END: +#+PROPERTY: header-args:R :session intro :exports both :results output org :tangle ../rscripts/01-montecarlo.R :mkdirp yes :dir ../ +#+EXCLUDE_TAGS: toc latex + +#+BEGIN_NOTES +*Profesor*: Alfredo Garbuno Iñigo | Primavera, 2022 | Integración Monte Carlo.\\ +*Objetivo*: Estudiar integración numérica en el contexto probabilistico. Estudiar, + en particular, el método Monte Carlo y entender sus bondades y limitaciones en + el contexto de inferencia Bayesiana. \\ +*Lectura recomendada*: Sección 6.1 de citet:Dogucu2021. Una lectura mas técnica + sobre reglas de cuadratura se puede encontrar en la sección 3.1 de + citet:Reich2015. Y una buena referencia (técnica) sobre el método Monte Carlo + lo encuentran en citet:Sanz-Alonso2019. +#+END_NOTES + +#+begin_src R :exports none :results none + ## Setup -------------------------------------------------- +#+end_src + +#+begin_src R :exports none :results none + library(tidyverse) + library(patchwork) + library(scales) + + ## Cambia el default del tamaño de fuente + theme_set(theme_linedraw(base_size = 25)) + + ## Cambia el número de decimales para mostrar + options(digits = 4) + ## Problemas con mi consola en Emacs + options(pillar.subtle = FALSE) + options(rlang_backtrace_on_error = "none") + options(crayon.enabled = FALSE) + + ## Para el tema de ggplot + sin_lineas <- theme(panel.grid.major = element_blank(), + panel.grid.minor = element_blank()) + color.itam <- c("#00362b","#004a3b", "#00503f", "#006953", "#008367", "#009c7b", "#00b68f", NA) + + sin_leyenda <- theme(legend.position = "none") + sin_ejes <- theme(axis.ticks = element_blank(), axis.text = element_blank()) +#+end_src + + +* Contenido :toc: +:PROPERTIES: +:TOC: :include all :ignore this :depth 3 +:END: +:CONTENTS: +- [[#introducción][Introducción]] +- [[#por-qué-integrar][¿Por qué integrar?]] +- [[#integración-numérica][Integración numérica]] + - [[#ejemplo-proporción][Ejemplo: Proporción]] + - [[#más-de-un-parámetro][Más de un parámetro]] + - [[#reglas-de-cuadratura][Reglas de cuadratura]] +- [[#integración-monte-carlo][Integración Monte Carlo]] + - [[#ejemplo-dardos][Ejemplo: Dardos]] + - [[#propiedades][Propiedades]] + - [[#teorema-error-monte-carlo][Teorema [Error Monte Carlo]​]] + - [[#teorema-tlc-para-estimadores-monte-carlo][Teorema [TLC para estimadores Monte Carlo]​]] + - [[#nota][Nota:]] + - [[#nota][Nota:]] + - [[#nota][Nota:]] + - [[#ejemplo-proporciones][Ejemplo: Proporciones]] + - [[#ejemplo-sabores-de-helados][Ejemplo: Sabores de helados]] + - [[#tarea-sabores-de-helados][Tarea: Sabores de helados]] +- [[#extensiones-muestreo-por-importancia][Extensiones: Muestreo por importancia]] + - [[#propiedades-muestreo-por-importancia][Propiedades: muestreo por importancia]] + - [[#ejemplo][Ejemplo]] +:END: + +* Introducción + +En inferencia bayesiana lo que queremos es poder resolver +\begin{align} +\mathbb{E}[f] = \int_{\Theta}^{} f(\theta) \, \pi(\theta | y ) \, \text{d}\theta\,. +\end{align} + +#+BEGIN_NOTES + +Lo que necesitamos es resolver integrales con respecto a la distribución de interés. + +#+END_NOTES + +#+REVEAL: split +#+ATTR_REVEAL: :frag (appear) +- La pregunta clave (I) es: ¿qué distribución? +- La pregunta clave (II) es: ¿con qué método numérico resuelvo la integral? +- La pregunta clave (III) es: ¿y si no hay método numérico? + + +* ¿Por qué integrar? + +Consideremos de interés estimar la proporción de volumen de la hiper-esfera +contenida en un hiper-cubo unitario conforme aumenta la dimensión del problema. + +#+begin_src R :exports none :results none + ## Maldición de la dimensionalidad ------------------------------------------- +#+end_src + +#+begin_src R :exports code :results none + distancia_euclideana <- function(u) sqrt(sum(u * u)); + + experimento <- function(ndim){ + nsamples <- 1e5; + y <- matrix(runif(nsamples * ndim, -0.5, 0.5), nsamples, ndim); + mean(apply(y, 1, distancia_euclideana) < 0.5) + } +#+end_src + +#+REVEAL: split +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/curse-dimensionality.jpeg :exports results :results output graphics file + tibble(dims = 1:10) |> + mutate(prob = map_dbl(dims, experimento)) |> + ggplot(aes(dims, prob)) + + geom_point() + + geom_line() + + sin_lineas + + scale_x_continuous(breaks=c(1, 3, 5, 7, 9)) + + xlab("Número de dimensiones") + + ylab("Volumen relativo") +#+end_src +#+caption: Evolución del volumen relativo de la hiper-esfera circunscrita dentro del hiper-cubo unitario. +#+RESULTS: +[[file:../images/curse-dimensionality.jpeg]] + +#+REVEAL: split +#+begin_src R :exports none :results none + chi.pdf <- function(x, d) { + x^(d - 1) * exp(-x^2/2) / (2^(d/2 - 1) * gamma(d/2)) + } +#+end_src + +#+begin_src R :exports code :results none + puntos.grafica <- tibble(dims = c(1, 5, 10, 25, 50, 100)) |> + mutate(points = map(dims, function(dim){ + tibble(x = seq(0, 15, length.out = 1000)) |> + mutate(y = chi.pdf(x, dim)) + }), dimensions = factor(dims)) +#+end_src + +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/densidad-esfera.jpeg :exports results :results output graphics file + puntos.grafica |> + unnest(points) |> + ggplot(aes(x, y, group = dimensions, color = dimensions)) + + geom_line() + sin_leyenda + + sin_lineas + xlab("Número de dimensiones") + + ylab("Densidad") +#+end_src +#+caption: Densidad de los vecinos de la moda para una Normal multivariada estándar $\mathsf{N}(0, I_p)$. +#+RESULTS: +[[file:../images/densidad-esfera.jpeg]] + + +#+REVEAL: split +Otro detalle interesante de altas dimensiones es la poca intuición +probabilística que tenemos de estos espacios y de lo que es una muestra típica +de una distribución. + +Por ejemplo, para $X \sim \mathsf{N}(0,1)$ estamos acostumbrados a asociar la +moda como el valor de mas alta densidad. Lo cual es un error terrible en varias +dimensiones. + +#+REVEAL: split +Consideremos un análisis analítico. Por ejemplo, sabemos que si $X \sim \mathsf{N}(0, I_p)$, entonces tenemos que +\begin{align} +\sum_{i = 1}^{p}X_i^2 \sim \chi^2_{p}\,. +\end{align} +Gráfiquemos el valor central de estas variables aleatorias y sus percentiles del +$2.5\%$ y $97.5\%$. Lo que observamos es que una ~muestra típica~ no se comporta +como el promedio de nuestra distirbución, /aka/ el individuo promedio no es tan +común. + +#+REVEAL: split +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/typical-sets.jpeg :exports results :results output graphics file + tibble(dim = 2**seq(0, 8)) |> + mutate(.centro = sqrt(qchisq(.50, dim)), + .lower = sqrt(qchisq(.025, dim)), + .upper = sqrt(qchisq(.975, dim))) |> + ggplot(aes(dim, .centro)) + + geom_ribbon(aes(ymin = .lower, ymax = .upper), alpha = .3, fill = "gray") + + geom_line() + geom_point() + sin_lineas + + scale_x_log10() + + ylab("Distancia euclideana al centro") + + xlab("Número de dimensiones") +#+end_src +#+caption: Distancia euclideana de puntos aleatorios de una Gaussiana multivariada al centro de la distribución. Esto ilustra que aunque el centro es el comportamiento promedio, los puntos típicos de una Gaussiana se encuentran lejos. +#+RESULTS: +[[file:../images/typical-sets.jpeg]] + +#+REVEAL: split +Lo que sucede se conoce como el fenómeno de ~concentración de medida~ donde los +puntos de más alta densidad no corresponden a los puntos de mayor volumen +(probabilidad). + +#+REVEAL: split +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/concentracion-medida.jpeg :exports results :results output graphics file + tibble(dim = 2**seq(0, 8)) |> + mutate(.resultados = map(dim, function(ndim){ + x <- unlist(purrr::rerun(10000, sum(dnorm(rnorm(ndim),log = TRUE)))) + tibble(x = x) |> + summarise(.densidad_tip = mean(x), + .lower_densidad = quantile(x, .025), + .upper_densidad = quantile(x, .975), + .densidad_moda = sum(dnorm(rep(0, ndim), log = TRUE))) + })) |> + unnest(.resultados) |> + ggplot(aes(dim, .densidad_tip)) + + geom_line(aes(y = .densidad_moda), col = 'red') + + geom_point(aes(y = .densidad_moda), col = 'red') + + geom_ribbon(aes(ymin = .lower_densidad, ymax = .upper_densidad), alpha = .3, fill = "gray") + + geom_line() + geom_point() + sin_lineas + + scale_x_log10() + + ylab("log-Densidad") + + xlab("Número de dimensiones") + +#+end_src +#+caption: En rojo la log-densidad de la moda de una Gaussiana multivariada. En negro la log-densidad de muestras aleatorias de una Gaussiana multivariada. Esto muestra que los elementos con mayor densidad no corresponden a vecindades de mayor volumen. +#+RESULTS: +[[file:../images/concentracion-medida.jpeg]] + +#+REVEAL: split +Esto explica por qué no queremos realizar la aproximación +\begin{align} +\pi(f) \approx f(\theta^\star)\,, \quad \text{ donde } \quad \theta^\star = \underset{\theta \in \Theta}{\arg \max} \, \pi(\theta)\,. +\end{align} + + +* Integración numérica + +Recordemos la definición de integrales Riemann: +$$\int_a^b f(x) \text{d} x\,.$$ + +#+BEGIN_NOTES +La aproximación utilizando una malla de $N$ puntos sería: +$$\sum_{n=1}^N f(u_n) \Delta u_n.$$ + +El método útil cuando las integrales se realizan cuando tenemos pocos parámetros. Es decir, $\theta \in \mathbb{R}^p$ con $p$ pequeña. +#+END_NOTES + +#+begin_src R :exports none :results none + ## Ejemplo de integracion numerica ------------------------------------------- + + grid.n <- 11 # Número de celdas + grid.size <- 6/(grid.n+1) # Tamaño de celdas en el intervalo [-3, 3] + norm.cuadrature <- tibble(x = seq(-3, 3, by = grid.size), y = dnorm(x) ) + + + norm.density <- tibble(x = seq(-5, 5, by = .01), + y = dnorm(x) ) + +#+end_src + +#+REVEAL: split +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/quadrature.jpeg :exports results :results output graphics file + norm.cuadrature |> + ggplot(aes(x=x + grid.size/2, y=y)) + + geom_area(data = norm.density, aes(x = x, y = y), fill = 'lightblue') + + geom_bar(stat="identity", alpha = .3) + + geom_bar(aes(x = x + grid.size/2, y = -0.01), fill = 'black', stat="identity") + + sin_lineas + xlab('') + ylab("") + + annotate('text', label = expression(Delta~u[n]), + x = .01 + 5 * grid.size/2, y = -.02, size = 12) + + annotate('text', label = expression(f(u[n]) ), + x = .01 + 9 * grid.size/2, y = dnorm(.01 + 4 * grid.size/2), size = 12) + + annotate('text', label = expression(f(u[n]) * Delta~u[n]), + x = .01 + 5 * grid.size/2, y = dnorm(.01 + 4 * grid.size/2)/2, + angle = -90, alpha = .7, size = 12) + sin_ejes +#+end_src +#+caption: Integral por medio de discretización con $N = 11$. +#+RESULTS: +[[file:../images/quadrature.jpeg]] + +#+REVEAL: split +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/quadrature-hi.jpeg :exports results :results output graphics file + grid.n <- 101 # Número de celdas + grid.size <- 6/(grid.n+1) # Tamaño de celdas en el intervalo [-3, 3] + norm.cuadrature <- tibble(x = seq(-3, 3, by = grid.size), y = dnorm(x) ) + + norm.cuadrature |> + ggplot(aes(x=x + grid.size/2, y=y)) + + geom_area(data = norm.density, aes(x = x, y = y), fill = 'lightblue') + + geom_bar(stat="identity", alpha = .3) + + geom_bar(aes(x = x + grid.size/2, y = -0.01), fill = 'black', stat="identity") + + sin_lineas + xlab('') + ylab("") + + annotate('text', label = expression(Delta~u[n]), + x = .01 + 5 * grid.size/2, y = -.02, size = 12) + + annotate('text', label = expression(f(u[n]) ), + x = .01 + 9 * grid.size/2, y = dnorm(.01 + 4 * grid.size/2), size = 12) + + annotate('text', label = expression(f(u[n]) * Delta~u[n]), + x = .01 + 5 * grid.size/2, y = dnorm(.01 + 4 * grid.size/2)/2, + angle = -90, alpha = .7, size = 12) + sin_ejes +#+end_src +#+caption: Integral por medio de una malla fina, $N = 101$. +#+RESULTS: +[[file:../images/quadrature-hi.jpeg]] + + +** Ejemplo: Proporción + +Supongamos que $p(S_n = k|\theta) \propto \theta^k(1-\theta)^{n-k}$ cuando +observamos $k$ éxitos en $n$ pruebas independientes. Supongamos que nuestra +inicial es $p(\theta) = 2\theta$ (~checa que es una densidad~). + +#+REVEAL: split +#+begin_src R :exports code :results none + crear_log_post <- function(n, k){ + function(theta){ + verosim <- k * log(theta) + (n - k) * log(1 - theta) + inicial <- log(theta) + verosim + inicial + } + } +#+end_src + +#+REVEAL: split +#+begin_src R + # observamos 3 exitos en 4 pruebas: + log_post <- crear_log_post(4, 3) + prob_post <- function(x) { exp(log_post(x))} + # integramos numericamente + p_x <- integrate(prob_post, lower = 0, upper = 1, subdivisions = 100L) + p_x +#+end_src + +#+RESULTS: +#+begin_src org +0.033 with absolute error < 3.7e-16 +#+end_src + +#+REVEAL: split +Y ahora podemos calcular la media posterior: +\begin{align} +\mathbb{E}[\theta | S_n] = \int_{\Theta} \theta \, \pi(\theta | S_n)\, \text{d}\theta\,. +\end{align} + +#+begin_src R + media_funcion <- function(theta){ + theta * prob_post(theta) / p_x$value + } + integral_media <- integrate(media_funcion, + lower = 0, upper = 1, + subdivisions = 100L) + media_post <- integral_media$value + c(Numerico = media_post, Analitico = 5/(2+5)) +#+end_src + +#+RESULTS: +#+begin_src org + Numerico Analitico + 0.71 0.71 +#+end_src + +** Más de un parámetro + +#+BEGIN_NOTES +Consideramos ahora un espacio con $\theta \in \mathbb{R}^p$. Si conservamos $N$ +puntos por cada dimensión, ¿cuántos puntos en la malla necesitaríamos? Lo que +tenemos son recursos computacionales limitados y hay que buscar hacer el mejor +uso de ellos. En el ejemplo, hay zonas donde no habrá contribución en la +integral. +#+END_NOTES + + +#+HEADER: :width 1500 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/eruption-quadrature.jpeg :exports results :results output graphics file + canvas <- ggplot(faithful, aes(x = eruptions, y = waiting)) + + xlim(0.5, 6) + + ylim(40, 110) + + grid.size <- 10 - 1 + + mesh <- expand.grid(x = seq(0.5, 6, by = (6-.5)/grid.size), + y = seq(40, 110, by = (110-40)/grid.size)) + + g1 <- canvas + + geom_density_2d_filled(aes(alpha = ..level..), bins = 8) + + scale_fill_manual(values = rev(color.itam)) + + sin_lineas + theme(legend.position = "none") + + geom_point(data = mesh, aes(x = x, y = y)) + + annotate("rect", xmin = .5 + 5 * (6-.5)/grid.size, + xmax = .5 + 6 * (6-.5)/grid.size, + ymin = 40 + 3 * (110-40)/grid.size, + ymax = 40 + 4 * (110-40)/grid.size, + linestyle = 'dashed', + fill = 'salmon', alpha = .4) + ylab("") + xlab("") + + annotate('text', x = .5 + 5.5 * (6-.5)/grid.size, + y = 40 + 3.5 * (110-40)/grid.size, + label = expression(u[n]), color = 'red', size = 15) + + theme(axis.ticks = element_blank(), + axis.text = element_blank()) + + + g2 <- canvas + + stat_bin2d(aes(fill = after_stat(density)), binwidth = c((6-.5)/grid.size, (110-40)/grid.size)) + + sin_lineas + theme(legend.position = "none") + + theme(axis.ticks = element_blank(), + axis.text = element_blank()) + + scale_fill_distiller(palette = "Greens", direction = 1) + + sin_lineas + theme(legend.position = "none") + + ylab("") + xlab("") + + g3 <- canvas + + stat_bin2d(aes(fill = after_stat(density)), binwidth = c((6-.5)/25, (110-40)/25)) + + sin_lineas + theme(legend.position = "none") + + theme(axis.ticks = element_blank(), + axis.text = element_blank()) + + scale_fill_distiller(palette = "Greens", direction = 1) + + sin_lineas + theme(legend.position = "none") + + ylab("") + xlab("") + + g1 + g2 + g3 +#+end_src +#+caption: Integral por método de malla. +#+RESULTS: +[[file:../images/eruption-quadrature.jpeg]] + +** Reglas de cuadratura + +Por el momento hemos escogido aproximar las integrales por medio de una aproximación con una ~malla uniforme~. +Sin embargo, se pueden utilizar aproximaciones +$$\int_a^b f(x) \text{d} x \approx \sum_{n=1}^N f(\xi_n)\, \omega_n\,.$$ + +Estas aproximaciones usualmente se realizan para integrales en intervalos cerrados $[a,b]$. La regla de cuadratura determina los pesos $\omega_n$ y los centros $\xi_n$ pues se escogen de acuerdo a ~ciertos criterios de convergencia~. + +#+BEGIN_NOTES +Por ejemplo, se consideran polinomios que aproximen con cierto grado de precisión el integrando. Los pesos y los centros se escogen de acuerdo a la familia de polinomios. Pues para cada familia se tienen identificadas las mallas que optimizan la aproximación. Ver sección 3.1 de citet:Reich2015. +#+END_NOTES + +* Integración Monte Carlo +\begin{gather*} +\pi(f) = \mathbb{E}_\pi[f] = \int f(x) \pi(x) \text{d}x\,,\\ +\hat{\pi}_N^{\textsf{MC}}(f) = \frac1N \sum_{n = 1}^N f( x^{(n)}), \qquad \text{ donde } x^{(n)} \overset{\mathsf{iid}}{\sim} \pi, \qquad \text{ con } n = 1, \ldots, N \,, \\ + \pi(f) \approx \hat{\pi}_N^{\textsf{MC}}(f)\,. +\end{gather*} + + +** Ejemplo: Dardos + +Consideremos el experimento de lanzar dardos uniformemente en un cuadrado de +tamaño 2, el cual contiene un circulo de radio 1. + +#+HEADER: :width 1100 :height 300 :R-dev-args bg="transparent" +#+begin_src R :file images/dardos-montecarlo.jpeg :exports results :results output graphics file + ## Integración Monte Carlo --------------------------------------------------- + genera_dardos <- function(n = 100){ + tibble(x1 = runif(n, min = -1, max = 1), + x2 = runif(n, min = -1, max = 1)) |> + mutate(resultado = ifelse(x1**2 + x2**2 <= 1., 1., 0.)) + } + + dardos <- tibble(n = seq(2,5)) |> + mutate(datos = map(10**n, genera_dardos)) |> + unnest() + + dardos |> + ggplot(aes(x = x1, y = x2)) + + geom_point(aes(color = factor(resultado))) + + facet_wrap(~n, nrow = 1) + + sin_lineas + sin_ejes + sin_leyenda + coord_equal() +#+end_src +#+caption: Integración Monte Carlo para aproximar $\pi$. +#+RESULTS: +[[file:../images/dardos-montecarlo.jpeg]] + +#+begin_src R :exports none :results none + dardos |> + group_by(n) |> + summarise(aprox = 4 * mean(resultado)) +#+end_src + +#+RESULTS: +#+begin_src org + n aprox +1 2 3.1 +2 3 3.2 +3 4 3.1 +4 5 3.1 +#+end_src + +#+REVEAL: split +Si escogemos $N$ suficientemente grande entonces nuestro promedio converge a la +integral. En [[fig-mc-rolling]] se muestra para cada $n$ en el eje horizontal cómo +cambia nuestra estimación $\hat \pi_n^{\mathsf{MC}}(f)$ . + +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/dardos-consistencia.jpeg :exports results :results output graphics file + set.seed(1087) + genera_dardos(n = 2**16) |> + mutate(n = seq(1, 2**16), + approx = cummean(resultado) * 4) |> + ggplot(aes(x = n, y = approx)) + + geom_line() + + geom_hline(yintercept = pi, linetype = 'dashed') + + scale_x_continuous(trans='log10', + labels = trans_format("log10", math_format(10^.x))) + + ylab('Aproximación') + xlab("Número de muestras") + sin_lineas + +#+end_src +#+caption: Estimación $\hat{\pi}_N^{\textsf{MC}}(f)$ con $N \rightarrow \infty$. +#+name: fig-mc-rolling +#+RESULTS: +[[file:../images/dardos-consistencia.jpeg]] + +#+REVEAL: split +También podemos en replicar el experimento unas $M$ veces y observar cómo +cambiaría nuestra estimación con distintas semillas. Por ejemplo, podemos +replicar el experimento 10 veces. En ~R~ y ~python~ lo usual es utilizar ~arreglos +multidimensionales~ para poder guardar muestras bajo distintas replicas. + +#+begin_src R :exports both :results org + set.seed(108) + nsamples <- 10**4; nexp <- 100 + U <- runif(nexp * 2 * nsamples) + U <- array(U, dim = c(nexp, 2, nsamples)) + apply(U[1:5,,], 1, str) +#+end_src + +#+RESULTS: +#+begin_src org + num [1:2, 1:10000] 0.4551 0.7159 0.164 0.0627 0.5291 ... + num [1:2, 1:10000] 0.404 0.2313 0.9282 0.0426 0.0883 ... + num [1:2, 1:10000] 0.351 0.739 0.449 0.658 0.369 ... + num [1:2, 1:10000] 0.664 0.984 0.627 0.762 0.185 ... + num [1:2, 1:10000] 0.4635 0.6107 0.0115 0.7251 0.0117 ... +NULL +#+end_src + +#+REVEAL: split +#+begin_src R :exports code :results none + resultados <- apply(U, 1, function(x){ + dardos <- apply(x**2, 2, sum) + exitos <- ifelse(dardos <= 1, 1, 0) + prop <- cummean(exitos) + 4 * prop + }) +#+end_src + +#+REVEAL: split +Lo cual nos permite realizar distintos escenarios posibles. +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/dardos-trayectorias.jpeg :exports results :results output graphics file + resultados |> + as_data_frame() |> + mutate(n = 1:nsamples) |> + pivot_longer(cols = 1:10) |> + ggplot(aes(n, value)) + + geom_line(aes(group = name, color = name)) + + geom_hline(yintercept = pi, linetype = 'dashed') + + scale_x_continuous(trans='log10', + labels = trans_format("log10", math_format(10^.x))) + + ylab('Aproximación') + xlab("Número de muestras") + sin_lineas + sin_leyenda + + ylim(0, 7) +#+end_src +#+caption: Réplica de las trayectorias de diversas realizaciones de la aproximación de la integral. +#+RESULTS: +[[file:../images/dardos-trayectorias.jpeg]] + +#+REVEAL: split +Bajo ciertas consideraciones teóricas podemos esperar un buen comportamiento de +nuestro estimador de la integral. E incluso podríamos (si el número de +simulaciones lo permite) aproximar dicho comportamiento utilizando +distribuciones asintóticas, ($\mathsf{TLC}$). + +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/dardos-normalidad.jpeg :exports results :results output graphics file + resultados |> + as_data_frame() |> + mutate(n = 1:nsamples) |> + pivot_longer(cols = 1:nexp) |> + group_by(n) |> + summarise(promedio = mean(value), + desv.est = sd(value), + y.lo = promedio - 2 * desv.est, + y.hi = promedio + 2 * desv.est) |> + ggplot(aes(n , promedio)) + + geom_ribbon(aes(ymin = y.lo, ymax = y.hi), fill = "gray", alpha = .3) + + geom_ribbon(aes(ymin = promedio - 2 * sqrt(pi * (4 - pi)/(n)), + ymax = promedio + 2 * sqrt(pi * (4 - pi)/(n))), + fill = "salmon", alpha = .1) + + geom_hline(yintercept = pi, linetype = 'dashed') + + geom_line() + + scale_x_continuous(trans='log10', + labels = trans_format("log10", math_format(10^.x))) + + ylab('Aproximación') + xlab("Número de muestras") + sin_lineas + sin_leyenda + + ylim(0, 7) +#+end_src +#+caption: Comportamiento promedio e intervalos de confianza. +#+RESULTS: +[[file:../images/dardos-normalidad.jpeg]] + +#+REVEAL: split +Podemos explicar la reducción de los intervalos de confianza por medio de la +varianza de la estimación de la integral en las distintas réplicas que +tenemos. Mas adelante explicaremos de dónde viene la línea punteada. Vemos cómo, +aunque captura bien la reducción en varianza, puede sub- o sobre-estimarla. +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/dardos-cota-cramerrao.jpeg :exports results :results output graphics file + resultados |> + as_data_frame() |> + mutate(n = 1:nsamples) |> + pivot_longer(cols = 1:nexp) |> + group_by(n) |> + summarise(varianza = var(value/4)) |> + mutate(cramer.rao = pi * (4 - pi)/(16 * n)) |> + ggplot(aes(n , varianza)) + + geom_line() + + geom_line(aes(n, cramer.rao), lty = 2, color = 'red') + + scale_y_continuous(trans='log10') + + scale_x_continuous(trans='log10', + labels = trans_format("log10", math_format(10^.x))) + + ylab('Varianza') + xlab("Número de muestras") + sin_lineas + sin_leyenda +#+end_src +#+caption: Comportamiento promedio e intervalos de confianza. +#+RESULTS: +[[file:../images/dardos-cota-cramerrao.jpeg]] + +** Propiedades + +A continuación enunciaremos algunas propiedades clave del método Monte +Carlo. Poco a poco las iremos explicando y en particular discutiremos algunas de +ellas. + +*** ~Teorema~ [Error Monte Carlo] +Sea $f : \mathbb{R}^p \rightarrow \mathbb{R}$ cualquier función bien +comportada$^\dagger$. Entonces, el estimador Monte Carlo es *insesgado*. Es +decir, se satisface + +\begin{align} +\mathbb{E}\left[\hat \pi_N^{\textsf{MC}}(f) - \pi(f)\right] = 0, +\end{align} +para cualquier $N$. Usualmente estudiamos el error en un escenario pesimista +donde medimos el *error cuadrático medio* en el peor escenario + +\begin{align*} +\sup_{f \in \mathcal{F}} \, \, \mathbb{E}\left[ \left(\hat \pi_N^{\textsf{MC}}(f) - \pi(f) \right)^2 \right] \leq \frac1N. +\end{align*} + +#+BEGIN_NOTES +Esta desigualdad nos muestra una de las propiedades que usualmente se celebran +de los métodos Monte Carlo. La integral y nuestra aproximación de ella por medio +de simulaciones tiene un error acotado proporcionalmente por el número de +simulaciones. +#+END_NOTES + +#+REVEAL: split +En particular, la varianza del estimador (*error estándar*) satisface la igualdad +$$ \textsf{ee}^2\left(\hat \pi_N^{\textsf{MC}}(f)\right) = \frac{\mathbb{V}_\pi( f )}{N}.$$ + +#+BEGIN_NOTES +Esta igualdad, aunque consistente con nuestra desigualdad anterior, nos dice +algo mas. El error de nuestra aproximación *depende* de la varianza de $f$ bajo la +distribución $\pi$. +#+END_NOTES + +*** ~Teorema~ [TLC para estimadores Monte Carlo] +Sea $f$ una función *bien comportada* $^{\dagger\dagger}$, entonces bajo una $N$ +suficientemente grande tenemos +\begin{align} +\sqrt{N} \left(\hat \pi_N^{\textsf{MC}} (f) - \pi(f) \right) \sim \mathsf{N}\left(0, \mathbb{V}_\pi(f)\right)\,. +\end{align} + +*** ~Nota~: +El estimador Monte Carlo del que hablamos, $\hat \pi_{N}^{\mathsf{MC}}(f)$, es una estimación con una ~muestra finita de simulaciones~. En ese sentido podemos pensar que tenemos un /mapeo/ de muestras a estimador +\begin{align} +(x^{(1)}, \ldots, x^{(N)}) \mapsto \hat \pi_N^{\mathsf{MC}}(f)\,, +\end{align} +con $x^{(i)} \overset{\mathsf{iid}}{\sim} \pi$ . + +#+REVEAL: split +De lo cual es natural pensar: ¿y si hubiéramos observado otro conjunto de +simulaciones? Nuestro proceso de estimación es el mismo pero la muestra puede +cambiar. + +#+REVEAL: split +En este sentido nos preguntamos por el ~comportamiento promedio~ bajo distintas +muestras observadas +\begin{align} +\mathbb{E}[\hat \pi_N^{\mathsf{MC}}(f)] = \mathbb{E}_{x_{1}, \ldots, x_{N}}[\hat \pi_N^{\mathsf{MC}}(f)]\,. +\end{align} +De la misma manera nos podemos preguntar sobre la ~dispersión alrededor de dicho +promedio~ (varianza) +\begin{align} +\mathbb{V}[\hat \pi_N^{\mathsf{MC}}(f)] = \mathbb{V}_{x_{1}, \ldots, x_{N}}[\hat \pi_N^{\mathsf{MC}}(f)]\,. +\end{align} + +#+REVEAL: split +Al ser un ejercicio de ~estimación~ la desviación estándar del estimador recibe el +nombre de ~error estándar~. Lo cual denotamos por +\begin{align} +\mathsf{ee}[\hat \pi_N^{\mathsf{MC}}(f)] = \left( \mathbb{V}[\hat \pi_N^{\mathsf{MC}}(f)] \right)^{1/2}= \left( \frac{\mathbb{V}_\pi( f )}{N} \right)^{1/2}\,. +\end{align} + +*** ~Nota~: +Para algunos estimadores la fórmula del error estándar se puede obtener de +manera analítica. Para otro tipo, tenemos que +utilizar propiedades asintóticas (p.e. cota de Cramer-Rao). + +#+REVEAL: split +Hay casos en los que no existe una fórmula asintótica o resultado analítico, pero +podemos usar simulación [ ~8)~ ] para cuantificar dicha dispersión. + +*** ~Nota~: +Hay situaciones en las que la distribución normal asintótica no tiene +sentido. Para este tipo de situaciones también veremos cómo podemos utilizar +simulación para cuantificar dicha dispersión. + +#+DOWNLOADED: screenshot @ 2022-08-29 19:52:47 +#+attr_html: :width 700 :align center +#+caption: Comportamiento promedio e intervalos de confianza con aproximación asintótica. +[[file:../images/dardos-normalidad.jpeg]] + +** Ejemplo: Proporciones + +Consideramos la estimación de una proporción $\theta$, tenemos como inicial +$p(\theta) \propto \theta$, que es una $\mathsf{Beta}(2,1)$. Si observamos 3 +éxitos en 4 pruebas, entonces sabemos que la posterior es $p(\theta|x)\propto +\theta^4(1-\theta)$, que es una $\mathsf{Beta}(5, 2)$. Si queremos calcular la +media y el segundo momento posterior para $\theta$, en teoría necesitamos +calcular +\begin{align} +\mu_1 = \int_0^1 \theta \,\, p(\theta|X = 3)\, \text{d}\theta,\qquad \mu_2=\int_0^1 \theta^2 \,\, p(\theta|X = 3)\, \text{d}\theta\,. +\end{align} + +#+REVEAL: split +#+begin_src R :exports none :results none + ### Ejemplo proporciones ----------------------------------------------------- +#+end_src + +Utilizando el ~método Monte Carlo~: +#+begin_src R +theta <- rbeta(10000, 5, 2) +media_post <- mean(theta) +momento_2_post <- mean(theta^2) +c(mu_1 = media_post, mu_2 = momento_2_post) +#+end_src + +#+RESULTS: +#+begin_src org +mu_1 mu_2 +0.71 0.54 +#+end_src + +#+REVEAL: split +Incluso, podemos calcular cosas mas /exóticas/ como +\begin{align} +P(e^{\theta}> 2|x)\,. +\end{align} + +#+begin_src R +mean(exp(theta) > 2) +#+end_src + +#+RESULTS: +#+begin_src org +[1] 0.61 +#+end_src + +** Ejemplo: Sabores de helados + +Supongamos que probamos el nivel de gusto para 4 sabores distintos de una +paleta. Usamos 4 muestras de aproximadamente 50 personas diferentes para cada +sabor, y cada uno evalúa si le gustó mucho o no. Obtenemos los siguientes +resultados: +#+begin_src R :exports none :results none + ### Ejemplo helados ---------------------------------------------------------- +#+end_src + +#+begin_src R :exports results + datos <- tibble( + sabor = c("fresa", "limon", "mango", "guanabana"), + n = c(50, 45, 51, 50), gusto = c(36, 35, 42, 29)) |> + mutate(prop_gust = gusto / n) + + datos +#+end_src + +#+caption: Resultados de las encuestas. +#+RESULTS: +#+begin_src org + sabor n gusto prop_gust +1 fresa 50 36 0.72 +2 limón 45 35 0.78 +3 mango 51 42 0.82 +4 guanábana 50 29 0.58 +#+end_src + +#+REVEAL: split +Usaremos como inicial $\mathsf{Beta}(2, 1)$ (pues hemos obervado cierto sesgo de +cortesía en la calificación de sabores, y no es tan probable tener valores muy +bajos) para todos los sabores, es decir $p(\theta_i)$ es la funcion de densidad +de una $\mathsf{Beta}(2, 1)$. La inicial conjunta la definimos entonces, usando +~independencia inicial~, como +$$p(\theta_1,\theta_2, \theta_3,\theta_4) = p(\theta_1)p(\theta_2)p(\theta_3)p(\theta_4)\,.$$ + +#+REVEAL: split +Pues inicialmente establecemos que ningún parámetro da información sobre otro: +saber que mango es muy gustado no nos dice nada acerca del gusto por fresa. Bajo +este supuesto, y el supuesto adicional de que las muestras de cada sabor son +independientes, podemos mostrar que las ~posteriores son independientes~: +$$p(\theta_1,\theta_2,\theta_3, \theta_4|k_1,k_2,k_3,k_4) = p(\theta_4|k_1)p(\theta_4|k_2)p(\theta_4|k_3)p(\theta_4|k_4)$$ + +#+REVEAL: split +#+begin_src R :exports results + datos <- datos |> + mutate(a_post = gusto + 2, + b_post = n - gusto + 1, + media_post = a_post/(a_post + b_post)) + datos +#+end_src + +#+caption: Resultado de inferencia Bayesiana. +#+RESULTS: +#+begin_src org + sabor n gusto prop_gust a_post b_post media_post +1 fresa 50 36 0.72 38 15 0.72 +2 limón 45 35 0.78 37 11 0.77 +3 mango 51 42 0.82 44 10 0.81 +4 guanábana 50 29 0.58 31 22 0.58 +#+end_src + +#+REVEAL: split +Podemos hacer preguntas interesantes como: ¿cuál es la probabilidad de que mango +sea el sabor preferido? Para contestar esta pregunta podemos utilizar +simulación y responder por medio de un procedimiento Monte Carlo. + +#+begin_src R :exports none :results none + modelo_beta <- function(params, n = 5000){ + rbeta(n, params$alpha, params$beta) + } +#+end_src + +#+begin_src R :exports code :results none + ## Generamos muestras de la posterior + paletas <- datos |> + mutate(alpha = a_post, beta = b_post) |> + nest(params.posterior = c(alpha, beta)) |> + mutate(muestras.posterior = map(params.posterior, modelo_beta)) |> + select(sabor, muestras.posterior) +#+end_src + +#+REVEAL: split +#+HEADER: :width 1200 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/paletas-hist.jpeg :exports results :results output graphics file + paletas |> + unnest(muestras.posterior) |> + ggplot(aes(muestras.posterior)) + + geom_histogram(aes(fill = sabor), position = "identity", alpha = .8) + + sin_lineas +#+end_src +#+caption: Histogramas de la distribución predictiva marginal para cada $\theta_j$. +#+RESULTS: +[[file:../images/paletas-hist.jpeg]] + +#+REVEAL: split +#+begin_src R + ## Utilizamos el metodo Monte Carlo para aproximar la integral. + paletas |> + unnest(muestras.posterior) |> + mutate(id = rep(seq(1, 5000), 4)) |> group_by(id) |> + summarise(favorito = sabor[which.max(muestras.posterior)]) |> + group_by(favorito) |> tally() |> + mutate(prop = n/sum(n)) +#+end_src +#+caption: Aproximación Monte Carlo. +#+RESULTS: +#+begin_src org + favorito n prop +1 fresa 308 0.0616 +2 guanábana 1 0.0002 +3 limón 1319 0.2638 +4 mango 3372 0.6744 +#+end_src + +#+BEGIN_NOTES +Escencialmente estamos preguntándonos sobre calcular la integral: +\begin{align} +\mathbb{P}(\text{mango sea preferido}) = \int_\Theta f(\theta_1, \ldots, \theta_4) \, p(\theta_1, \ldots, \theta_4 | X_1, \ldots, X_n) d\theta\,, +\end{align} +donde $f(\theta_1, \ldots, \theta_4) = \mathbb{I}_{[\theta_4 \geq \theta_j, j \neq 4]}(\theta_1, \ldots, \theta_4)$. +#+END_NOTES + +** Tarea: Sabores de helados + +- ¿Cuál es la probabilidad a priori de que cada sabor sea el preferido? +- Con los datos de arriba, calcula la probabilidad de que la gente prefiera el sabor de mango sobre limón. + + + +* Extensiones: Muestreo por importancia + +Incluso cuando tenemos una integral *complicada* podemos ~relajar~ el problema de integración. De tal forma que podemos ~sustituir~ +$$\int f(x) \pi(x) \text{d} x = \int f(x) \frac{\pi(x)}{\rho(x)}\,\rho(x) \text{d} x = \int f(x) \, w(x) \, \rho(x) \, \text{d}x\,,$$ +donde $\rho$ es una densidad de una variable aleatoria ~adecuada~. + +#+REVEAL: split +Esto nos permite utilizar lo que sabemos de las propiedades del método Monte Carlo para resolver la integral +\begin{align*} +\pi(f) = \int f(x) \pi(x) \text{d} x = \int f(x) \omega(x) \, \rho(x) \, \text{d}x =: \rho(f\omega)\,, +\end{align*} +por medio de una aproximación +\begin{align} +\pi(f) \approx \sum_{n = 1}^{N} \bar{\omega}^{(n)} f(x^{(n)}), \qquad x^{(n)} \overset{\mathsf{iid}}{\sim} \rho\,. +\end{align} +#+REVEAL: split +Al estimador le llamamos el estimador por importancia y lo denotamos por +\begin{align} +\hat{\pi}_N^{\mathsf{IS}}(f) = \sum_{n = 1}^{N} \bar{\omega}^{(n)} f(x^{(n)}), \qquad \bar{\omega}^{(n)} = \frac{\omega(x^{(n)})}{\sum_{m= 1}^{N}\omega(x^{(m)})}\,. +\end{align} + +** Propiedades: muestreo por importancia + +Lamentablemente, utilizar muestreo por importancia ~impacta la calidad de la +estimación~ (medida, por ejemplo, en términos del *peor error cuadrático medio +cometido*). El impacto es un factor que incorpora la /diferencia/ entre la distribución +~objetivo~ --para integrales de la forma $\int f(x) \text{d}x$, implica la +distribución uniforme-- y la distribución ~sustituto~. Puedes leer más de esto +(aunque a un nivel mas técnico) en la sección 5 de las notas de +citet:Sanz-Alonso2019. + +** Ejemplo + +#+HEADER: :width 1200 :height 400 :R-dev-args bg="transparent" +#+begin_src R :file images/muestreo-importancia-mezcla.jpeg :exports results :results output graphics file + crea_mezcla <- function(weights){ + function(x){ + weights$w1 * dnorm(x, mean = -1.5, sd = .5) + + weights$w2 * dnorm(x, mean = 1.5, sd = .7) + } + } + objetivo <- crea_mezcla(list(w1 = .6, w2 = .4)) + + muestras_mezcla <- function(id){ + n <- 100 + tibble(u = runif(n)) |> + mutate(muestras = ifelse(u <= .6, + rnorm(1, -1.5, sd = .5), + rnorm(1, 1.5, sd = .7))) |> + pull(muestras) + } + + muestras.mezcla <- tibble(id = 1:1000) |> + mutate(muestras = map(id, muestras_mezcla)) |> + unnest(muestras) |> + group_by(id) |> + summarise(estimate = mean(muestras)) + + g0 <- muestras.mezcla |> + ggplot(aes(estimate)) + + geom_histogram() + + geom_vline(xintercept = -1.5 * .6 + 1.5 * .4, + lty = 2, color = 'salmon', lwd = 1.5) + + geom_vline(xintercept = mean(muestras.mezcla$estimate), + lty = 3, color = 'steelblue', lwd = 1.5) + + xlim(-1, 1) + + ggtitle("Objetivo") + sin_lineas + + muestras_uniforme <- function(id){ + n <- 100 + runif(n, -5, 5) + } + + muestras.uniforme <- tibble(id = 1:1000) |> + mutate(muestras = map(id, muestras_uniforme)) |> + unnest(muestras) |> + mutate(pix = objetivo(muestras), + gx = dunif(muestras, -5, 5), + wx = pix/gx) |> + group_by(id) |> + summarise(estimate = sum(muestras * wx)/sum(wx)) + + g1 <- muestras.uniforme |> + ggplot(aes(estimate)) + + geom_histogram() + + geom_vline(xintercept = -1.5 * .6 + 1.5 * .4, + lty = 2, color = 'salmon', lwd = 1.5) + + geom_vline(xintercept = mean(muestras.uniforme$estimate), + lty = 3, color = 'steelblue', lwd = 1.5) + + xlim(-1, 1) + + ggtitle("Uniforme(-5,5)") + sin_lineas + + muestras_importancia <- function(id){ + n <- 100 + rnorm(n, 0, sd = 1) + } + + muestras.normal <- tibble(id = 1:1000) |> + mutate(muestras = map(id, muestras_importancia)) |> + unnest(muestras) |> + mutate(pix = objetivo(muestras), + gx = dnorm(muestras, 0, sd = 1), + wx = pix/gx) |> + group_by(id) |> + summarise(estimate = sum(muestras * wx)/sum(wx)) + + g2 <- muestras.normal |> ggplot(aes(estimate)) + + geom_histogram() + + geom_vline(xintercept = -1.5 * .6 + 1.5 * .4, + lty = 2, color = 'salmon', lwd = 1.5) + + geom_vline(xintercept = mean(muestras.normal$estimate), + lty = 3, color = 'steelblue', lwd = 1.5) + + xlim(-1, 1) + + ggtitle("Normal(0, 2)") + + sin_lineas + + g0 + g1 + g2 + +#+end_src +#+caption: Muestreo por importancia utilizando distintas distribuciones instrumentales. Distribución de muestreo $\pi^{\mathsf{IS}}_N$ con $B = 10,000$ y $n = 100$. +#+RESULTS: +[[file:../images/muestreo-importancia-mezcla.jpeg]] + +#+BEGIN_NOTES +El análisis del error en la sección anterior habla en del error cuadrático medio en el peor escenario posible bajo una familia de funciones de prueba (resumen). El ejemplo anterior muestra el error Monte Carlo cometido con respecto a una función resumen $f(\theta) = \theta$ con la cual, vemos, se reduce la varianza. Esto no contradice lo anterior pues para esta función resumen nuestra distribución instrumental satisface el criterio de reducción de varianza. En general, lo complicado es encontrar dicha distribución que podamos usar en la estimación Monte Carlo. +#+END_NOTES + + +bibliographystyle:abbrvnat +bibliography:references.bib + diff --git a/org/math/02_mcmc_246b17.org b/org/math/02_mcmc_246b17.org new file mode 100644 index 0000000..b797ce8 --- /dev/null +++ b/org/math/02_mcmc_246b17.org @@ -0,0 +1,1095 @@ +#+TITLE: EST-46115: Modelación Bayesiana +#+AUTHOR: Prof. Alfredo Garbuno Iñigo +#+EMAIL: agarbuno@itam.mx +#+DATE: ~MCMC~ +#+STARTUP: showall +:LATEX_PROPERTIES: +#+OPTIONS: toc:nil date:nil author:nil tasks:nil +#+LANGUAGE: sp +#+LATEX_CLASS: handout +#+LATEX_HEADER: \usepackage[spanish]{babel} +#+LATEX_HEADER: \usepackage[sort,numbers]{natbib} +#+LATEX_HEADER: \usepackage[utf8]{inputenc} +#+LATEX_HEADER: \usepackage[capitalize]{cleveref} +#+LATEX_HEADER: \decimalpoint +#+LATEX_HEADER:\usepackage{framed} +#+LaTeX_HEADER: \usepackage{listings} +#+LATEX_HEADER: \usepackage{fancyvrb} +#+LATEX_HEADER: \usepackage{xcolor} +#+LaTeX_HEADER: \definecolor{backcolour}{rgb}{.95,0.95,0.92} +#+LaTeX_HEADER: \definecolor{codegray}{rgb}{0.5,0.5,0.5} +#+LaTeX_HEADER: \definecolor{codegreen}{rgb}{0,0.6,0} +#+LaTeX_HEADER: {} +#+LaTeX_HEADER: {\lstset{language={R},basicstyle={\ttfamily\footnotesize},frame=single,breaklines=true,fancyvrb=true,literate={"}{{\texttt{"}}}1{<-}{{$\bm\leftarrow$}}1{<<-}{{$\bm\twoheadleftarrow$}}1{~}{{$\bm\sim$}}1{<=}{{$\bm\le$}}1{>=}{{$\bm\ge$}}1{!=}{{$\bm\neq$}}1{^}{{$^{\bm\wedge}$}}1{|>}{{$\rhd$}}1,otherkeywords={!=, ~, $, \&, \%/\%, \%*\%, \%\%, <-, <<-, ::, /},extendedchars=false,commentstyle={\ttfamily \itshape\color{codegreen}},stringstyle={\color{red}}} +#+LaTeX_HEADER: {} +#+LATEX_HEADER_EXTRA: \definecolor{shadecolor}{gray}{.95} +#+LATEX_HEADER_EXTRA: \newenvironment{NOTES}{\begin{lrbox}{\mybox}\begin{minipage}{0.95\textwidth}\begin{shaded}}{\end{shaded}\end{minipage}\end{lrbox}\fbox{\usebox{\mybox}}} +#+EXPORT_FILE_NAME: ../docs/02-mcmc.pdf +:END: +#+PROPERTY: header-args:R :session mcmc :exports both :results output org :tangle ../rscripts/02-mcmc.R :mkdirp yes :dir ../ +#+EXCLUDE_TAGS: toc latex + +#+BEGIN_NOTES +*Profesor*: Alfredo Garbuno Iñigo | Primavera, 2023 | MCMC.\\ +*Objetivo*. Estudiar el método general de integración Monte Carlo vía cadenas de Markov (MCMC). La estrategia será construir poco a poco utilizando los principios básicos que lo componen. \\ +*Lectura recomendada*: Capítulo 7 de citep:Dogucu2021. Sección 6 de citep:Sanz-Alonso2019 y Capítulo 3 de citep:Reich2015 (avanzado). Si te interesa saber mas sobre programación orientada a objetos dentro del contexto de ~R~ puedes consultar citep:Wickham2019. +#+END_NOTES + + +* Contenido :toc: +:PROPERTIES: +:TOC: :include all :ignore this :depth 3 +:END: +:CONTENTS: +- [[#introducción][Introducción]] +- [[#muestreo-por-aceptación-rechazo][Muestreo por aceptación rechazo]] + - [[#implementación][Implementación]] + - [[#disclaimer][Disclaimer:]] + - [[#implementación-de-una-distribución-de-muestreo][Implementación de una distribución de muestreo.]] + - [[#ejercicio][Ejercicio:]] + - [[#propiedades][Propiedades]] +- [[#qué-hemos-visto][¿Qué hemos visto?]] +- [[#muestreo-por-cadenas-de-markov][Muestreo por cadenas de Markov]] + - [[#definición-cadena-de-markov][Definición [Cadena de Markov]:]] +- [[#generalizando][Generalizando...]] + - [[#pseudo-código][Pseudo-código]] + - [[#desentrañando][Desentrañando]] + - [[#implementación][Implementación]] + - [[#ejercicio][Ejercicio:]] + - [[#ejercicio][Ejercicio:]] + - [[#tarea][Tarea:]] +- [[#el-método-metropolis-hastings][El método Metropolis-Hastings]] + - [[#ejercicio-3][Ejercicio (3)]] + - [[#distribución-propuesta][Distribución propuesta]] +- [[#en-más-dimensiones][En más dimensiones]] +- [[#por-qué-funciona][¿Por qué funciona?]] + - [[#definición-invarianza][Definición [Invarianza]:]] + - [[#lema-comportamiento-asintótico-de-metropolis-hastings][Lema [Comportamiento asintótico de Metropolis-Hastings]:]] +:END: + +* Introducción + +#+begin_src R :exports none :results none + ## Setup -------------------------------------------- + library(tidyverse) + library(patchwork) + library(scales) + + ## Cambia el default del tamaño de fuente + theme_set(theme_linedraw(base_size = 25)) + + ## Cambia el número de decimales para mostrar + options(digits = 4) + ## Problemas con mi consola en Emacs + options(pillar.subtle = FALSE) + options(rlang_backtrace_on_error = "none") + options(crayon.enabled = FALSE) + + ## Para el tema de ggplot + sin_lineas <- theme(panel.grid.major = element_blank(), + panel.grid.minor = element_blank()) + color.itam <- c("#00362b","#004a3b", "#00503f", "#006953", "#008367", "#009c7b", "#00b68f", NA) + + sin_leyenda <- theme(legend.position = "none") + sin_ejes <- theme(axis.ticks = element_blank(), axis.text = element_blank()) +#+end_src + +El interés es poder resolver +\begin{align} +\mathbb{E}[f] = \int_{\Theta}^{} f(\theta) \, \pi(\theta | y ) \, \text{d}\theta\,. +\end{align} + +Sin embargo, ~no podemos generar~ $\theta^{(i)} \overset{\mathsf{iid}}{\sim} \pi(\theta|y)$. + +* Muestreo por aceptación rechazo + +Podemos utilizar una versión estocástica de muestreo por importancia. + +#+BEGIN_NOTES +Para muestrear de $\pi$ necesitamos utilizar una distribución sustituto (lo +mismo hicimos con muestreo por importancia). Sólo que ahora permitimos rechazar +muestras que no correspondan con las regiones de alta densidad de nuestra +distribución objetivo. El rechazo se realiza lanzando una moneda. La tasa de +éxito depende del qué tanto cubre nuestra distribución sustituto. +#+END_NOTES + +#+begin_src R :exports none :results none + ## Muestreo por aceptacion rechazo --------------- +#+end_src + +#+HEADER: :width 900 :height 500 :R-dev-args bg="transparent" +#+begin_src R :file images/rejection-sampling.jpeg :exports results :results output graphics file + crea_mezcla <- function(weights){ + function(x){ + weights$w1 * dnorm(x, mean = -1.5, sd = .5) + + weights$w2 * dnorm(x, mean = 1.5, sd = .7) + } + } + + objetivo <- crea_mezcla(list(w1 = .6, w2 = .4)) + + tibble(x = seq(-5, 5, length.out = 100)) |> + mutate(y = objetivo(x), + aprox = 3.3 * dnorm(x, 0, sd = 2)) |> + ggplot(aes(x,y)) + + geom_area(fill = "lightblue") + + geom_line(aes(x, aprox), lty = 2) + + geom_ribbon(aes(ymin = y, ymax = aprox), fill = "salmon") + sin_lineas + + sin_ejes + +#+end_src +#+caption: Esquema de muestreo. +#+RESULTS: +[[file:../images/rejection-sampling.jpeg]] + +** Implementación +Necesitamos algunas cosas. Ser capaces de ~evaluar~ nuestra distribución +objetivo. Ser capaces de ~evaluar~ *y* ~muestrear~ de nuestra distribución de +muestreo. + +#+REVEAL: split +#+caption: Distribución objetivo. +#+begin_src R :exports code :results none + crea_mezcla <- function(weights){ + function(x){ + weights$w1 * dnorm(x, mean = -1.5, sd = .5) + + weights$w2 * dnorm(x, mean = 1.5, sd = .7) + } + } + objetivo <- crea_mezcla(list(w1 = .6, w2 = .4)) + M <- 3.3 +#+end_src + +*** /Disclaimer/: +:PROPERTIES: +:reveal_background: #00468b +:END: + +El objetivo del curso *no* es enseñar programación orientada a objetos. Sin +embargo, permitirá abstraer los puntos importantes y concentrarnos en las ideas +generales y no preocuparnos por lo detalles. + +*** Implementación de una distribución de muestreo. + +Recordemos que lo que queremos son dos cosas: generar números aleatorios y evaluar la función de densidad. + +#+caption: Distribución de muestreo. +#+begin_src R :exports code :results none + library(R6) + ModeloNormal <- + R6Class("ProbabilityModel", + list( + mean = NA, + sd = NA, + ## Inicializador + initialize = function(mean = 0, sd = 1){ + self$mean = mean + self$sd = sd + }, + ## Muestreador + sample = function(n = 1){ + rnorm(n, self$mean, sd = self$sd) + }, + ## Evaluacion de densidad + density = function(x, log = TRUE){ + dnorm(x, self$mean, sd = self$sd, log = log) + } + )) +#+end_src + +#+BEGIN_NOTES +En muestreo con rechazo necesitamos definir una distribución de la +cual *si podamos* generar números aleatorios. El inconveniente es, además, *conocer* +qué tanto podemos inflar la densidad de nuestra propuesta para /cubrir/ la +distribución objetivo. +#+END_NOTES + +#+REVEAL: split +#+caption: Algoritmo de muestreo con rechazo. +#+begin_src R :exports code :results none + crea_rejection_sampling <- function(objetivo, aprox, M){ + function(niter){ + muestras <- matrix(nrow = niter, ncol = 3) + for (ii in seq(1, niter)){ + propuesta <- aprox$sample() + p <- objetivo(propuesta) + g <- aprox$density(propuesta, log = FALSE) + u <- runif(1) + if (u < p/(M * g)) { ## Aceptamos + muestras[ii, 1] <- 1 + } else { ## Rechazamos + muestras[ii, 1] <- 0 + } + muestras[ii, 2] <- propuesta + muestras[ii, 3] <- u + } + colnames(muestras) <- c("accept", "value", "auxiliar") + muestras + } + } +#+end_src + +#+REVEAL: split +#+HEADER: :width 1200 :height 300 :R-dev-args bg="transparent" +#+begin_src R :file images/muestreo-aceptacion.jpeg :exports results :results output graphics file + modelo.muestreo <- ModeloNormal$new(mean = 0, sd = 2) + muestreo_rechazo <- crea_rejection_sampling(objetivo, modelo.muestreo, M) + + muestras <- muestreo_rechazo(5000) |> + as.tibble() |> + mutate(density = modelo.muestreo$density(value, log = FALSE)) + + g1 <- muestras |> + ggplot(aes(value, auxiliar * modelo.muestreo$density(value, log = FALSE))) + + geom_point(aes(color = factor(accept))) + sin_lineas + sin_ejes + sin_leyenda + + xlab("") + ylab("") + + ggtitle(paste("Muestras en el espacio (x,u), aceptación: ", mean(muestras$accept))) + + g2 <- muestras |> + filter(accept == 1) |> + ggplot(aes(value)) + + geom_histogram() + + sin_lineas + sin_ejes + sin_leyenda + + xlab("") + ylab("") + + ggtitle("Histograma de las muestras generadas") + + g1 + g2 +#+end_src + +#+RESULTS: +[[file:../images/muestreo-aceptacion.jpeg]] + +*** Ejercicio: +:PROPERTIES: +:reveal_background: #00468b +:END: + +- ¿Qué pasa si $M$ es demasiado grande? Juega con el código e interpreta los resultados. +- ¿Qué pasa si $M$ no es suficiente para cubrir la distribución objetivo? Juega con el código e interpreta los resultados. + +** Propiedades + +*Lema (~Consistencia de muestreo por rechazo~)*. El método de muestreo por aceptación-rechazo genera muestras $x^{(i)}$ con $i = 1, \ldots, N$ que son independientes y distribuidas acorde a la distribución objetivo $\pi$. + +#+REVEAL: split +/Prueba/. Usemos probabilidad condicional para medir +\begin{align} +\pi(x | \textsf{aceptar}) = \frac{\pi(\textsf{aceptar} | x) \times \pi(x)}{\pi(\textsf{aceptar})}\,. +\end{align} + +* ¿Qué hemos visto? + +- El método Monte Carlo se puede utilizar para aproximar integrales. +- Se puede utilizar una distribución sustituto para generar números aleatorios que nos interesan. +- Podemos lanzar monedas para /filtrar/ sólo los aleatorios que tengan altas probabilidades. +- Hemos utilizado el supuesto de independencia. + +* Muestreo por cadenas de Markov + +Vamos a ~relajar~ el supuesto de ~independencia~. Es decir, vamos a generar una +secuencia de números aleatorios con cierta correlación. + +*** ~Definición~ [Cadena de Markov]: +Un *proceso estocástico* en tiempo discreto --una colección de variables + aleatorias $X_1, X_2, \ldots$ -- que satisface la propiedad de dependencia + condicional +\begin{align} +\mathbb{P}\left( X_{n+1} = x | X_1 = x_1, \ldots, X_n = x_n \right) = \mathbb{P}\left( X_{n+1} = x | X_n = x_n \right)\,, +\end{align} +se llama una *cadena de Markov* en tiempo discreto. + +** Ejemplo: + +#+DOWNLOADED: screenshot @ 2022-02-03 12:21:07 +#+caption: Problema del café. +#+attr_html: :width 700 :align center +[[file:images/20221031-163123_screenshot.png]] + +#+REVEAL: split +El vendedor de galletas quiere satisfacer la demanda para acompañar un café. El vendedor: +- Viaja entre las islas. +- Decide si se queda o no se queda en la isla donde está. +- Se puede mover entre islas contiguas (a través de puentes). +- Tiene mala memoria y pregunta el número de casas en las islas aledañas (todos los días). +- Quiere visitar todas las islas y vender galletas. +- Viaja en bicicleta. + + +#+REVEAL: split +También es astuto. Sabe que en /donde haya /mucha gente venderá mas/, pero también +sabe que una isla siempre lo /podría llevar a una mas grande/. Asi que a veces le +convendrá viajar a una isla pequeña. Asi que utilizará el ~principio de +aceptación rechazo~ para decidir si se moverá a la siguiente isla. + +#+REVEAL: split +1. Lanza una moneda para decidir si se mueve a la izquierda o derecha. +2. Decide si se mueve de acuerdo al cociente de poblaciones. + +** Pregunta + +En el contexto de nuestro problema ¿qué cambiaría si tuviera conocimiento censal +del archipiélago y pudiera viajar en avión? + +** Modelación del /tour/ de ventas + +El vendedor se encuentra en el $t$ -ésimo día. Supongamos que va a evaluar si se +cambia a la isla de la derecha. Sea $\pi_\star$ la población de la isla propuesta y +$\pi_{t}$ la población de la isla actual. Entonces el vendedor acepta cambiar de isla +con probabilidad + +$$\alpha_{\textsf{mover}}= \frac{\pi_\star}{\pi_{t}}\,.$$ + +#+BEGIN_NOTES +Nota que nunca dudará moverse a una isla mas grande. Por otro lado, entre mas +parecidas sean las poblaciones de las islas mas *indeciso* será de moverse. Por +definición $\alpha_{\textsf{mover}} \in (0,1)$. De hecho, podemos definir la +probabilidad de aceptar un viaje a otra isla por medio de + +$$\alpha(t, \star) = \min \Bigg\{ 1, \frac{\pi_\star}{\pi_{t}}\Bigg\},$$ + +pues incluye los dos casos. +#+END_NOTES + +#+REVEAL: split +#+begin_src R :exports none :results none + ## Caminata entre islas -------------------------- + set.seed(1087) +#+end_src + +#+caption: Mecanismo de cambio o permanencia desde la isla $i$. +#+begin_src R :exports code :results none + islas <- tibble(islas = 1:7, pob = c(1,2,3,4,5,4,3)) + camina_isla <- function(i){ # i: isla actual + u_izq <- runif(1) # Lanzamos volado para ver si nos vamos izq o der. + v <- ifelse(u_izq < 0.5, i - 1, i + 1) # Pedimos índice isla vecina. + if (v < 1 | v > 7) { # si estas en los extremos y el volado indica salir + return(i) + } + u_cambio <- runif(1) # Moneda de aceptacion de cambio + p_cambio = min(islas$pob[v]/islas$pob[i], 1) + if (u_cambio < p_cambio) { + return(v) # isla destino + } + else { + return(i) # me quedo en la misma isla + } + } +#+end_src + +#+REVEAL: split +#+begin_src R :exports none :results none + pasos <- 100000; iteraciones <- numeric(pasos) + iteraciones[1] <- sample(1:7, 1) # isla inicial + for (j in 2:pasos) { + iteraciones[j] <- camina_isla(iteraciones[j - 1]) + } + caminata <- tibble(paso = 1:pasos, isla = iteraciones) +#+end_src + +#+HEADER: :width 1200 :height 300 :R-dev-args bg="transparent" +#+begin_src R :file images/caminata-cafe.jpeg :exports results :results output graphics file + plot_caminata <- ggplot(caminata[1:500, ], aes(x = paso, y = isla)) + + geom_point(size = 0.8) + + geom_path(alpha = 0.5) + + labs(title = "Caminata aleatoria") + + scale_x_continuous(trans = "log10", "Tiempo", breaks = c(1, 2, 5, 20, 100, 500)) + + scale_y_continuous( expression(theta)) + sin_lineas + plot_dist <- ggplot(caminata, aes(x = isla)) + + geom_bar(fill = "darkgray", aes(y = (..count..)/sum(..count..))) + + geom_bar(data = islas |> mutate(prop = pob/sum(pob)), + aes(x = islas, y = prop), fill = "steelblue", alpha = .3, stat = "identity") + + scale_x_continuous(expression(theta), breaks = 1:10) + + ylim(0,.5) + + labs(title = "Distribución objetivo (Histograma)", + y = expression(hat(pi)(theta))) + sin_lineas + coord_flip() + plot_caminata + plot_dist +#+end_src +#+caption: Caminata aleatoria en un archipiélago de 7 islas. +#+RESULTS: +[[file:../images/caminata-cafe.jpeg]] + +#+begin_src R :exports none :results none :eval never :tangle no + ## Animación histograma ----------------------------------- + library(gganimate) + res <- caminata |> + mutate(tiempo = cut(paso, breaks = seq(0, n(), by = 10))) |> + group_by(isla, tiempo) |> + count() |> + ungroup() |> + complete(tiempo, nesting(isla), fill = list(n = 0)) |> + group_by(isla) |> + mutate(count = cumsum(n)) |> + group_by(tiempo) |> + mutate(prop = count/sum(count)) |> + arrange(tiempo, isla) |> + ungroup() + + anim <- res |> + mutate(tiempo = as.numeric(tiempo)) |> + filter(tiempo <= 1500) |> + ggplot(aes(x = isla, y = prop)) + + geom_bar(fill = "darkgray", stat = "identity") + + coord_flip() + sin_lineas + + geom_bar(data = islas |> mutate(prop = pob/sum(pob)), + aes(x = islas, y = prop), fill = "steelblue", alpha = .3, stat = "identity") + + scale_x_continuous(expression(theta), breaks = 1:10) + + transition_states(tiempo, transition_length = 2, state_length = 1) + + ease_aes("exponential-out") + + animate(anim, renderer = ffmpeg_renderer(), height = 300, width = 900) + + anim_save("./images/islas-histograma.mp4") + +#+end_src + +** Conclusiones + +- La estrategia del vendedor le permitirá, en el ~largo plazo~, visitar todas las islas. +- El tiempo que pasa en cada isla$^\dagger$ corresponde a la población relativa. +- Al principio, aún no representa dicha proporción. + +* Generalizando... + +Supongamos que tenemos un modelo +\begin{gather} +Y| \mu \sim \mathsf{N}(\mu, 0.75^2)\,,\\ +\mu \sim \mathsf{N}(0,1^2)\,. +\end{gather} + +~Verifica~ que bajo la observación $y = 6.25$ la distribución posterior que nos interesa es +\begin{gather} +\mu | y \sim \mathsf{N}(4, 0.6^2)\,. +\end{gather} + +#+REVEAL: split +~Vamos a suponer~ que *no* sabemos muestrear de una Normal. Asi que usaremos una +estrategia parecida que con el vendedor de galletas. La estrategia será: +1. Generar una propuesta $\mu_\star$ para cambiarnos de nuestro valor actual $\mu_t$. +2. Decidir si nos movemos utilizando un cociente que tome en cuenta los pesos relativos. + +** Pseudo-código +- Vamos a proponer una ''moneda'' para lanzar la *dirección* de movimiento. Esto lo haremos con + + \begin{align} + \mu_\star | \mu_t \sim \mathsf{Uniforme}( \mu_t - \omega, \mu_t + \omega)\,. + \end{align} + +#+REVEAL: split +- Vamos a decidir si nos movemos de acuerdo a los pesos relativos + \begin{align} + \alpha(\mu_t, \mu_\star) = \min \left\lbrace1 , \frac{\pi(\mu_\star|y)}{\pi(\mu_t|y)} \right\rbrace\,. + \end{align} + +** Desentrañando + +Escribamos el cociente en términos de la densidad de la distribución posterior y simplifiquemos. ¿Qué observas? + +** Implementación + +Veamos cómo implementarlo. Vamos a suponer una distribución de muestreo con un intervalo de longitud 2. Es decir, $\omega = 1$. + +#+begin_src R :exports none :results none + ## Caminata en espacio continuo ------------------------ +#+end_src + +#+REVEAL: split +#+caption: Modelo de muestreo uniforme. +#+begin_src R :exports code :results none + ModeloUniforme <- + R6Class("ProbabilityModel", + list( + a = NA, + b = NA, + initialize = function(a = 0, b = 1){ + self$a = a + self$b = b + }, + sample = function(n = 1){ + runif(n, self$a, self$b) + }, + density = function(x, log = TRUE){ + dunif(x, self$a, self$b, log = log) + } + )) +#+end_src + +#+REVEAL: split +#+caption: Nuestra segunda cadena de Markov. +#+begin_src R :exports code :results none + crea_cadena_markov <- function(objetivo, muestreo){ + function(niter){ + muestras <- matrix(nrow = niter, ncol = 2) + ## Empezamos en algun lugar + estado <- muestreo$sample() + muestras[1,1] <- 1 + muestras[1,2] <- estado + for (ii in 2:niter){ + ## Generamos un candidato (caminata aleatoria) + propuesta <- estado + muestreo$sample() + p_propuesta <- objetivo$density(propuesta, log = FALSE) + p_estado <- objetivo$density(estado, log = FALSE) + ## Evaluamos probabilidad de aceptar + if (runif(1) < p_propuesta/p_estado) { + muestras[ii, 1] <- 1 ## Aceptamos + muestras[ii, 2] <- propuesta + } else { + muestras[ii, 1] <- 0 ## Rechazamos + muestras[ii, 2] <- estado + } + estado <- muestras[ii, 2] + } + colnames(muestras) <- c("accept", "value") + muestras + } + } +#+end_src + +#+REVEAL: split +#+begin_src R :exports code :results none + objetivo <- ModeloNormal$new(mean = 4, sd = .6) + muestreo <- ModeloUniforme$new(a = -1, b = 1) + + mcmc <- crea_cadena_markov(objetivo, muestreo) + muestras <- mcmc(5000) +#+end_src + +#+HEADER: :width 1200 :height 300 :R-dev-args bg="transparent" +#+begin_src R :file images/primer-mcmc.jpeg :exports results :results output graphics file + g1 <- muestras |> + as.tibble() |> + mutate(iter = 1:n()) |> + ggplot(aes(iter, value)) + + geom_line() + sin_lineas + + ggtitle(paste("Trayectoria, eficiencia: ", mean(muestras[,1]))) + + g2 <- muestras |> + as.tibble() |> + ggplot(aes(value)) + + geom_histogram(aes(y = ..density..)) + + stat_function(fun = objetivo$density, + args = list(log = FALSE), + color = "salmon", + size = 2) + sin_lineas + + ggtitle("Histograma") + + g1 + g2 +#+end_src +#+caption: Nuestra segunda cadena de Markov. +#+RESULTS: +[[file:../images/primer-mcmc.jpeg]] + +*** Ejercicio: +:PROPERTIES: +:reveal_background: #00468b +:END: + +Sin modificar el número de iteraciones, considera cambiar la dispersión de la distribución de muestreo. +- ¿Qué observas si $\omega = 0.01$? +- ¿Qué observas si $\omega = 100$? + +*** Ejercicio: +:PROPERTIES: +:reveal_background: #00468b +:END: + +Regresa a nuestro ejemplo conjugado Beta-Binomial. Considera una previa $\theta \sim \mathsf{Beta}(2,3)$ y una verosimilitud $Y|\theta \sim \mathsf{Binomial}(2, \theta)$. Escribe la distribución posterior asumiendo $Y = k$. + +#+REVEAL: split +Para este caso tenemos un ligero inconveniente. El soporte para $\theta$ es el intervalo cerrado $[0,1]$ y utilizar una propuesta como en el caso anterior nos podría colocar (casi seguramente) fuera del intervalo. Así que lo que haremos será un pequeña modificación a cómo generamos nuestra propuesta y cómo evaluamos la probabilidad de aceptar dicha propuesta. + +#+REVEAL: split +- Vamos a generar propuestas de la siguiente manera + \begin{align} + \theta_\star | \theta_t \sim \mathsf{Beta}(\alpha, \beta)\,. + \end{align} +- Vamos a calcular la probabilidad de aceptar dicho movimiento a través de + \begin{align} + \alpha(\theta_t, \theta_\star) = \min \left\lbrace 1, \frac{\pi(\theta_\star|y)}{\pi(\theta_t|y)} \cdot \frac{g(\theta_t)}{g(\theta_\star)}\right\rbrace\,, + \end{align} + donde $g$ denota la densidad de la distribución de muestreo definida arriba. + +*** Tarea: +:PROPERTIES: +:reveal_background: #00468b +:END: +Modifica el código de clase para implementar este muestreador. Utiliza distintas configuraciones de $a,b$ para la distribución de propuesta. Compara con muestras exactas del modelo posterior bajo la observación $Y = 1$. + +* El método Metropolis-Hastings + +La forma más general que tenemos para generar una cadena de muestras es el método de Metropolis-Hastings. +#+REVEAL: split + +- Generamos propuestas en cada iteración por medio de + \begin{align} + \theta_\star | \theta_t \sim q( \theta_\star | \theta_t )\,. + \end{align} +- Calculamos la probabilidad de aceptar la propuesta como + \begin{align} + \alpha(\theta_t, \theta_\star) = \min \left\lbrace 1, \frac{\pi(\theta_\star)}{\pi(\theta_t)} \cdot \frac{q(\theta_t|\theta_\star)}{q(\theta_\star|\theta_t)}\right\rbrace\,, + \end{align} + donde la notación hace énfasis en que este mecanismo puede generar muestras de + la distribución $\pi$ utilizando un generador $q$. + +** Ejercicio (3) +:PROPERTIES: +:reveal_background: #00468b +:END: + +- Repasemos ~los métodos anteriores~. +- ¿Qué pasa si desconocemos la constante de normalización de la distribución objetivo? + +** Distribución propuesta + +El /arte/ está en proponer una distribución de muestreo eficiente. Como ya hemos +discutido, si no está bien calibrada podríamos tener un comportamiento no +deseado. Supongamos que queremos muestrear de una $\mathsf{Gamma}(20, +100)$. Para esto veamos tres configuraciones de la distribución de muestreo que será +$\mathsf{N}(\theta_t, \sigma^2)$. + +#+begin_src R :exports none :results none + ## Implementacion Metropolis Hastings ----------------------- + ModeloGamma <- + R6Class("ProbabilityModel", + list( + shape = NA, + rate = NA, + initialize = function(a = 0, b = 1){ + self$shape = a + self$rate = b + }, + sample = function(n = 1){ + rgamma(n, shape = self$shape, rate = self$rate) + }, + density = function(x, log = TRUE){ + dgamma(x, shape = self$shape, rate = self$rate, log = log) + } + )) +#+end_src + +#+begin_src R :exports none :results none + ### Muestreador Metropolis-Hastings ------------------------- + crea_metropolis_hastings <- function(objetivo, muestreo){ + ## Este muestreador aprovecha la simetría de la propuesta + function(niter){ + ## Empezamos en algun lugar + estado <- muestreo$sample() + ndim <- length(estado) + muestras <- matrix(nrow = niter, ncol = ndim + 1) + muestras[1,2:(ndim+1)] <- estado + muestras[1,1] <- 1 + for (ii in 2:niter){ + propuesta <- estado + muestreo$sample() + log_pi_propuesta <- objetivo$density(propuesta) + log_pi_estado <- objetivo$density(estado) + log_alpha <- log_pi_propuesta - log_pi_estado + + if (log(runif(1)) < log_alpha) { + muestras[ii, 1] <- 1 ## Aceptamos + muestras[ii, 2:(ndim+1)] <- propuesta + } else { + muestras[ii, 1] <- 0 ## Rechazamos + muestras[ii, 2:(ndim+1)] <- estado + } + estado <- muestras[ii, 2:(ndim+1)] + } + if (ndim == 1) {colnames(muestras) <- c("accept", "value")} + muestras + } + } +#+end_src + + +#+REVEAL: split +#+HEADER: :width 1200 :height 300 :R-dev-args bg="transparent" +#+begin_src R :file images/mh-pasochico.jpeg :exports results :results output graphics file + set.seed(108727) + objetivo <- ModeloGamma$new(a = 20, b = 100) + muestreo <- ModeloNormal$new(sd = 0.001) + mcmc_chico <- crea_metropolis_hastings(objetivo, muestreo) + + g1 <- mcmc_chico(3000) |> + as.tibble() |> + mutate(t = 1:n()) |> + ggplot(aes(t, value)) + + geom_line() + sin_lineas + ylab(expression(theta)) + + ylim(0, 0.5) + + g2 <- tibble(x = rgamma(10000, 20, 100)) |> + ggplot(aes(y = x, x = "")) + + geom_violin() + + ylab("") + sin_lineas + + ylim(0, 0.5) + + g1 + g2 + plot_layout(widths = c(5, 1)) +#+end_src +#+caption: Metropolis-Hastings en acción con un tamaño de paso muy pequeño. +#+RESULTS: +[[file:../images/mh-pasochico.jpeg]] + +#+REVEAL: split +#+HEADER: :width 1200 :height 300 :R-dev-args bg="transparent" +#+begin_src R :file images/mh-pasogrande.jpeg :exports results :results output graphics file + set.seed(108727) + muestreo <- ModeloNormal$new(sd = 20) + mcmc_grande <- crea_metropolis_hastings(objetivo, muestreo) + + g1 <- mcmc_grande(3000) |> + as.tibble() |> + mutate(t = 1:n()) |> + ggplot(aes(t, value)) + + geom_line() + sin_lineas + ylab(expression(theta)) + + ylim(0, 0.5) + + g2 <- tibble(x = rgamma(10000, 20, 100)) |> + ggplot(aes(y = x, x = "")) + + geom_violin() + + ylab("") + sin_lineas + + ylim(0, 0.5) + + g1 + g2 + plot_layout(widths = c(5, 1)) +#+end_src +#+caption: Metropolis-Hastings en acción con un tamaño de paso muy grande. +#+RESULTS: +[[file:../images/mh-pasogrande.jpeg]] + +#+REVEAL: split +#+HEADER: :width 1200 :height 300 :R-dev-args bg="transparent" +#+begin_src R :file images/mh-pasojusto.jpeg :exports results :results output graphics file + set.seed(108727) + muestreo <- ModeloNormal$new(sd = 0.1) + mcmc_justo <- crea_metropolis_hastings(objetivo, muestreo) + + g1 <- mcmc_justo(3000) |> + as.tibble() |> + mutate(t = 1:n()) |> + ggplot(aes(t, value)) + + geom_line() + sin_lineas + ylab(expression(theta)) + + ylim(0, 0.5) + + g2 <- tibble(x = rgamma(10000, 20, 100)) |> + ggplot(aes(y = x, x = "")) + + geom_violin() + + ylab("") + sin_lineas + + ylim(0, 0.5) + + g1 + g2 + plot_layout(widths = c(5, 1)) +#+end_src +#+caption: Metropolis-Hastings en acción con un tamaño de paso /justo/. +#+RESULTS: +[[file:../images/mh-pasojusto.jpeg]] + +#+REVEAL: split +#+begin_src R :exports results :results org + tibble(configuracion = c("Paso chico", "Paso grande", "Paso justo"), + cadena = c(mcmc_chico, mcmc_grande, mcmc_justo)) |> + mutate(muestras = map(cadena, function(x) { + set.seed(108727) + x(3000) |> + as.tibble() + })) |> + unnest(muestras) |> + group_by(configuracion) |> + summarise(media = mean(value), + tasa.aceptacion = mean(accept)) |> + rbind(tibble(configuracion = "Teorica", + media = objetivo$shape/objetivo$rate, + tasa.aceptacion = NA)) +#+end_src + +#+RESULTS: +#+begin_src org +# A tibble: 3 × 3 + configuracion media tasa.aceptacion + +1 Paso chico 0.0863 0.944 +2 Paso grande 0.309 0.00667 +3 Paso justo 0.197 0.463 +#+end_src + +#+REVEAL: split +#+HEADER: :width 1200 :height 300 :R-dev-args bg="transparent" +#+begin_src R :file images/mh-largoplazo.jpeg :exports results :results output graphics file :eval never + set.seed(108727) + + g1 <- mcmc_chico(1000000) |> + as.tibble() |> + mutate(t = 1:n()) |> + ggplot(aes(t, value)) + + geom_line() + sin_lineas + ylab(expression(theta)) + + ylim(0, 0.5) + + g2 <- tibble(x = rgamma(10000, 20, 100)) |> + ggplot(aes(y = x, x = "")) + + geom_violin() + + ylab("") + sin_lineas + + ylim(0, 0.5) + + g1 + g2 + plot_layout(widths = c(5, 1)) +#+end_src +#+caption: Metropolis-Hastings en acción con un tamaño de paso /pequeño/ y un periodo suficientemente amplio. +#+RESULTS: +[[file:../images/mh-largoplazo.jpeg]] + +* En más dimensiones + +Consideremos la siguiente distribución objetivo +\begin{align} +\theta \sim \mathsf{N}(\textsf{m}, \textsf{S}), \qquad \textsf{m} = (1,2)^\top, \qquad \mathsf{S} = \begin{pmatrix}1 & .75\\.75 &1 \end{pmatrix}\,, +\end{align} +y utilicemos el modelo de muestreo +\begin{align} +\theta \sim \mathsf{N}(\mathsf{0}, \mathsf{\Sigma}), \qquad \mathsf{0} \in \mathbb{R}^2, \qquad \mathsf{\Sigma} =\sigma^2 \cdot \begin{pmatrix}1 & 0\\0 &1 \end{pmatrix}\,. +\end{align} + +#+begin_src R :exports none :results none + ## En mas dimensiones ------------------------------- +#+end_src +#+REVEAL: split +#+caption: Modelo de muestreo multivariado. +#+begin_src R :exports code :results none + library(mvtnorm) + ModeloNormalMultivariado <- + R6Class("ProbabilityModel", + list( + mean = NA, + cov = NA, + initialize = function(mu = 0, sigma = 1){ + self$mean = mu + self$cov = sigma |> as.matrix() + }, + sample = function(n = 1){ + rmvnorm(n, mean = self$mean, sigma = self$cov) + }, + density = function(x, log = TRUE){ + dmvnorm(x, self$mean, self$cov, log = log) + } + )) +#+end_src + +#+begin_src R :exports none :results none + mu <- c(1, 2) + Sigma <- matrix(c(1, .75, .75, 1), nrow = 2) + objetivo <- ModeloNormalMultivariado$new(mu, Sigma) + + + genera_experimento <- function(sigma){ + muestreo <- ModeloNormalMultivariado$new(c(0,0), + sigma * diag(c(1,1))) + set.seed(10) + mcmc_multi <- crea_metropolis_hastings(objetivo, muestreo) + mcmc_multi(50) |> + as.tibble() + } +#+end_src + +#+REVEAL: split +#+HEADER: :width 1200 :height 400 :R-dev-args bg="transparent" +#+begin_src R :file images/multinormal-propuestas-mh.jpeg :exports results :results output graphics file + set.seed(108727) + ## Para dibujar las curvas de nivel - distribucion objetivo + plot.grid <- expand_grid(x = seq(-2,5, by = 7/99), y = seq(-1,5, by = 6/99)) + plot.grid <- plot.grid %>% + mutate(density.target = dmvnorm(plot.grid, mean = mu, sigma = Sigma)) + plot.breaks.target <- plot.grid %>% + summarise(breaks = quantile(density.target, probs = c(.67, .90, .99, 1))) %>% + pull(breaks) + + ## Caminatas aleatorias + muestras.normal <- tibble(sigma = c(.1, .75, 2.33/sqrt(2), 5)) |> + mutate(muestras = map(sigma, genera_experimento)) |> + unnest(muestras) + + ## Para dibujar las curvas de nivel - distribucion propuesta + contours.proposal <- muestras.normal |> + filter(sigma == 2.33/sqrt(2)) |> + slice(1,3,7) |> mutate(id = 1:3) |> + nest(location = c(V2, V3)) |> + mutate(density.proposal = map(location, + function(x){ + dmvnorm(plot.grid |> select(x,y), + mean = as.matrix(x), + sigma = 1.65 * diag(c(1,1))) + }), + coords = list(plot.grid |> select(x,y))) |> + mutate(breaks.proposal = map(density.proposal, quantile, probs = c(.67,.90,.99))) + + contours.proposal |> + unnest(location, density.proposal, coords) |> + ggplot(aes(x, y, z = density.proposal)) + + geom_contour_filled(bins = 4) + scale_fill_brewer(palette = "Purples") + + geom_point(data = contours.proposal |> unnest(location), + aes(V2, V3), shape = 19, size = 10) + + geom_contour(data = plot.grid, aes(x,y,z = density.target), + breaks = plot.breaks.target, color = "black") + + xlab(expression(x[1])) + ylab(expression(x[2])) + + facet_wrap(~id) + sin_lineas + coord_equal() + sin_leyenda +#+end_src +#+caption: Propuestas Gaussianas (morado) contra densidad objetivo (línea sólida). Tres primeras iteraciones. +#+RESULTS: +[[file:../images/multinormal-propuestas-mh.jpeg]] + +#+REVEAL: split +#+HEADER: :width 1200 :height 400 :R-dev-args bg="transparent" +#+begin_src R :file images/multinormal-aceptacion-mh.jpeg :exports results :results output graphics file + contours.proposal |> + mutate(denominator = map(location, objetivo$density), + numerator = map(coords , objetivo$density)) |> + unnest(numerator, denominator) |> + mutate(metropolis.hastings = ifelse(exp(numerator-denominator) < 1, + exp(numerator-denominator), 1.00), + contours.proposal |> unnest(coords) |> select(x,y), + contours.proposal |> unnest(density.proposal), + alpha = metropolis.hastings * density.proposal) |> + ggplot(aes(x, y, z = log(metropolis.hastings + 1))) + + geom_contour_filled(bins = 7) + + scale_fill_brewer(palette = "Purples", direction = 1) + + facet_wrap(~id) + sin_lineas + coord_equal() + sin_leyenda + + geom_point(data = contours.proposal |> unnest(location), + aes(V2, V3), inherit.aes = FALSE, shape = 19, size = 10) + + xlab(expression(x[1])) + ylab(expression(x[2])) +#+end_src +#+caption: Probabilidad de aceptación de la propuesta de transición. +#+RESULTS: +[[file:../images/multinormal-aceptacion-mh.jpeg]] + + +#+REVEAL: split +#+HEADER: :width 1200 :height 400 :R-dev-args bg="transparent" +#+begin_src R :file images/multinormal-transicion-mh.jpeg :exports results :results output graphics file + contours.proposal |> + mutate(denominator = map(location, objetivo$density), + numerator = map(coords , objetivo$density)) |> + unnest(numerator, denominator) |> + mutate(metropolis.hastings = ifelse(exp(numerator-denominator) < 1, + exp(numerator-denominator), 1.00), + contours.proposal |> unnest(coords) |> select(x,y), + contours.proposal |> unnest(density.proposal), + alpha = metropolis.hastings * density.proposal) |> + ggplot(aes(x, y, z = alpha)) + + geom_contour_filled(bins = 5) + + scale_fill_brewer(palette = "Purples") + + facet_wrap(~id) + sin_lineas + coord_equal() + sin_leyenda + + geom_point(data = contours.proposal |> unnest(location), + aes(V2, V3), inherit.aes = FALSE, shape = 19, size = 10) + + xlab(expression(x[1])) + ylab(expression(x[2])) +#+end_src +#+caption: Probabilidad de transición (morado) = probabilidad de proponer un nuevo estado multiplicada por la probabilidad de aceptar dicha transición. +#+RESULTS: +[[file:../images/multinormal-transicion-mh.jpeg]] + +#+begin_src R :exports none :results none :eval never :tangle no + ## + muestreo <- ModeloNormalMultivariado$new(c(0,0), 1.65 * diag(c(1,1))) + set.seed(10) + mcmc_multi <- crea_metropolis_hastings(objetivo, muestreo) + + anim <- mcmc_multi(5000) |> + as.tibble() |> + mutate(tiempo = seq(1,5000)) |> + ggplot(aes(x = V2, y = V3)) + + geom_contour_filled(data = plot.grid, aes(x,y,z = density.target), + breaks = plot.breaks.target, inherit.aes = FALSE) + + scale_fill_brewer(palette = "Reds") + + ## geom_path(alpha = .3) + + geom_point() + + xlab(expression(x[1])) + ylab(expression(x[2])) + + sin_lineas + coord_equal() + sin_leyenda + + transition_reveal(tiempo) + + shadow_trail(alpha = .3, distance = 0.01) + + ## shadow_mark(past=TRUE, future = TRUE) + + ease_aes("exponential-out") + + animate(anim, renderer = ffmpeg_renderer(), height = 300, width = 300) + + anim_save("./images/caminata-aleatoria.mp4") +#+end_src + + + +#+REVEAL: split +#+HEADER: :width 1200 :height 400 :R-dev-args bg="transparent" +#+begin_src R :file images/multinormal.jpeg :exports results :results output graphics file + ## Caminatas aleatorias + muestras.normal |> + ggplot(aes(x = V2, y = V3)) + + geom_contour_filled(data = plot.grid, aes(x,y,z = density.target), + breaks = plot.breaks.target) + + scale_fill_brewer(palette = "Reds") + + geom_path() + geom_point() + + facet_wrap(~round(sigma,2), nrow = 1) + + xlab(expression(x[1])) + ylab(expression(x[2])) + + sin_lineas + coord_equal() + sin_leyenda +#+end_src +#+caption: Caminata aleatoria utilizando Metropolis-Hastings para $\theta\in \mathbb{R}^2$. +#+RESULTS: +[[file:../images/multinormal.jpeg]] + + + +* ¿Por qué funciona? + +Ya vimos cómo funciona y describimos una versión suficientemente +robusta. Ahora estudiaremos el por qué esa manera de operar las transiciones nos +lleva a tener un mecanismo que genera muestras de la distribución (en el largo +plazo). + +#+REVEAL: split +Para esto tenemos que preguntarnos sobre las probabilidades de transición entre +dos estados. Es decir, la probabilidad de movernos al estado $\theta_\star$ +condicional en estar en $\theta$. Lo denotamos por +\begin{align} +\mathbb{P}\left( \theta_{t + 1} = \theta_\star | \theta_t = \theta\right)\,. +\end{align} + +#+REVEAL: split +Si el algoritmo es capaz de mantener un balance entre las probabilidades +condicionales entre dos estados de acuerdo a su frecuencia relativa, entonces el +algoritmo será capaz de preservar las frecuencias. + +#+REVEAL: split +En palabras (bueno...), buscamos que +\begin{align} +\frac{\mathbb{P}\left( \theta_{t + 1} = \theta_\star | \theta_t = \theta\right)}{\mathbb{P}\left( \theta_{t + 1} = \theta | \theta_t = \theta_\star\right)} = \frac{\pi(\theta_\star)}{\pi(\theta)}\,, +\end{align} +donde $\pi(\cdot)$ denota la probabilidad objetivo. + +#+REVEAL: split +Sólo nos falta calcular la probabilidad de transición. Esto lo logramos con dos +pasos: 1) generar la propuesta y 2) aceptar o rechazar la propuesta. Por lo tanto +\begin{align} +\mathbb{P}\left( \theta_{t + 1} = \theta_\star | \theta_t = \theta\right) = q(\theta_\star | \theta ) \cdot \alpha(\theta, \theta_\star) = q(\theta_\star | \theta ) \cdot \min \left\lbrace 1, \frac{\pi(\theta_\star)}{\pi(\theta)} \cdot \frac{q(\theta|\theta_\star)}{q(\theta_\star|\theta)}\right\rbrace\,. +\end{align} + +*** ~Definición~ [Invarianza]: +Decimos que la distribución $\pi$ es ~invariante~ ante un +mecanismo de transición Markoviana ($p(u, v)$) si satisface que +\begin{align} +\int \pi(u)\, p(u, v) \text{d}u = \pi(v) \,. +\end{align} + +#+BEGIN_NOTES +Lo que aprendemos de esto es que si tenemos un mecanismo de transición +Markoviana que satisface las ecuaciones de balance entonces se mantendrá el +comportamiento aleatorio de la distribución objetivo. Lo importante es que la +transición preserva la distribución objetivo. +#+END_NOTES + +*** ~Lema~ [Comportamiento asintótico de Metropolis-Hastings]: + +El mecanismo de MH descrito anteriormente tiene como distribución límite $\pi(\cdot)$. + +#+BEGIN_NOTES +Lo que aprendemos de esto es que en particular MH preserva las ecuaciones de +balance. Por lo tanto, si la cadena empieza en la distribución que nos interesa, +entonces se mantendrá en ese comportamiento. Estudiar formalmente las +condiciones y la tasa de convergencia para llegar a esa distribución escapa a +los intereses del curso y se puede encontrar un tratamiento mas cuidadoso de +esto en citep:Meyn1993. Sin embargo, podemos entenderlo bajo el argumento que MH +busca las zonas de alta densidad. Tal como el vendedor ambulante prefería de +manera consistente las islas mas grandes. +#+END_NOTES + +bibliographystyle:abbrvnat +bibliography:references.bib + + diff --git a/org/math/Org_Mode_885465.org b/org/math/Org_Mode_885465.org new file mode 100644 index 0000000..9d2d49c --- /dev/null +++ b/org/math/Org_Mode_885465.org @@ -0,0 +1,825 @@ +# -*- mode: org; -*- +#+INCLUDE: theme/style.org +#+STARTUP: content +#+DESCRIPTION: org-mode features and summary +#+KEYWORDS: org-mode emacs summary literate programming documentation +#+TITLE: Org-mode + +* Org-Mode +** Overview + +Org-Mode is a mode built-in to Emacs that allows to store structured +data, information in text format - org-mode markdown that can be +exported to html, pdf, latex, markdown, github flavoured markdown +and more file formats. + +Features: + + - Everything stored in text format: The most portable format. + - Todo List. + - It can be used as a personal Wiki. + - Table editing, formating, built-in spreadsheet. + - Tags, Headlines + - Literate programming, Run code blocks, Create Interactive and + reproducible software documentation. + - Display and export Latex Formulas + - Display Pictures + - Many link formats + - Link to files, web, IRC, Usenet News groups + - Link to shell commands + - Links to trigger Emacs Functions + - Usefulness + - Authoring + - Write Software documentation with embedded snippets + - Literate Programming + - Reproducible Research + - Wiki + - Markdown + +Example: this document is now written in org-mode and the exported to +html and github flavoured markdown. + +file:images/document_in_org_mode1.png + +It also supports inline code blocks that can be evaluated and the +result printed in the document or displayed in the minibuffer. + +file:images/document_in_org_mode2.png + +** Key bindings and commands for org-mode :mode:org:key:binding: +*** Useful Commands + +| Command | Description | +|-------------------------------+-------------------------------------| +| | | +| *Display* | | +| M-x org-toggle-inline-images | Toggle images display | +| M-x org-toggle-latex-fragment | Toggle latex formulas display | +| M-x org-toggle-link-display | Toggle hyperlink display | +| | | +| *Export* | | +| M-x org-html-export-to-html | Export buffer to html file. | +| M-x org-latex-export-to-pdf | Export buffer to pdf file. | +| | | +| *Search* | | +| heml-occur | Useful quick search and navigation. | +| helm-org-in-buffer-headings | Filter org-mode files by headlines. | +| | | +*** Hyperlink + +| Key binding | Description | +|-------------+---------------------------| +| C-c C-l | Insert hyperlink at point | +| C-c C-o | Open hyperlink at point | +| | | + +*** Move within headlines + +| Key Binding | Description | +|--------------+----------------------------------------------------| +| M - | Insert headline at same level as the previous one. | +| C-c C-p | Move to previous headline | +| C-c C-n | Move to next headline | +| C-c C-u | Move to higher headline | +| M-[up] | Move headline, list row or table row up | +| M-[down] | Move headline, list item or table row down | +| M-[left] | Demote list item or headline | +| M-[right] | Promote list item or headline | + +*** Buffer Subtree + +| Key Binding | Description | +|-------------+-----------------------------------------------| +| shift-tab | Fold / Unfold headlines | +| C-x n s | Narrow the buffer subtree to current headline | +| C-c n w | Widen the view back | +| | | + +*** Table + +| Key Binding | Description | +|-------------+-----------------------------| +| C-c-! | Convert region into a table | +| | | + +*** Hyperlinks + +| Key Binding | Description | +|-------------+---------------------| +| C-c-C-o | Open a link | +| C-c-C-l | Insert/ Edit a link | +| | | + +** Markdown Summary +*** Text Formatting + +| Example | Code | +|------------------+--------------------| +| *bold* | =*bold*= | +| /italics/ | =/italics/= | +| */very strong/* | =*/very strong/*= | +| _underline_ | =_underline_= | +| ~verbatim~ | =~verbatim~= | +| +strike through+ | =+strike through+= | +| =inline code= | ==inline code== | +| | | + +*** Hyperlinks + + +| Description | Formatting | Output | +|---------------------------------+-------------------------------+-----------------------------| +| Link to a file | =file:/etc/fstab= | file:/etc/fstab | +| Link to a web page | =http://www.httpbing.org/get= | http://www.httpbing.org/get | +| Email | =mailto:dummy@gmail.com= | mailto:dummy@gmail.com | +| Usenet Link | =news:comp.emacs= | news:comp.emacs | +| Info - Documentation | =info:gcc= | info:gcc | +| Shell Command | =shell:uname%20-a= | shell:uname%20-a | +| Elisp code | =elisp:(info%20"gcc")= | [[elisp:(info%20"gcc")]] | +| Doi - Digital object identifier | =doi:10.1000/182= | doi:10.1000/182 | +| | | | + +Hyperlinks from org-contrib: + +| Description | Example | | +|-----------------+------------+--------------------| +| Link to manpage | =man:sed= | (require 'org-man) | + +*** Code Blocks +**** Summary + +| Description | Shortcut | Code | +|--------------------+----------+-------------------------------------| +| Soource code block | (org-babel-get-src-block-info) +("scala" "import java.awt.BorderLayout\nimport javax.swing.{JFrame, JPanel, JButton, JTextArea}\n\nval frame = new JFrame(\"Border Layout\")\nval btn1 = new JButton(\"North\")\nval btn2 = new JButton(\"South\")\nval btn3 = new JButton(\"Center\")\nval btn4 = new JButton(\"West\")\nval btn5 = new JButton(\"East\")\n\nframe.setLayout(new BorderLayout())\nframe.add(btn1, BorderLayout.NORTH)\nframe.add(btn2, BorderLayout.SOUTH)\nframe.add(btn3, BorderLayout.CENTER)\nframe.add(btn4, BorderLayout.WEST)\nframe.add(btn5, BorderLayout.EAST)\n\nframe.setSize(300, 400)\nframe.setVisible(true)" + ((:colname-names) + (:rowname-names) + (:result-params "replace") + (:result-type . value) + (:comments . "") + (:shebang . "") + (:cache . "no") + (:padline . "") + (:noweb . "no") + (:tangle . "/tmp/scalatest.scala") + (:exports . "code") + (:results . "replace") + (:hlines . "no") + (:session . "none")) + "" nil 0 2257) + +ELISP> +#+END_SRC + +*** Getting the programming language of the code block + +#+BEGIN_SRC elisp +ELISP> (car (org-babel-get-src-block-info)) +"scala" +ELISP> +#+END_SRC + +*** Getting the source code of the code block + +#+BEGIN_SRC elisp +ELISP> (cadr (org-babel-get-src-block-info)) +"import java.awt.BorderLayout\nimport javax.swing.{JFrame, JPanel, JButton, JTextArea}\n\nval frame = ..." +ELISP> + +ELISP> (print (cadr (org-babel-get-src-block-info))) + +"import java.awt.BorderLayout +import javax.swing.{JFrame, JPanel, JButton, JTextArea} + +val frame = new JFrame(\"Border Layout\") +val btn1 = new JButton(\"North\") +val btn2 = new JButton(\"South\") +val btn3 = new JButton(\"Center\") +val btn4 = new JButton(\"West\") +val btn5 = new JButton(\"East\") + +frame.setLayout(new BorderLayout()) +frame.add(btn1, BorderLayout.NORTH) +frame.add(btn2, BorderLayout.SOUTH) +frame.add(btn3, BorderLayout.CENTER) +frame.add(btn4, BorderLayout.WEST) +frame.add(btn5, BorderLayout.EAST) + +frame.setSize(300, 400) +frame.setVisible(true)" + +#+END_SRC + +*** Getting code block attributes + +#+BEGIN_SRC elisp + ELISP> (caddr (org-babel-get-src-block-info)) + ((:colname-names) + (:rowname-names) + (:result-params "replace") + (:result-type . value) + (:comments . "") + (:shebang . "") + (:cache . "no") + (:padline . "") + (:noweb . "no") + (:tangle . "/tmp/scalatest.scala") + (:exports . "code") + (:results . "replace") + (:hlines . "no") + (:session . "none")) + + ELISP> (assoc :exports (caddr (org-babel-get-src-block-info))) + (:exports . "code") + + ELISP> (cdr (assoc :exports (caddr (org-babel-get-src-block-info)))) + "code" + ELISP> + + ELISP> (assoc :tangle (caddr (org-babel-get-src-block-info))) + (:tangle . "/tmp/scalatest.scala") + + ELISP> (cdr (assoc :tangle (caddr (org-babel-get-src-block-info)))) + "/tmp/scalatest.scala" + ELISP> +#+END_SRC +*** Run a Scala code block + +This example is specific for the Scala language, but can be easily +adapated to other languages. + +Usage: + + 1. Place the cursos at the some scala code block + 2. run M-x org/run-scala-block + +It will run save the code block content to the file /tmp/scala-snippet.scala +and run the command =$ scala /tmp/scala-snippet.scala= in the +compiling mode. + +#+BEGIN_SRC elisp + (defun org/run-scala-block () + (interactive) + ;; Org-mode block contents + (let* ((content (cadr (org-babel-get-src-block-info))) + ;; File in that the contents will be saved. + (file "/tmp/scala-snippet.scala")) + ;; Execute the commands inside this special form + ;; in a temporary buffer + (with-temp-buffer + ;; Delete file if it exists + (if (file-exists-p file) (delete-file file)) + ;; Insert the code block contents in the temporary buffer + (insert content) + ;; Write the buffer contents to fil. + (append-to-file (point-min) (point-max) file)) + ;; Run the compilation command + (compile (format "scala %s" file)))) +#+END_SRC + +** Custom Protocols +*** Open directory with dired mode + +Org-mode already provides the protocol ~file:~ to open a +directory or file. The motivation to implement this protocol is that it +is unambiguous like file protocol and easy to search. + +Hyperlink syntax: ~dir:~ + + +#+BEGIN_SRC elisp +(add-hook 'org-mode-hook + (lambda () + (org-add-link-type "dir" #'dired nil))) +#+END_SRC + + +Org-mode file example: + +#+BEGIN_SRC +Log directory - dir:/var/log - [[dir:/var/log][Log directory]] + +System cofiguration - dir:/etc +#+END_SRC + +*** Open directory with system file manager + +Hyperlink format: ~dire:~ + +#+BEGIN_SRC elisp +(defvar default-file-manager-app "pcmanfm-qt") + +(defun org/protocol-dire (input) + (start-process "proc" ;; Process name + nil ;; Buffer name + + default-file-manager + input + )) + +(add-hook 'org-mode-hook + (lambda () + (org-add-link-type "dire" #'org/protocol-dire nil))) +#+END_SRC + +Example: + +#+BEGIN_SRC + +To open the directory file:/var/log in the system file +manager click on the hyperlink bellow. + + + - Hyperlink1: dire:/var/log + + - Hyperlink2: [[dire:/var/log][System Log directory]] + +#+END_SRC + + +[[file:images/org-mode-protocol-file-manager.png][file:images/org-mode-protocol-file-manager.png]] + +*** Man page + +Provides a hyperlink that displays a man page when clicked. + + +#+BEGIN_SRC elisp +(add-hook 'org-mode-hook + (lambda () + (org-add-link-type "man" #'woman nil))) +#+END_SRC + +Example: + +file test.org + +#+BEGIN_SRC +Click on the hyperlinks bellow to open the man pages: + +Gcc Man Page: + + - man:gcc + +C-function cbrt Man Page + + - man:cbrt + + - [[man:cbrt][C-function cbrt Man Page]] +#+END_SRC + +*** Elisp Documentation + +Provides clickable link that shows the the Elisp documentation. + +A link of format ~elisp-doc:add-hook~ will show the =add-hook= +documentation when clicked. + +Hyperlink format: ~elisp-doc:~ or ~[elisp-doc:]~ + +#+BEGIN_SRC elisp + (defun org/protocol-elisp-doc (function-symbol) + (princ function-symbol) + (describe-function (intern-soft function-symbol))) + + + (defun org/protocol-elisp-doc-html (path desc backend) + (cl-case backend + (html (format + "%s" + (documentation (intern-soft path)) + (or desc path))))) + + (add-hook 'org-mode-hook + (lambda () + (org-add-link-type "elisp-doc" + #'org/protocol-elisp-doc + #'org/protocol-elisp-doc-html))) + +#+END_SRC + +Example: + +file: ~/tmp/test.org~ + +#+BEGIN_SRC org-mode +Elisp documentation protocol: + +[[elisp-doc:add-hook][Function Add hook]] + +The function elisp-doc:start-process is used to start an asynchronous process. +#+END_SRC + + +This screenshot show what happens when the user clicks in the hyperlink. + +[[file:images/elisp-doc-org-mode-protocol-click.png][file:images/elisp-doc-org-mode-protocol-click.png]] + +Exported to html with: =M-x org-html-export-to-html= + +[[file:images/elisp-doc-org-mode-protocol.png][file:images/elisp-doc-org-mode-protocol.png]] +** Settings +*** General Settings + +Syntax highlight for code blocks ~#+BEGIN_SRC .. #+END_SRC~ + +#+BEGIN_SRC elisp +;; Syntax highlight for code blocks #+BEGIN_SRC .. #+END_SRC +;; +(setq org-src-fontify-natively t) +#+END_SRC + +Syntax highlight for latex fragments + +#+BEGIN_SRC elisp +(setq org-highlight-latex-and-related '(latex script entities)) +#+END_SRC + +*** Code Block - Org-babel + +Enable source code block in org files + +#+BEGIN_SRC elisp + +(org-babel-do-load-languages + 'org-babel-load-languages + '((emacs-lisp . t) + (sh . t) + (python . t) + (scheme . t) + (lisp . t) + (clojure . t) + (R . t) + (latex . t) + (ruby . t) + (C . t) + ;;; (C++ . t) + (ditaa . t) + (haskell . t) + ;; (fsharp . t) + ;; (java . t) + ;; (scala . t) +;; (javascript . t) + (maxima . t) + )) +#+END_SRC + +Disable Security confirmation: + +#+BEGIN_SRC elisp +;; Disable security confirmations +;; + +(setq ;; Confirmation for running coide blocks + org-confirm-babel-evaluate nil + ;; Confirmation for elisp links + org-confirm-elisp-link-function nil + ;; Confirmation for shell links + org-confirm-shell-link-function nil + + org-export-babel-evaluate nil + ) +#+END_SRC + diff --git a/org/math/latex_0d83c6.org b/org/math/latex_0d83c6.org new file mode 100644 index 0000000..94afc2e --- /dev/null +++ b/org/math/latex_0d83c6.org @@ -0,0 +1,36 @@ +#+title: Latex Support +#+published: true +#+position: 203 +#+type: document + + +** Inline Math +Orgajs supports inline math with latex math delimiters. + +#+begin_src org +If $$a^2=b$$ and \( b=2 \), then the solution must be either $$ a=+\sqrt{2} $$ or \[ a=-\sqrt{2} \]. +#+end_src + +With be rendered as follows. + +If $$a^2=b$$ and \( b=2 \), then the solution must be either $$ a=+\sqrt{2} $$ or \[ a=-\sqrt{2} \]. + +** Latex Block + +It also supports =\begin= commands. + +#+begin_src org +\begin{equation} +x=\sqrt{b} +\end{equation} +#+end_src + +Will be rendered + +\begin{equation} +x=\sqrt{b} +\end{equation} + +** Styling + +=@orgajs/rehype-latex= is the plugin for handling latex. It uses [[https://katex.org][katex]] underneath, so you will have to add the css link yourself in your website. Add the following to the =head=. diff --git a/rst/math/comprehensive_math_test_276a5e.rst b/rst/math/comprehensive_math_test_276a5e.rst new file mode 100644 index 0000000..30ffe3a --- /dev/null +++ b/rst/math/comprehensive_math_test_276a5e.rst @@ -0,0 +1,527 @@ +================================== +Using LaTeX syntax for mathematics +================================== + +.. role:: m(math) +.. default-role:: math +.. |latex| replace:: L\ :sup:`A`\ T\ :sub:`E`\ X + +.. contents:: + + +Introduction +============ + +Since version 0.8, Docutils supports mathematical content with a `"math" +directive`__ and `role`__. +The input format is *LaTeX math syntax*\ [#math-syntax]_ with support for +Unicode symbols. + + +.. [#math-syntax] The supported LaTeX commands include AMS extensions + (see, e.g., the `Short Math Guide`_). + + The support is limited to a subset of *LaTeX math* by the conversion + required for many output formats. For HTML, the `math_output`_ + configuration setting (or the corresponding ``--math-output`` command + line option) select between alternative output formats with different + subsets of supported elements. If a writer does not support math + typesetting at all, the content is inserted verbatim. + +__ https://docutils.sourceforge.io/docs/ref/rst/directives.html#math +__ https://docutils.sourceforge.io/docs/ref/rst/roles.html#math +.. _Short Math Guide: + http://mirrors.ctan.org/info/short-math-guide/short-math-guide.pdf +.. _math_output: + https://docutils.sourceforge.io/docs/user/config.html#math-output + + +Role and directive +================== + +The ``math`` role can be used for inline mathematical expressions: +``:math:`\psi(r) = \exp(-2r)``` will produce :m:`\psi(r)=\exp(-2r)`. +Inside the backtics you can write anything you would write between dollar +signs in a LaTeX document. + +For producing displayed math (like an ``equation*`` environment in a +LaTeX document) there is a ``math`` directive. If you write:: + + .. math:: \psi(r) = e^{-2r} + +you will get: + +.. math:: \psi(r) = e^{-2r} + +A more complex example is the definition of the Fourier transform + +.. math:: + + (\mathcal{F}f)(y) = + \frac{1}{\sqrt{2\pi}^{\ n}} + \int_{\mathbb{R}^n} f(x)\,e^{-\mathrm{i} y \cdot x} \,\mathrm{d} x. + + +.. tip:: + + If you put ``.. default-role:: math`` at the top of your + document, then you can write ```x^2``` instead of the longer + version: ``:math:`x^2```. You can also introduce an + abreviation like this ``.. role:: m(math)``. That will allow + you to write ``:m:`x^2``` or ```x^2`:m:``. + + +Not *all* math syntax constructs work with every output format, but basic +everyday-math should work. + +If a command or a special symbol is not desribed in this document, then +it is probably not implemented in the internal LaTeX -> MathML converter. + + +Commands +======== + + +.. class:: colwidths-auto + + ===================== ============================== ============================ + command example result + ===================== ============================== ============================ + ``\sqrt`` ``\sqrt{x^2-1}`` `\sqrt{x^2-1}` + ``\frac`` ``\frac{1}{2}`` `\frac{1}{2}` + ``\left``, ``\right`` ``\left(\frac{1}{2}\right)^n`` `\left(\frac{1}{2}\right)^n` + ===================== ============================== ============================ + + +Environments +============ + +Displayed math can use ``\\`` and ``&`` for line shifts and alignments:: + + .. math:: + + a & = (x + y)^2 \\ + & = x^2 + 2xy + y^2 + +LaTeX output will wrap it in an ``align*`` environment. +The result is: + +.. math:: + + a & = (x + y)^2 \\ + & = x^2 + 2xy + y^2 + +The ``matrix`` and ``cases`` environments can also contain ``\\`` and +``&``:: + + .. math:: + + \left(\begin{matrix} a & b \\ c & d \end{matrix}\right) + +Result: + +.. math:: + + \left(\begin{matrix} a & b \\ c & d \end{matrix}\right) + + +Mathematical symbols +==================== + +The following tables are adapted from the first edition of +"The LaTeX Companion" (Goossens, Mittelbach, Samarin). + +Accents +------- +.. class:: colwidths-auto + + =========== ============= =========== ============= ============== ================ + `\acute{x}` ``\acute{x}`` `\dot{t}` ``\dot{t}`` `\hat{H}` ``\hat{H}`` + `\bar{v}` ``\bar{v}`` `\ddot{t}` ``\ddot{t}`` `\mathring{x}` ``\mathring{x}`` + `\breve{x}` ``\breve{x}`` `\dddot{t}` ``\dddot{t}`` `\tilde{n}` ``\tilde{n}`` + `\check{x}` ``\check{x}`` `\grave{x}` ``\grave{x}`` `\vec{x}` ``\vec{x}`` + =========== ============= =========== ============= ============== ================ + +When adding an accent to an i or j in math, dotless variants can be +obtained with ``\imath`` and ``\jmath``: `\bar \imath`, `\hat{\jmath}` +(MathML drops the dot automatically). + +For adornment that span multiple symbols, see `top and bottom +embellishments`_. + +Font switches +------------- + +TeX’s *math alphabets* correspond to the +:t:`mathematical alphanumeric symbols` block in Unicode and the +"mathvariant" `style attribute`__ in MathML. They are “to be used for +mathematical variables where style variations are important +semantically”. + +__ https://developer.mozilla.org/en-US/docs/Web/MathML/Attribute + +.. class:: colwidths-auto + + =============== ============================ ========================== + command example result + =============== ============================ ========================== + ``\mathbf`` ``\mathbf{r}^2=x^2+y^2+z^2`` `\mathbf{r}^2=x^2+y^2+z^2` + ``\mathbb`` ``\mathbb{R \subset C}`` `\mathbb{R \subset C}` + ``\mathcal`` ``\mathcal{F}f(x)`` `\mathcal{F}f(x)` + ``\mathfrak`` ``\mathfrak{a}`` `\mathfrak{a}` + ``\mathit`` ``\mathit{\Gamma}`` `\mathit{\Gamma}` + ``\mathrm`` ``s_\mathrm{out}`` `s_\mathrm{out}` + ``\mathsf`` ``\mathsf x`` `\mathsf x` + ``\mathtt`` ``\mathtt{0.12}`` `\mathtt{0.12}` + =============== ============================ ========================== + +Additional alphabets are defined in LaTeX packages, e.g. + +.. class:: colwidths-auto + + =========== ============= ====================== + TeX command LaTeX package MathML "mathvariant" + =========== ============= ====================== + mathbfit isomath_ bold-italic + mathsfit isomath_ sans-serif-italic + mathsfbfit isomath_ sans-serif-bold-italic + mathscr mathrsfs_ script + =========== ============= ====================== +.. _isomath: https://www.ctan.org/pkg/isomath +.. _mathrsfs: https://www.ctan.org/pkg/mathrsfs + +This can be used to typeset vector symbols in **bold** *italic* +in line with the International Standard [ISO-80000-2]. +``\mathbfit{r}^2=x^2+y^2+z^2`` becomes + +.. math:: \mathbfit{r}^2=x^2+y^2+z^2. + + + +In contrast to the math alphabet selectors, ``\boldsymbol`` only changes +the *font weight*. In LaTeX, it can be used to get a bold version of any +mathematical symbol (for other output formats, results are mixed): + +.. math:: + \boldsymbol{abs(x) \pm \alpha \approx 3 \Gamma \quad \forall x \in R} + + + + +Arrows +------ +.. class:: colwidths-auto + + ===================== ======================= ===================== ======================= + `\leftarrow` ``\leftarrow`` `\Leftarrow` ``\Leftarrow`` + `\rightarrow` ``\rightarrow`` `\Rightarrow` ``\Rightarrow`` + `\leftrightarrow` ``\leftrightarrow`` `\Leftrightarrow` ``\Leftrightarrow`` + `\uparrow` ``\uparrow`` `\Uparrow` ``\Uparrow`` + `\downarrow` ``\downarrow`` `\Downarrow` ``\Downarrow`` + `\updownarrow` ``\updownarrow`` `\Updownarrow` ``\Updownarrow`` + + `\longleftarrow` ``\longleftarrow`` `\Longleftarrow` ``\Longleftarrow`` + `\longrightarrow` ``\longrightarrow`` `\Longrightarrow` ``\Longrightarrow`` + `\longleftrightarrow` ``\longleftrightarrow`` `\Longleftrightarrow` ``\Longleftrightarrow`` + + `\nearrow` ``\nearrow`` `\leftharpoonup` ``\leftharpoonup`` + `\searrow` ``\searrow`` `\rightharpoonup` ``\rightharpoonup`` + `\swarrow` ``\swarrow`` `\leftharpoondown` ``\leftharpoondown`` + `\nwarrow` ``\nwarrow`` `\rightharpoondown` ``\rightharpoondown`` + + `\mapsto` ``\mapsto`` `\hookleftarrow` ``\hookleftarrow`` + `\longmapsto` ``\longmapsto`` `\hookrightarrow` ``\hookrightarrow`` + ===================== ======================= ===================== ======================= + + +Binary operators +---------------- +.. class:: colwidths-auto + + ================== ==================== ================= =================== ================== ==================== + `*` ``*`` `\circledast` ``\circledast`` `\ominus` ``\ominus`` + `+` ``+`` `\circledcirc` ``\circledcirc`` `\oplus` ``\oplus`` + `-` ``-`` `\circleddash` ``\circleddash`` `\oslash` ``\oslash`` + `:` ``:`` `\cup` ``\cup`` `\otimes` ``\otimes`` + `\Cap` ``\Cap`` `\curlyvee` ``\curlyvee`` `\pm` ``\pm`` + `\Cup` ``\Cup`` `\curlywedge` ``\curlywedge`` `\rightthreetimes` ``\rightthreetimes`` + `\amalg` ``\amalg`` `\dagger` ``\dagger`` `\rtimes` ``\rtimes`` + `\ast` ``\ast`` `\ddagger` ``\ddagger`` `\setminus` ``\setminus`` + `\bigcirc` ``\bigcirc`` `\diamond` ``\diamond`` `\smallsetminus` ``\smallsetminus`` + `\bigtriangledown` ``\bigtriangledown`` `\div` ``\div`` `\sqcap` ``\sqcap`` + `\bigtriangleup` ``\bigtriangleup`` `\divideontimes` ``\divideontimes`` `\sqcup` ``\sqcup`` + `\boxdot` ``\boxdot`` `\dotplus` ``\dotplus`` `\star` ``\star`` + `\boxminus` ``\boxminus`` `\doublebarwedge` ``\doublebarwedge`` `\times` ``\times`` + `\boxplus` ``\boxplus`` `\gtrdot` ``\gtrdot`` `\triangleleft` ``\triangleleft`` + `\boxtimes` ``\boxtimes`` `\intercal` ``\intercal`` `\triangleright` ``\triangleright`` + `\bullet` ``\bullet`` `\leftthreetimes` ``\leftthreetimes`` `\uplus` ``\uplus`` + `\cap` ``\cap`` `\lessdot` ``\lessdot`` `\vee` ``\vee`` + `\cdot` ``\cdot`` `\ltimes` ``\ltimes`` `\veebar` ``\veebar`` + `\centerdot` ``\centerdot`` `\mp` ``\mp`` `\wedge` ``\wedge`` + `\circ` ``\circ`` `\odot` ``\odot`` `\wr` ``\wr`` + ================== ==================== ================= =================== ================== ==================== + + +Braces +------ +.. class:: colwidths-auto + + ============ ============ ============ ============== ======================== + `(` ``(`` `[` ``[`` `|` ``|`` `\{` ``\{`` `\langle` ``\langle`` + `)` ``)`` `]` ``]`` `|` ``|`` `\}` ``\}`` `\rangle` ``\rangle`` + ============ ============ ============ ============== ======================== + + +Greek letters +------------- +.. class:: colwidths-auto + + ========== ============ ========== ============ ========== ============ ============== =============== + `\Gamma` ``\Gamma`` `\alpha` ``\alpha`` `\mu` ``\mu`` `\omega` ``\omega`` + `\Delta` ``\Delta`` `\beta` ``\beta`` `\nu` ``\nu`` `\backepsilon` ``\backepsilon`` + `\Lambda` ``\Lambda`` `\gamma` ``\gamma`` `\xi` ``\xi`` `\digamma` ``\digamma`` + `\Omega` ``\Omega`` `\delta` ``\delta`` `\pi` ``\pi`` `\varepsilon` ``\varepsilon`` + `\Phi` ``\Phi`` `\epsilon` ``\epsilon`` `\rho` ``\rho`` `\varkappa` ``\varkappa`` + `\Pi` ``\Pi`` `\zeta` ``\zeta`` `\sigma` ``\sigma`` `\varphi` ``\varphi`` + `\Psi` ``\Psi`` `\eta` ``\eta`` `\tau` ``\tau`` `\varpi` ``\varpi`` + `\Sigma` ``\Sigma`` `\theta` ``\theta`` `\upsilon` ``\upsilon`` `\varrho` ``\varrho`` + `\Theta` ``\Theta`` `\iota` ``\iota`` `\phi` ``\phi`` `\varsigma` ``\varsigma`` + `\Upsilon` ``\Upsilon`` `\kappa` ``\kappa`` `\chi` ``\chi`` `\vartheta` ``\vartheta`` + `\Xi` ``\Xi`` `\lambda` ``\lambda`` `\psi` ``\psi`` + ========== ============ ========== ============ ========== ============ ============== =============== + + +Letterlike symbols +------------------ +.. class:: colwidths-auto + +======= ========== ============= =============== ========= =========== ========== ============ +`\Im` ``\Im`` `\forall` ``\forall`` `\aleph` ``\aleph`` `\eth` ``\eth`` +`\Re` ``\Re`` `\exists` ``\exists`` `\beth` ``\beth`` `\hbar` ``\hbar`` +`\mho` ``\mho`` `\complement` ``\complement`` `\gimel` ``\gimel`` `\hslash` ``\hslash`` +`\Bbbk` ``\Bbbk`` `\Finv` ``\Finv`` `\daleth` ``\daleth`` `\imath` ``\imath`` +`\ell` ``\ell`` `\Game` ``\Game`` `\nabla` ``\nabla`` `\partial` ``\partial`` +`\wp` ``\wp`` +======= ========== ============= =============== ========= =========== ========== ============ + + +Miscellaneous symbols +--------------------- +.. class:: colwidths-auto + +======== =============== =========== ============= ============== ================ ========== ============ +`\angle` ``\angle`` `\emptyset` ``\emptyset`` `\clubsuit` ``\clubsuit`` `\flat` ``\flat`` +`\colon` ``\colon`` [#]_ `\infty` ``\infty`` `\diamondsuit` ``\diamondsuit`` `\natural` ``\natural`` +`\cdots` ``\cdots`` `\neg` ``\neg`` `\heartsuit` ``\heartsuit`` `\sharp` ``\sharp`` +`\ddots` ``\ddots`` `\bot` ``\bot`` `\spadesuit` ``\spadesuit`` +`\ddots` ``\ddots`` `\top` ``\top`` +======== =============== =========== ============= ============== ================ ========== ============ + +.. [#] Punctuation (not ratio): + Compare spacing in `a\colon b\to c` and `a:b = c`. + + +Named operators +--------------- +.. class:: colwidths-auto + + ========= =========== ====== ======== ====== ======== ======= ========= + `\arccos` ``\arccos`` `\csc` ``\csc`` `\ker` ``\ker`` `\sec` ``\sec`` + `\arcsin` ``\arcsin`` `\deg` ``\deg`` `\lg` ``\lg`` `\sin` ``\sin`` + `\arctan` ``\arctan`` `\det` ``\det`` `\lim` ``\lim`` `\sinh` ``\sinh`` + `\arg` ``\arg`` `\dim` ``\dim`` `\ln` ``\ln`` `\sup` ``\sup`` + `\cos` ``\cos`` `\exp` ``\exp`` `\log` ``\log`` `\tan` ``\tan`` + `\cosh` ``\cosh`` `\gcd` ``\gcd`` `\max` ``\max`` `\tanh` ``\tanh`` + `\cot` ``\cot`` `\hom` ``\hom`` `\min` ``\min`` + `\coth` ``\coth`` `\inf` ``\inf`` `\Pr` ``\Pr`` + ========= =========== ====== ======== ====== ======== ======= ========= + +Named operators outside the above list can be typeset with +``\operatorname{name}``, e.g. `\operatorname{sgn}(-3) = -1`. + + +Relation symbols +---------------- +.. class:: colwidths-auto + + ================================ ================================ ================================ ================================ + `\Join` ``\Join`` `\approx` ``\approx`` `\asymp` ``\asymp`` `\bowtie` ``\bowtie`` + `\cong` ``\cong`` `\dashv` ``\dashv`` `\doteq` ``\doteq`` `\equiv` ``\equiv`` + `\frown` ``\frown`` `\ge` ``\ge`` `\geq` ``\geq`` `\gg` ``\gg`` + `\in` ``\in`` `\le` ``\le`` `\leq` ``\leq`` `\ll` ``\ll`` + `\mid` ``\mid`` `\models` ``\models`` `\neq` ``\neq`` `\ni` ``\ni`` + `\parallel` ``\parallel`` `\perp` ``\perp`` `\prec` ``\prec`` `\precsim` ``\precsim`` + `\propto` ``\propto`` `\sim` ``\sim`` `\simeq` ``\simeq`` `\smile` ``\smile`` + `\sqsubset` ``\sqsubset`` `\sqsubseteq` ``\sqsubseteq`` `\sqsupset` ``\sqsupset`` `\sqsupseteq` ``\sqsupseteq`` + `\subset` ``\subset`` `\subseteq` ``\subseteq`` `\succ` ``\succ`` `\succsim` ``\succsim`` + `\supset` ``\supset`` `\supseteq` ``\supseteq`` `\vdash` ``\vdash`` + ================================ ================================ ================================ ================================ + +negated relations +.. class:: colwidths-auto + + ============================= =================== + `\not\in` ``\not\in`` `\not =` ``\not =`` + `\not \equiv` ``\not \equiv`` + ============================= =================== + + +Variable-sized symbols +---------------------- +.. class:: colwidths-auto + + ================= =========================== ========================= ========================= ===================== + `\sum` ``\sum`` `\bigodot` ``\bigodot`` `\bigcap` ``\bigcap`` `\bigwedge` ``\bigwedge`` `\prod` ``\prod`` + `\int` ``\int`` `\bigoplus` ``\bigoplus`` `\bigcup` ``\bigcup`` `\bigvee` ``\bigvee`` `\coprod` ``\coprod`` + `\oint` ``\oint`` `\bigotimes` ``\bigotimes`` `\biguplus` ``\biguplus`` + ================= =========================== ========================= ========================= ===================== + +Larger symbols are used in displayed formulas: + +.. math:: + + \sum\ \int\ \oint \bigcap \prod \ldots + +Extensible delimiters +--------------------- +Unless you indicate otherwise, delimiters in math formulas remain at the +standard size regardless of the height of the enclosed material. To get +adaptable sizes, use ``\left`` and ``\right`` prefixes. + +.. math:: + + g(A,B,Y) = f \left(A,B,X=h^{[X]}(Y)\right) + +Use ``.`` for "empty" delimiters: + +.. math:: + + A = \left . \frac{1}{1-n}\, \right |_{n=0}^\infty + + +Top and bottom embellishments +----------------------------- + +Visually similar to accents_ but generally applied to multiple symbols. + +.. class:: colwidths-auto + + ========================== ============================ =========================== ============================= + `\widetilde{abi}` ``\widetilde{abi}`` `\widehat{abi}` ``\widehat{abi}`` + `\overline{abi}` ``\overline{abi}`` `\underline{abi}` ``\underline{abi}`` + `\overbrace{abi}` ``\overbrace{abi}`` `\underbrace{abi}` ``\underbrace{abi}`` + `\overleftarrow{abi}` ``\overleftarrow{abi}`` `\underleftarrow{abi}` ``\underleftarrow{abi}`` + `\overrightarrow{abi}` ``\overrightarrow{abi}`` `\underrightarrow{abi}` ``\underrightarrow{abi}`` + `\overleftrightarrow{abi}` ``\overleftrightarrow{abi}`` `\underleftrightarrow{abi}` ``\underleftrightarrow{abi}`` + ========================== ============================ =========================== ============================= + +Extensible arrows +----------------- + +TODO + + +Text +==== + +The main use of the command ``\text`` is for words or phrases in a +display. It is similar to ``\mbox`` in its effects but, unlike ``\mbox``, +automatically produces subscript-size text if used in a subscript, +``k_{\text{B}}T`` becomes `k_{\text{B}}T`. + +Whitespace is kept inside the argument: + +.. Math:: f_{[x_{i-1},x_i]} \text{ is monotonic for } i = 1,\,…,\,c+1 + + +Currently, math in text is not supported by LaTeX2MathML. + +Horizontal space +================ + +.. class:: colwidths-auto + + ================= ================== ============= + :m:`|\qquad|` ``|\qquad|`` 2 em + :m:`|\quad|` ``|\quad|`` 1 em + :m:`|\;|` ``|\;|`` thick + :m:`|\ |` ``|\ |`` standard + :m:`|\:|` ``|\:|`` medium + :m:`|\,|` ``|\,|`` thin + :m:`| |` ``| |`` none + :m:`|\!|` ``|\!|`` thin negative + `|\hspace{1ex}|` ``|\hspace{1ex}|`` custom + ================= ================== ============= + +ToDo +==== + +internal LaTeX2MathML + +* Math inside text: ``n - 1 \text{if $n$ is odd}``. +* Remove circular refs. +* Decimal numbers. + +* Shorthands for combined named operators + + ========== ============ ============= =============== ================== + `\liminf` ``\liminf`` `\varliminf` ``\varliminf`` `\underline{\lim}` + `\limsup` ``\limsup`` `\varlimsup` ``\varlimsup`` `\overline{\lim}` + `\injlim` ``\injlim`` `varinjlim` ``\varinjlim`` + `\projlim` ``\projlim`` `varprojlim` ``\varprojlim`` + ========== ============ ============= =============== ================== + +* Implement ``\circledS``? (in short-math-guide.pdf but not in mathematical Unicode characters) + + +Tests +========== + +Font changes +------------ + +Math alphabet macros change the default alphabet ("mathvariant" in +MathML), leaving some symbols unchanged: + +:normal: `abs(x) \pm \alpha \approx 3 \Gamma \quad \forall x \in R` +:mathrm: `\mathrm{abs(x) \pm \alpha \approx 3 \Gamma \quad \forall x \in R}` +:mathit: `\mathit{abs(x) \pm \alpha \approx 3 \Gamma \quad \forall x \in R}` +:mathsf: `\mathsf{abs(x) \pm \alpha \approx 3 \Gamma \quad \forall x \in R}` +:mathbb: `\mathbb{abs(x) \pm \alpha \approx 3 \Gamma \quad \forall x \in R}` +:mathbf: `\mathbf{abs(x) \pm \alpha \approx 3 \Gamma \quad \forall x \in R` + +Unicode supports the following blackboard-bold characters: +`\mathbb{a \ldots z A \ldots Z 0 \ldots 9 +\mathbb\Gamma \mathbb{\Pi} \mathbb {\Sigma}\mathbb\gamma \mathbb\pi}`. + +The package mathrsfs_ (and some drop-in replacements) define the ``\mathscr`` +macro that selects a differently shaped "script" alphabet. +Compare `\mathscr{A, B, …, Z, a, b, …, z}` +with `\mathcal{A, B, …, Z, a, b, …, z}`. + +.. _rsfs: https://ctan.org/pkg/mathrsfs + +Inferred s in MathML +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The elements , , , , , , +, and treat their contents as a single inferred mrow +formed from all their children. + +.. math:: a = \sqrt 2, b = \sqrt{1+x^2}, c = \sqrt\frac{sin(x)}{23} + +inline: :math:`a = \sqrt 2, b = \sqrt{1+x^2}, c = \sqrt\frac{sin(x)}{23}`. + +Accents vs. embellishments +-------------------------- + +MathML drops dots on "i" and "j" with accents: + +.. math:: \vec i \ne \overrightarrow i + \text{ and } \vec\lim \ne \overrightarrow\lim. + +Accents should be nearer to the base (in Firefox 78, it's vice versa!): + +.. math:: \vec a \vec l \ne \overrightarrow a \overrightarrow l + + \bar a \bar l \ne \overline a \overline l diff --git a/rst/math/fitting_71d4d8.rst b/rst/math/fitting_71d4d8.rst new file mode 100644 index 0000000..9c5f2dc --- /dev/null +++ b/rst/math/fitting_71d4d8.rst @@ -0,0 +1,837 @@ +.. _minimize_chapter: + +.. module:: lmfit.minimizer + +===================================== +Performing Fits and Analyzing Outputs +===================================== + +As shown in the previous chapter, a simple fit can be performed with the +:func:`minimize` function. For more sophisticated modeling, the +:class:`Minimizer` class can be used to gain a bit more control, especially +when using complicated constraints or comparing results from related fits. + +The :func:`minimize` function +============================= + +The :func:`minimize` function is a wrapper around :class:`Minimizer` for +running an optimization problem. It takes an objective function (the +function that calculates the array to be minimized), a :class:`Parameters` +object, and several optional arguments. See :ref:`fit-func-label` for +details on writing the objective function. + +.. autofunction:: minimize + +.. _fit-func-label: + +Writing a Fitting Function +========================== + +An important component of a fit is writing a function to be minimized -- +the *objective function*. Since this function will be called by other +routines, there are fairly stringent requirements for its call signature +and return value. In principle, your function can be any Python callable, +but it must look like this: + +.. function:: func(params, *args, **kws): + + Calculate objective residual to be minimized from parameters. + + :param params: Parameters. + :type params: :class:`~lmfit.parameter.Parameters` + :param args: Positional arguments. Must match ``args`` argument to :func:`minimize`. + :param kws: Keyword arguments. Must match ``kws`` argument to :func:`minimize`. + :return: Residual array (generally ``data-model``) to be minimized in the least-squares sense. + :rtype: :numpydoc:`ndarray`. The length of this array cannot change between calls. + + +A common use for the positional and keyword arguments would be to pass in other +data needed to calculate the residual, including things as the data array, +dependent variable, uncertainties in the data, and other data structures for the +model calculation. + +The objective function should return the value to be minimized. For the +Levenberg-Marquardt algorithm from :meth:`leastsq`, this returned value **must** be an +array, with a length greater than or equal to the number of fitting variables in the +model. For the other methods, the return value can either be a scalar or an array. If an +array is returned, the sum of squares of the array will be sent to the underlying fitting +method, effectively doing a least-squares optimization of the return values. + +Since the function will be passed in a dictionary of :class:`Parameters`, it is advisable +to unpack these to get numerical values at the top of the function. A +simple way to do this is with :meth:`Parameters.valuesdict`, as shown below: + +.. jupyter-execute:: + + from numpy import exp, sign, sin, pi + + + def residual(pars, x, data=None, eps=None): + # unpack parameters: extract .value attribute for each parameter + parvals = pars.valuesdict() + period = parvals['period'] + shift = parvals['shift'] + decay = parvals['decay'] + + if abs(shift) > pi/2: + shift = shift - sign(shift)*pi + + if abs(period) < 1.e-10: + period = sign(period)*1.e-10 + + model = parvals['amp'] * sin(shift + x/period) * exp(-x*x*decay*decay) + + if data is None: + return model + if eps is None: + return model - data + return (model-data) / eps + +In this example, ``x`` is a positional (required) argument, while the +``data`` array is actually optional (so that the function returns the model +calculation if the data is neglected). Also note that the model +calculation will divide ``x`` by the value of the ``period`` Parameter. It +might be wise to ensure this parameter cannot be 0. It would be possible +to use bounds on the :class:`Parameter` to do this: + +.. jupyter-execute:: + :hide-code: + + from lmfit import Parameter, Parameters + + params = Parameters() + +.. jupyter-execute:: + + params['period'] = Parameter(name='period', value=2, min=1.e-10) + +but putting this directly in the function with: + +.. jupyter-execute:: + :hide-code: + + period = 1 + +.. jupyter-execute:: + + if abs(period) < 1.e-10: + period = sign(period)*1.e-10 + +is also a reasonable approach. Similarly, one could place bounds on the +``decay`` parameter to take values only between ``-pi/2`` and ``pi/2``. + +.. _fit-data-label: + +Types of Data to Use for Fitting +=================================== + +Minimization methods assume that data is numerical. For all the fitting +methods supported by lmfit, data and fitting parameters are also assumed to +be continuous variables. As the routines make heavy use of numpy and scipy, +the most natural data to use in fitting is then numpy nd-arrays. In fact, many +of the underlying fitting algorithms - including the default :meth:`leastsq` +method - **require** the values in the residual array used for the +minimization to be a 1-dimensional numpy array with data type (`dtype`) of +"float64": a 64-bit representation of a floating point number (sometimes called +a "double precision float"). + +Python is generally forgiving about data types, and in the scientific Python +community there is a concept of an object being "array like" which essentially +means that the can usually be coerced or interpreted as a numpy array, often +with that object having an ``__array__()`` method specially designed for that +conversion. Important examples of objects that can be considered "array like" +include Lists and Tuples that contain only numbers, pandas Series, and HDF5 +Datasets. Many objects from data-processing libraries like dask, xarray, zarr, +and more are also "array like". + +Lmfit tries to be accommodating in the data that can be used in the fitting +process. When using :class:`Minimizer`, the data you pass in as extra arrays for the +calculation of the residual array will not be altered, and can be used in your +objective function in whatever form you send. Usually, "array like" data will +work, but some care may be needed. In the example above, if ``x`` was not a +numpy array but a list of numbers, this would give an error message like:: + + TypeError: unsupported operand type(s) for /: 'list' and 'float' + +or:: + + TypeError: can't multiply sequence by non-int of type 'float' + +because a list of numbers is only sometimes "array like". + +Sending in a "more array-like" object like a pandas Series will avoid many +(though maybe not all!) such exceptions, but the resulting calculation returned +from the function would then also be a pandas Series. Lmfit :meth:`minimize` will +always coerce the return value from the objective function into a 1-D numpy +array with ``dtype`` of "float64". This will usually "just work", but there +may be exceptions. + +When in doubt, or if running it trouble, converting data to float64 numpy +arrays before being used in a fit is recommended. If using complex data or +functions, a ``dtype`` of "complex128" will also always work, and will be +converted to "float64" with ``ndaarray.view("float64")``. Numpy arrays of other +``dtype`` (say, "int16" or "float32") should be used with caution. In +particular, "float32" data should be avoided: Multiplying a "float32" array and +a Python float will result in a "float32" array for example. As fitting +variables may have small changes made to them, the results may be at or below +"float32" precision, which will cause the fit to give up. For integer data, +results are more sometimes promoted to "float64", but many numpy ufuncs (say, +``numpy.exp()``) will promote only to "float32", so care is still needed. + + +See also :ref:`model_data_coercion_section` for discussion of data passed in for +curve-fitting. + + + +.. _fit-methods-label: + +Choosing Different Fitting Methods +================================== + +By default, the `Levenberg-Marquardt +`_ algorithm is +used for fitting. While often criticized, including the fact it finds a +*local* minimum, this approach has some distinct advantages. These include +being fast, and well-behaved for most curve-fitting needs, and making it +easy to estimate uncertainties for and correlations between pairs of fit +variables, as discussed in :ref:`fit-results-label`. + +Alternative algorithms can also be used by providing the ``method`` +keyword to the :func:`minimize` function or :meth:`Minimizer.minimize` +class as listed in the :ref:`Table of Supported Fitting Methods +`. If you have the ``numdifftools`` package installed, lmfit +will try to estimate the covariance matrix and determine parameter +uncertainties and correlations if ``calc_covar`` is ``True`` (default). + +.. _fit-methods-table: + + Table of Supported Fitting Methods: + + +--------------------------+------------------------------------------------------------------+ + | Fitting Method | ``method`` arg to :func:`minimize` or :meth:`Minimizer.minimize` | + +==========================+==================================================================+ + | Levenberg-Marquardt | ``leastsq`` or ``least_squares`` | + +--------------------------+------------------------------------------------------------------+ + | Nelder-Mead | ``nelder`` | + +--------------------------+------------------------------------------------------------------+ + | L-BFGS-B | ``lbfgsb`` | + +--------------------------+------------------------------------------------------------------+ + | Powell | ``powell`` | + +--------------------------+------------------------------------------------------------------+ + | Conjugate Gradient | ``cg`` | + +--------------------------+------------------------------------------------------------------+ + | Newton-CG | ``newton`` | + +--------------------------+------------------------------------------------------------------+ + | COBYLA | ``cobyla`` | + +--------------------------+------------------------------------------------------------------+ + | COBYQA | ``cobyqa`` | + +--------------------------+------------------------------------------------------------------+ + | BFGS | ``bfgsb`` | + +--------------------------+------------------------------------------------------------------+ + | Truncated Newton | ``tnc`` | + +--------------------------+------------------------------------------------------------------+ + | Newton CG trust-region | ``trust-ncg`` | + +--------------------------+------------------------------------------------------------------+ + | Exact trust-region | ``trust-exact`` | + +--------------------------+------------------------------------------------------------------+ + | Newton GLTR trust-region | ``trust-krylov`` | + +--------------------------+------------------------------------------------------------------+ + | Constrained trust-region | ``trust-constr`` | + +--------------------------+------------------------------------------------------------------+ + | Dogleg | ``dogleg`` | + +--------------------------+------------------------------------------------------------------+ + | Sequential Linear | ``slsqp`` | + | Squares Programming | | + +--------------------------+------------------------------------------------------------------+ + | Differential | ``differential_evolution`` | + | Evolution | | + +--------------------------+------------------------------------------------------------------+ + | Brute force method | ``brute`` | + +--------------------------+------------------------------------------------------------------+ + | Basinhopping | ``basinhopping`` | + +--------------------------+------------------------------------------------------------------+ + | Adaptive Memory | ``ampgo`` | + | Programming for Global | | + | Optimization | | + +--------------------------+------------------------------------------------------------------+ + | Simplicial Homology | ``shgo`` | + | Global Optimization | | + +--------------------------+------------------------------------------------------------------+ + | Dual Annealing | ``dual_annealing`` | + +--------------------------+------------------------------------------------------------------+ + | DIviding RECTangles | ``direct`` | + | (DIRECT) algorithm | | + +--------------------------+------------------------------------------------------------------+ + | Maximum likelihood via | ``emcee`` | + | Monte-Carlo Markov Chain | | + +--------------------------+------------------------------------------------------------------+ + + +.. note:: + + The objective function for the Levenberg-Marquardt method **must** + return an array, with more elements than variables. All other methods + can return either a scalar value or an array. The Monte-Carlo Markov + Chain or ``emcee`` method has two different operating methods when the + objective function returns a scalar value. See the documentation for ``emcee``. + + +.. warning:: + + Much of this documentation assumes that the Levenberg-Marquardt (``leastsq``) + method is used. Many of the fit statistics and estimates for uncertainties in + parameters discussed in :ref:`fit-results-label` are done only unconditionally + for this (and the ``least_squares``) method. Lmfit versions newer than 0.9.11 + provide the capability to use ``numdifftools`` to estimate the covariance matrix + and calculate parameter uncertainties and correlations for other methods as + well. + +.. _fit-results-label: + +:class:`MinimizerResult` -- the optimization result +=================================================== + +An optimization with :func:`minimize` or :meth:`Minimizer.minimize` +will return a :class:`MinimizerResult` object. This is an otherwise +plain container object (that is, with no methods of its own) that +simply holds the results of the minimization. These results will +include several pieces of informational data such as status and error +messages, fit statistics, and the updated parameters themselves. + +Importantly, the parameters passed in to :meth:`Minimizer.minimize` +will be not be changed. To find the best-fit values, uncertainties +and so on for each parameter, one must use the +:attr:`MinimizerResult.params` attribute. For example, to print the +fitted values, bounds and other parameter attributes in a +well-formatted text tables you can execute:: + + result.params.pretty_print() + +with ``results`` being a ``MinimizerResult`` object. Note that the method +:meth:`~lmfit.parameter.Parameters.pretty_print` accepts several arguments +for customizing the output (e.g., column width, numeric format, etcetera). + +.. autoclass:: MinimizerResult + + +Goodness-of-Fit Statistics +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _goodfit-table: + + Table of Fit Results: These values, including the standard Goodness-of-Fit statistics, + are all attributes of the :class:`MinimizerResult` object returned by + :func:`minimize` or :meth:`Minimizer.minimize`. + ++----------------------+----------------------------------------------------------------------------+ +| Attribute Name | Description / Formula | ++======================+============================================================================+ +| nfev | number of function evaluations | ++----------------------+----------------------------------------------------------------------------+ +| nvarys | number of variables in fit :math:`N_{\rm varys}` | ++----------------------+----------------------------------------------------------------------------+ +| ndata | number of data points: :math:`N` | ++----------------------+----------------------------------------------------------------------------+ +| nfree | degrees of freedom in fit: :math:`N - N_{\rm varys}` | ++----------------------+----------------------------------------------------------------------------+ +| aborted | boolean of whether the fit has been aborted. | ++----------------------+----------------------------------------------------------------------------+ +| success | boolean for a minimal test of whether the fit finished successfully | ++----------------------+----------------------------------------------------------------------------+ +| errorbars | boolean of whether error bars and unccertainty were estimated | ++----------------------+----------------------------------------------------------------------------+ +| ier | integer flag describing message from ``leastsq``. | ++----------------------+----------------------------------------------------------------------------+ +| message | simple message from ``leastsq`` | ++----------------------+----------------------------------------------------------------------------+ +| method | name of fitting methods | ++----------------------+----------------------------------------------------------------------------+ +| residual | residual array, returned by the objective function: :math:`\{\rm Resid_i\}`| ++----------------------+----------------------------------------------------------------------------+ +| chisqr | chi-square: :math:`\chi^2 = \sum_i^N [{\rm Resid}_i]^2` | ++----------------------+----------------------------------------------------------------------------+ +| redchi | reduced chi-square: :math:`\chi^2_{\nu}= {\chi^2} / {(N - N_{\rm varys})}` | ++----------------------+----------------------------------------------------------------------------+ +| aic | Akaike Information Criterion statistic (see below) | ++----------------------+----------------------------------------------------------------------------+ +| bic | Bayesian Information Criterion statistic (see below) | ++----------------------+----------------------------------------------------------------------------+ +| params | best-fit parameters after fit, with uncertainties is available | ++----------------------+----------------------------------------------------------------------------+ +| var_names | ordered list of variable parameter names used for init_vals and covar | ++----------------------+----------------------------------------------------------------------------+ +| covar | covariance matrix (with rows/columns using var_names) | ++----------------------+----------------------------------------------------------------------------+ +| init_vals | list of initial values for variable parameters | ++----------------------+----------------------------------------------------------------------------+ +| init_values | dictionary of initial values for variable Parameters. | ++----------------------+----------------------------------------------------------------------------+ +| uvars | dictionary of uncertainties uvalues for all Parameters. | ++----------------------+----------------------------------------------------------------------------+ +| call_kws | dict of keyword arguments sent to underlying solver | ++----------------------+----------------------------------------------------------------------------+ + +Note that the calculation of chi-square and reduced chi-square assume +that the returned residual function is scaled properly to the +uncertainties in the data. For these statistics to be meaningful, the +person writing the function to be minimized **must** scale them properly. + +After a fit using the :meth:`leastsq` or :meth:`least_squares` method has +completed successfully, standard errors for the fitted variables and +correlations between pairs of fitted variables are automatically calculated from +the covariance matrix. For other methods, the ``calc_covar`` parameter (default +is ``True``) in the :class:`Minimizer` class determines whether or not to use the +``numdifftools`` package to estimate the covariance matrix. The standard error +(estimated :math:`1\sigma` error-bar) goes into the :attr:`stderr` attribute of +the Parameter. The correlations with all other variables will be put into the +:attr:`correl` attribute of the Parameter -- a dictionary with keys for all +other Parameters and values of the corresponding correlation. + +In some cases, it may not be possible to estimate the errors and +correlations. For example, if a variable actually has no practical effect +on the fit, it will likely cause the covariance matrix to be singular, +making standard errors impossible to estimate. Placing bounds on varied +Parameters makes it more likely that errors cannot be estimated, as being +near the maximum or minimum value makes the covariance matrix singular. In +these cases, the :attr:`errorbars` attribute of the fit result +(:class:`Minimizer` object) will be ``False``. + + +.. _information_criteria_label: + +Akaike and Bayesian Information Criteria +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :class:`MinimizerResult` includes the traditional chi-square and +reduced chi-square statistics: + +.. math:: + :nowrap: + + \begin{eqnarray*} + \chi^2 &=& \sum_i^N r_i^2 \\ + \chi^2_\nu &=& \chi^2 / (N-N_{\rm varys}) + \end{eqnarray*} + +where :math:`r` is the residual array returned by the objective function +(likely to be ``(data-model)/uncertainty`` for data modeling usages), +:math:`N` is the number of data points (``ndata``), and :math:`N_{\rm +varys}` is number of variable parameters. + +Also included are the `Akaike Information Criterion +`_, and +`Bayesian Information Criterion +`_ statistics, +held in the ``aic`` and ``bic`` attributes, respectively. These give slightly +different measures of the relative quality for a fit, trying to balance +quality of fit with the number of variable parameters used in the fit. +These are calculated as: + +.. math:: + :nowrap: + + \begin{eqnarray*} + {\rm aic} &=& N \ln(\chi^2/N) + 2 N_{\rm varys} \\ + {\rm bic} &=& N \ln(\chi^2/N) + \ln(N) N_{\rm varys} \\ + \end{eqnarray*} + + +When comparing fits with different numbers of varying parameters, one +typically selects the model with lowest reduced chi-square, Akaike +information criterion, and/or Bayesian information criterion. Generally, +the Bayesian information criterion is considered the most conservative of +these statistics. + + +Uncertainties in Variable Parameters, and their Correlations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _uncertainties: https://github.com/lebigot/uncertainties/ + +As mentioned above, when a fit is complete the uncertainties for fitted +Parameters as well as the correlations between pairs of Parameters are usually +calculated. This happens automatically either when using the default +:meth:`leastsq` method, the :meth:`least_squares` method, or for most other +fitting methods if the highly-recommended ``numdifftools`` package is +available. The estimated standard error (the :math:`1\sigma` uncertainty) for +each variable Parameter will be contained in the :attr:`stderr`, while the +:attr:`correl` attribute for each Parameter will contain a dictionary of the +correlation with each other variable Parameter. These updated parameters with +uncertainty and correlation information will be placed in +``MinimizerResult.params``, so that you may access the best fit value, standard +error and correlation. For a successful fit for which uncertainties and +correlations can be calculated, the ``MinimizerResult`` will also have a +``uvars`` attribute that is a dictionary with keynames for each Parameter +(includnig constraints) and values of ``Ufloats`` from the `uncertainties`_ +package using the best fit values, the standard error and the correlation +between Parameters. + +These estimates of the uncertainties are done by inverting the Hessian +matrix which represents the second derivative of fit quality for each +variable parameter. There are situations for which the uncertainties cannot +be estimated, which generally indicates that this matrix cannot be inverted +because one of the fit is not actually sensitive to one of the variables. +This can happen if a Parameter is stuck at an upper or lower bound, if the +variable is simply not used by the fit, or if the value for the variable is +such that it has no real influence on the fit. + +In principle, the scale of the uncertainties in the Parameters is closely +tied to the goodness-of-fit statistics chi-square and reduced chi-square +(``chisqr`` and ``redchi``). The standard errors or :math:`1 \sigma` +uncertainties are those that increase chi-square by 1. Since a "good fit" +should have ``redchi`` of around 1, this requires that the data +uncertainties (and to some extent the sampling of the N data points) is +correct. Unfortunately, it is often not the case that one has high-quality +estimates of the data uncertainties (getting the data is hard enough!). +Because of this common situation, the uncertainties reported and held in +:attr:`stderr` are not those that increase chi-square by 1, but those that +increase chi-square by reduced chi-square. This is equivalent to rescaling +the uncertainty in the data such that reduced chi-square would be 1. To be +clear, this rescaling is done by default because if reduced chi-square is +far from 1, this rescaling often makes the reported uncertainties sensible, +and if reduced chi-square is near 1 it does little harm. If you have good +scaling of the data uncertainty and believe the scale of the residual +array is correct, this automatic rescaling can be turned off using +``scale_covar=False``. + +Note that the simple (and fast!) approach to estimating uncertainties and +correlations by inverting the second derivative matrix assumes that the +components of the residual array (if, indeed, an array is used) are +distributed around 0 with a normal (Gaussian distribution), and that a map +of probability distributions for pairs would be elliptical -- the size of +the of ellipse gives the uncertainty itself and the eccentricity of the +ellipse gives the correlation. This simple approach to assessing +uncertainties ignores outliers, highly asymmetric uncertainties, or complex +correlations between Parameters. In fact, it is not too hard to come up +with problems where such effects are important. Our experience is that the +automated results are usually the right scale and quite reasonable as +initial estimates, but a more thorough exploration of the Parameter space +using the tools described in :ref:`label-emcee` and +:ref:`label-confidence-advanced` can give a more complete understanding of +the distributions and relations between Parameters. + + +.. _fit-reports-label: + +Getting and Printing Fit Reports +================================ + +.. currentmodule:: lmfit.printfuncs + +.. autofunction:: fit_report + +An example using this to write out a fit report would be: + +.. jupyter-execute:: ../examples/doc_fitting_withreport.py + :hide-output: + +which would give as output: + +.. jupyter-execute:: + :hide-code: + + print(fit_report(out)) + +To be clear, you can get at all of these values from the fit result ``out`` +and ``out.params``. For example, a crude printout of the best fit variables +and standard errors could be done as + +.. jupyter-execute:: + + print('-------------------------------') + print('Parameter Value Stderr') + for name, param in out.params.items(): + print(f'{name:7s} {param.value:11.5f} {param.stderr:11.5f}') + + +.. _fit-itercb-label: + +Using a Iteration Callback Function +=================================== + +.. currentmodule:: lmfit.minimizer + +An iteration callback function is a function to be called at each +iteration, just after the objective function is called. The iteration +callback allows user-supplied code to be run at each iteration, and can +be used to abort a fit. + +.. function:: iter_cb(params, iter, resid, *args, **kws): + + User-supplied function to be run at each iteration. + + :param params: Parameters. + :type params: :class:`~lmfit.parameter.Parameters` + :param iter: Iteration number. + :type iter: int + :param resid: Residual array. + :type resid: numpy.ndarray + :param args: Positional arguments. Must match ``args`` argument to :func:`minimize` + :param kws: Keyword arguments. Must match ``kws`` argument to :func:`minimize` + :return: Iteration abort flag. + :rtype: None for normal behavior, any value like ``True`` to abort the fit. + + +Normally, the iteration callback would have no return value or return +``None``. To abort a fit, have this function return a value that is +``True`` (including any non-zero integer). The fit will also abort if any +exception is raised in the iteration callback. When a fit is aborted this +way, the parameters will have the values from the last iteration. The fit +statistics are not likely to be meaningful, and uncertainties will not be computed. + + +.. _fit-minimizer-label: + +Using the :class:`Minimizer` class +================================== + +.. currentmodule:: lmfit.minimizer + +For full control of the fitting process, you will want to create a +:class:`Minimizer` object. + +.. autoclass :: Minimizer + +The Minimizer object has a few public methods: + +.. automethod:: Minimizer.minimize + +.. automethod:: Minimizer.leastsq + +.. automethod:: Minimizer.least_squares + +.. automethod:: Minimizer.scalar_minimize + +.. automethod:: Minimizer.prepare_fit + +.. automethod:: Minimizer.brute + +For more information, check the examples in ``examples/lmfit_brute_example.ipynb``. + +.. automethod:: Minimizer.basinhopping + +.. automethod:: Minimizer.ampgo + +.. automethod:: Minimizer.shgo + +.. automethod:: Minimizer.dual_annealing + +.. automethod:: Minimizer.direct + +.. automethod:: Minimizer.emcee + + +.. _label-emcee: + +:meth:`Minimizer.emcee` - calculating the posterior probability distribution of parameters +========================================================================================== + +:meth:`Minimizer.emcee` can be used to obtain the posterior probability +distribution of parameters, given a set of experimental data. Note that this +method does *not* actually perform a fit at all. Instead, it explores +parameter space to determine the probability distributions for the parameters, +but without an explicit goal of attempting to refine the solution. It should +not be used for fitting, but it is a useful method to to more thoroughly +explore the parameter space around the solution after a fit has been done and +thereby get an improved understanding of the probability distribution for the +parameters. It may be able to refine your estimate of the most likely values +for a set of parameters, but it will not iteratively find a good solution to +the minimization problem. To use this method effectively, you should first +use another minimization method and then use this method to explore the +parameter space around those best-fit values. + +To illustrate this, we'll use an example problem of fitting data to function +of a double exponential decay, including a modest amount of Gaussian noise to +the data. Note that this example is the same problem used in +:ref:`label-confidence-advanced` for evaluating confidence intervals in the +parameters, which is a similar goal to the one here. + +.. jupyter-execute:: + :hide-code: + + import warnings + warnings.filterwarnings(action="ignore") + + import matplotlib as mpl + import matplotlib.pyplot as plt + mpl.rcParams['figure.dpi'] = 150 + %matplotlib inline + %config InlineBackend.figure_format = 'svg' + + +.. jupyter-execute:: + + import matplotlib.pyplot as plt + import numpy as np + + import lmfit + + x = np.linspace(1, 10, 250) + np.random.seed(0) + y = 3.0 * np.exp(-x / 2) - 5.0 * np.exp(-(x - 0.1) / 10.) + 0.1 * np.random.randn(x.size) + +Create a Parameter set for the initial guesses: + +.. jupyter-execute:: + + p = lmfit.Parameters() + p.add_many(('a1', 4.), ('a2', 4.), ('t1', 3.), ('t2', 3., True)) + + def residual(p): + v = p.valuesdict() + return v['a1'] * np.exp(-x / v['t1']) + v['a2'] * np.exp(-(x - 0.1) / v['t2']) - y + +Solving with :func:`minimize` gives the Maximum Likelihood solution. Note +that we use the robust Nelder-Mead method here. The default Levenberg-Marquardt +method seems to have difficulty with exponential decays, though it can refine +the solution if starting near the solution: + +.. jupyter-execute:: + + mi = lmfit.minimize(residual, p, method='nelder', nan_policy='omit') + lmfit.printfuncs.report_fit(mi.params, min_correl=0.5) + +and plotting the fit using the Maximum Likelihood solution gives the graph below: + +.. jupyter-execute:: + + plt.plot(x, y, 'o') + plt.plot(x, residual(mi.params) + y, label='best fit') + plt.legend() + plt.show() + +Note that the fit here (for which the ``numdifftools`` package is installed) +does estimate and report uncertainties in the parameters and correlations for +the parameters, and reports the correlation of parameters ``a2`` and ``t2`` to +be very high. As we'll see, these estimates are pretty good, but when faced +with such high correlation, it can be helpful to get the full probability +distribution for the parameters. MCMC methods are very good for this. + +Furthermore, we wish to deal with the data uncertainty. This is called +marginalisation of a nuisance parameter. ``emcee`` requires a function that +returns the log-posterior probability. The log-posterior probability is a sum +of the log-prior probability and log-likelihood functions. The log-prior +probability is assumed to be zero if all the parameters are within their +bounds and ``-np.inf`` if any of the parameters are outside their bounds. + +If the objective function returns an array of unweighted residuals (i.e., +``data-model``) as is the case here, you can use ``is_weighted=False`` as an +argument for ``emcee``. In that case, ``emcee`` will automatically add/use the +``__lnsigma`` parameter to estimate the true uncertainty in the data. To +place boundaries on this parameter one can do: + +.. jupyter-execute:: + + mi.params.add('__lnsigma', value=np.log(0.1), min=np.log(0.001), max=np.log(2)) + +Now we have to set up the minimizer and do the sampling (again, just to be +clear, this is *not* doing a fit): + +.. jupyter-execute:: + :hide-output: + + res = lmfit.minimize(residual, method='emcee', nan_policy='omit', burn=300, steps=1000, thin=20, + params=mi.params, is_weighted=False, progress=False) + +As mentioned in the Notes for :meth:`Minimizer.emcee`, the ``is_weighted`` +argument will be ignored if your objective function returns a float instead of +an array. For the documentation we set ``progress=False``; the default is to +print a progress bar to the Terminal if the ``tqdm`` package is installed. + +The success of the method (i.e., whether or not the sampling went well) can be +assessed by checking the integrated autocorrelation time and/or the acceptance +fraction of the walkers. For this specific example the autocorrelation time +could not be estimated because the "chain is too short". Instead, we plot the +acceptance fraction per walker and its mean value suggests that the sampling +worked as intended (as a rule of thumb the value should be between 0.2 and +0.5). + +.. jupyter-execute:: + + plt.plot(res.acceptance_fraction, 'o') + plt.xlabel('walker') + plt.ylabel('acceptance fraction') + plt.show() + +With the results from ``emcee``, we can visualize the posterior distributions +for the parameters using the ``corner`` package: + +.. jupyter-execute:: + + import corner + + emcee_plot = corner.corner(res.flatchain, labels=res.var_names, + truths=list(res.params.valuesdict().values())) + +The values reported in the :class:`MinimizerResult` are the medians of the +probability distributions and a 1 :math:`\sigma` quantile, estimated as half +the difference between the 15.8 and 84.2 percentiles. Printing these values: + + +.. jupyter-execute:: + + print('median of posterior probability distribution') + print('--------------------------------------------') + lmfit.report_fit(res.params) + +You can see that this recovered the right uncertainty level on the data. Note +that these values agree pretty well with the results, uncertainties and +correlations found by the fit and using ``numdifftools`` to estimate the +covariance matrix. That is, even though the parameters ``a2``, ``t1``, and +``t2`` are all highly correlated and do not display perfectly Gaussian +probability distributions, the probability distributions found by explicitly +sampling the parameter space are not so far from elliptical as to make the +simple (and much faster) estimates from inverting the covariance matrix +completely invalid. + +As mentioned above, the result from ``emcee`` reports the median values, which +are not necessarily the same as the Maximum Likelihood Estimate. To obtain +the values for the Maximum Likelihood Estimation (MLE) we find the location in +the chain with the highest probability: + +.. jupyter-execute:: + + highest_prob = np.argmax(res.lnprob) + hp_loc = np.unravel_index(highest_prob, res.lnprob.shape) + mle_soln = res.chain[hp_loc] + for i, par in enumerate(p): + p[par].value = mle_soln[i] + + + print('\nMaximum Likelihood Estimation from emcee ') + print('-------------------------------------------------') + print('Parameter MLE Value Median Value Uncertainty') + fmt = ' {:5s} {:11.5f} {:11.5f} {:11.5f}'.format + for name, param in p.items(): + print(fmt(name, param.value, res.params[name].value, + res.params[name].stderr)) + + +Here the difference between MLE and median value are seen to be below 0.5%, +and well within the estimated 1-:math:`\sigma` uncertainty. + +Finally, we can use the samples from ``emcee`` to work out the 1- and +2-:math:`\sigma` error estimates. + +.. jupyter-execute:: + + print('\nError estimates from emcee:') + print('------------------------------------------------------') + print('Parameter -2sigma -1sigma median +1sigma +2sigma') + + for name in p.keys(): + quantiles = np.percentile(res.flatchain[name], + [2.275, 15.865, 50, 84.135, 97.275]) + median = quantiles[2] + err_m2 = quantiles[0] - median + err_m1 = quantiles[1] - median + err_p1 = quantiles[3] - median + err_p2 = quantiles[4] - median + fmt = ' {:5s} {:8.4f} {:8.4f} {:8.4f} {:8.4f} {:8.4f}'.format + print(fmt(name, err_m2, err_m1, median, err_p1, err_p2)) + +And we see that the initial estimates for the 1-:math:`\sigma` standard error +using ``numdifftools`` was not too bad. We'll return to this example +problem in :ref:`label-confidence-advanced` and use a different method to +calculate the 1- and 2-:math:`\sigma` error bars. diff --git a/rst/math/g_functions_7277dd.rst b/rst/math/g_functions_7277dd.rst new file mode 100644 index 0000000..398b4c6 --- /dev/null +++ b/rst/math/g_functions_7277dd.rst @@ -0,0 +1,518 @@ +.. _g-functions: + +============================================ +Computing Integrals using Meijer G-Functions +============================================ + +This text aims do describe in some detail the steps (and subtleties) involved +in using Meijer G-functions for computing definite and indefinite integrals. +We shall ignore proofs completely. + +Overview +======== + +The algorithm to compute `\int f(x) \mathrm{d}x` or +`\int_0^\infty f(x) \mathrm{d}x` generally consists of three steps: + +1. Rewrite the integrand using Meijer G-functions (one or sometimes two). +2. Apply an integration theorem, to get the answer (usually expressed as another + G-function). +3. Expand the result in named special functions. + +Step (3) is implemented in the function hyperexpand (q.v.). Steps (1) and (2) +are described below. Moreover, G-functions are usually branched. Thus our treatment +of branched functions is described first. + +Some other integrals (e.g. `\int_{-\infty}^\infty`) can also be computed by first +recasting them into one of the above forms. There is a lot of choice involved +here, and the algorithm is heuristic at best. + +Polar Numbers and Branched Functions +==================================== + +Both Meijer G-Functions and Hypergeometric functions are typically branched +(possible branchpoints being `0`, `\pm 1`, `\infty`). This is not very important +when e.g. expanding a single hypergeometric function into named special functions, +since sorting out the branches can be left to the human user. However this +algorithm manipulates and transforms G-functions, and to do this correctly it needs +at least some crude understanding of the branchings involved. + +To begin, we consider the set +`\mathcal{S} = \{(r, \theta) : r > 0, \theta \in \mathbb{R}\}`. We have a map +`p: \mathcal{S}: \rightarrow \mathbb{C}-\{0\}, (r, \theta) \mapsto r e^{i \theta}`. +Decreeing this to be a local biholomorphism gives `\mathcal{S}` both a topology +and a complex structure. This Riemann Surface is usually referred to as the +Riemann Surface of the logarithm, for the following reason: +We can define maps +`\operatorname{Exp}: \mathbb{C} \rightarrow \mathcal{S}, (x + i y) \mapsto (\exp(x), y)` and +`\operatorname{Log}: \mathcal{S} \rightarrow \mathbb{C}, (e^x, y) \mapsto x + iy`. +These can both be shown to be holomorphic, and are indeed mutual inverses. + +We also sometimes formally attach a point "zero" (`0`) to `\mathcal{S}` and denote the +resulting object `\mathcal{S}_0`. Notably there is no complex structure +defined near `0`. A fundamental system of neighbourhoods is given by +`\{\operatorname{Exp}(z) : \Re(z) < k\}`, which at least defines a topology. Elements of +`\mathcal{S}_0` shall be called polar numbers. +We further define functions +`\operatorname{Arg}: \mathcal{S} \rightarrow \mathbb{R}, (r, \theta) \mapsto \theta` and +`|.|: \mathcal{S}_0 \rightarrow \mathbb{R}_{>0}, (r, \theta) \mapsto r`. +These have evident meaning and are both continuous everywhere. + +Using these maps many operations can be extended from `\mathbb{C}` to +`\mathcal{S}`. We define `\operatorname{Exp}(a) \operatorname{Exp}(b) = \operatorname{Exp}(a + b)` for `a, b \in \mathbb{C}`, +also for `a \in \mathcal{S}` and `b \in \mathbb{C}` we define +`a^b = \operatorname{Exp}(b \operatorname{Log}(a))`. +It can be checked easily that using these definitions, many algebraic properties +holding for positive reals (e.g. `(ab)^c = a^c b^c`) which hold in `\mathbb{C}` +only for some numbers (because of branch cuts) hold indeed for all polar numbers. + +As one peculiarity it should be mentioned that addition of polar numbers is not +usually defined. However, formal sums of polar numbers can be used to express +branching behaviour. For example, consider the functions `F(z) = \sqrt{1 + z}` +and `G(a, b) = \sqrt{a + b}`, where `a, b, z` are polar numbers. +The general rule is that functions of a single polar variable are defined in +such a way that they are continuous on circles, and agree with the usual +definition for positive reals. Thus if `S(z)` denotes the standard branch of +the square root function on `\mathbb{C}`, we are forced to define + +.. math:: F(z) = \begin{cases} + S(p(z)) &: |z| < 1 \\ + S(p(z)) &: -\pi < \operatorname{Arg}(z) + 4\pi n \le \pi \text{ for some } n \in \mathbb{Z} \\ + -S(p(z)) &: \text{else} + \end{cases}. + +(We are omitting `|z| = 1` here, this does not matter for integration.) +Finally we define `G(a, b) = \sqrt{a}F(b/a)`. + +Representing Branched Functions on the Argand Plane +=================================================== + +Suppose `f: \mathcal{S} \to \mathbb{C}` is a holomorphic function. We wish to +define a function `F` on (part of) the complex numbers `\mathbb{C}` that +represents `f` as closely as possible. This process is knows as "introducing +branch cuts". In our situation, there is actually a canonical way of doing this +(which is adhered to in all of SymPy), as follows: Introduce the "cut complex +plane" +`C = \mathbb{C} \setminus \mathbb{R}_{\le 0}`. Define a function +`l: C \to \mathcal{S}` via `re^{i\theta} \mapsto r \operatorname{Exp}(i\theta)`. Here `r > 0` +and `-\pi < \theta \le \pi`. Then `l` is holomorphic, and we define +`G = f \circ l`. This called "lifting to the principal branch" throughout the +SymPy documentation. + +Table Lookups and Inverse Mellin Transforms +=========================================== + +Suppose we are given an integrand `f(x)` and are trying to rewrite it as a +single G-function. To do this, we first split `f(x)` into the form `x^s g(x)` +(where `g(x)` is supposed to be simpler than `f(x)`). This is because multiplicative +powers can be absorbed into the G-function later. This splitting is done by +``_split_mul(f, x)``. Then we assemble a tuple of functions that occur in +`f` (e.g. if `f(x) = e^x \cos{x}`, we would assemble the tuple `(\cos, \exp)`). +This is done by the function ``_mytype(f, x)``. Next we index a lookup table +(created using ``_create_lookup_table()``) with this tuple. This (hopefully) +yields a list of Meijer G-function formulae involving these functions, we then +pattern-match all of them. If one fits, we were successful, otherwise not and we +have to try something else. + +Suppose now we want to rewrite as a product of two G-functions. To do this, +we (try to) find all inequivalent ways of splitting `f(x)` into a product +`f_1(x) f_2(x)`. +We could try these splittings in any order, but it is often a good idea to +minimize (a) the number of powers occurring in `f_i(x)` and (b) the number of +different functions occurring in `f_i(x)`. Thus given e.g. +`f(x) = \sin{x}\, e^{x} \sin{2x}` we should try `f_1(x) = \sin{x}\, \sin{2x}`, +`f_2(x) = e^{x}` first. +All of this is done by the function ``_mul_as_two_parts(f)``. + +Finally, we can try a recursive Mellin transform technique. Since the Meijer +G-function is defined essentially as a certain inverse mellin transform, +if we want to write a function `f(x)` as a G-function, we can compute its mellin +transform `F(s)`. If `F(s)` is in the right form, the G-function expression +can be read off. This technique generalises many standard rewritings, e.g. +`e^{ax} e^{bx} = e^{(a + b) x}`. + +One twist is that some functions don't have mellin transforms, even though they +can be written as G-functions. This is true for example for `f(x) = e^x \sin{x}` +(the function grows too rapidly to have a mellin transform). However if the function +is recognised to be analytic, then we can try to compute the mellin-transform of +`f(ax)` for a parameter `a`, and deduce the G-function expression by analytic +continuation. (Checking for analyticity is easy. Since we can only deal with a +certain subset of functions anyway, we only have to filter out those which are +not analyitc.) + +The function ``_rewrite_single`` does the table lookup and recursive mellin +transform. The functions ``_rewrite1`` and ``_rewrite2`` respectively use +above-mentioned helpers and ``_rewrite_single`` to rewrite their argument as +respectively one or two G-functions. + +Applying the Integral Theorems +============================== + +If the integrand has been recast into G-functions, evaluating the integral is +relatively easy. We first do some substitutions to reduce e.g. the exponent +of the argument of the G-function to unity (see ``_rewrite_saxena_1`` and +``_rewrite_saxena``, respectively, for one or two G-functions). Next we go through +a list of conditions under which the integral theorem applies. It can fail for +basically two reasons: either the integral does not exist, or the manipulations +in deriving the theorem may not be allowed (for more details, see this [BlogPost]_). + +Sometimes this can be remedied by reducing the argument of the G-functions +involved. For example it is clear that the G-function representing `e^z` +is satisfies `G(\operatorname{Exp}(2 \pi i)z) = G(z)` for all `z \in \mathcal{S}`. The function +``meijerg.get_period()`` can be used to discover this, and the function +``principal_branch(z, period)`` in ``functions/elementary/complexes.py`` can +be used to exploit the information. This is done transparently by the +integration code. + +.. [BlogPost] https://nessgrh.wordpress.com/2011/07/07/tricky-branch-cuts/ + +The G-Function Integration Theorems +*********************************** + +This section intends to display in detail the definite integration theorems +used in the code. The following two formulae go back to Meijer (In fact he +proved more general formulae; indeed in the literature formulae are usually +staded in more general form. However it is very easy to deduce the general +formulae from the ones we give here. It seemed best to keep the theorems as +simple as possible, since they are very complicated anyway.): + +1. .. math:: \int_0^\infty + G_{p, q}^{m, n} \left.\left(\begin{matrix} a_1, \cdots, a_p \\ + b_1, \cdots, b_q \end{matrix} + \right| \eta x \right) \mathrm{d}x = + \frac{\prod_{j=1}^m \Gamma(b_j + 1) \prod_{j=1}^n \Gamma(-a_j)}{\eta + \prod_{j=m+1}^q \Gamma(-b_j) \prod_{j=n+1}^p \Gamma(a_j + 1)} + +2. .. math:: \int_0^\infty + G_{u, v}^{s, t} \left.\left(\begin{matrix} c_1, \cdots, c_u \\ + d_1, \cdots, d_v \end{matrix} + \right| \sigma x \right) + G_{p, q}^{m, n} \left.\left(\begin{matrix} a_1, \cdots, a_p \\ + b_1, \cdots, b_q \end{matrix} + \right| \omega x \right) + \mathrm{d}x = + G_{v+p, u+q}^{m+t, n+s} \left.\left( + \begin{matrix} a_1, \cdots, a_n, -d_1, \cdots, -d_v, a_{n+1}, \cdots, a_p \\ + b_1, \cdots, b_m, -c_1, \cdots, -c_u, b_{m+1}, \cdots, b_q + \end{matrix} + \right| \frac{\omega}{\sigma} \right) + +The more interesting question is under what conditions these formulae are +valid. Below we detail the conditions implemented in SymPy. They are an +amalgamation of conditions found in [Prudnikov1990]_ and [Luke1969]_; please +let us know if you find any errors. + +Conditions of Convergence for Integral (1) +========================================== +.. TODO: Formatting could be improved. + +We can without loss of generality assume `p \le q`, since the G-functions +of indices `m, n, p, q` and of indices `n, m, q, p` can be related easily +(see e.g. [Luke1969]_, section 5.3). We introduce the following notation: + +.. math:: \xi = m + n - p \\ + \delta = m + n - \frac{p + q}{2} + +.. math:: C_3: -\Re(b_j) < 1 \text{ for } j=1, \ldots, m \\ + 0 < -\Re(a_j) \text{ for } j=1, \ldots, n + +.. math:: C_3^*: -\Re(b_j) < 1 \text{ for } j=1, \ldots, q \\ + 0 < -\Re(a_j) \text{ for } j=1, \ldots, p + +.. math:: C_4: -\Re(\delta) + \frac{q + 1 - p}{2} > q - p + +The convergence conditions will be detailed in several "cases", numbered one +to five. For later use it will be helpful to separate conditions "at infinity" +from conditions "at zero". By conditions "at infinity" we mean conditions that +only depend on the behaviour of the integrand for large, positive values +of `x`, whereas by conditions "at zero" we mean conditions that only depend on +the behaviour of the integrand on `(0, \epsilon)` for any `\epsilon > 0`. +Since all our conditions are specified in terms of parameters of the +G-functions, this distinction is not immediately visible. They are, however, of +very distinct character mathematically; the conditions at infinity being in +particular much harder to control. + +In order for the integral theorem to be valid, conditions +`n` "at zero" and "at infinity" both have to be fulfilled, for some `n`. + +These are the conditions "at infinity": + +1. .. math:: \delta > 0 \wedge |\arg(\eta)| < \delta \pi \wedge (A \vee B \vee C), + + where + + .. math:: + A = 1 \le n \wedge p < q \wedge 1 \le m + + .. math:: + B = 1 \le p \wedge 1 \le m \wedge q = p+1 \wedge + \neg (n = 0 \wedge m = p + 1 ) + + .. math:: + C = 1 \le n \wedge q = p \wedge |\arg(\eta)| \ne (\delta - 2k)\pi + \text{ for } k = 0, 1, \ldots + \left\lceil \frac{\delta}{2} \right\rceil. +2. .. math:: n = 0 \wedge p + 1 \le m \wedge |\arg(\eta)| < \delta \pi +3. .. math:: (p < q \wedge 1 \le m \wedge \delta > 0 \wedge |\arg(\eta)| = \delta \pi) + \vee (p \le q - 2 \wedge \delta = 0 \wedge \arg(\eta) = 0) +4. .. math:: p = q \wedge \delta = 0 \wedge \arg(\eta) = 0 \wedge \eta \ne 0 + \wedge \Re\left(\sum_{j=1}^p b_j - a_j \right) < 0 +5. .. math:: \delta > 0 \wedge |\arg(\eta)| < \delta \pi + +And these are the conditions "at zero": + +1. .. math:: \eta \ne 0 \wedge C_3 +2. .. math:: C_3 +3. .. math:: C_3 \wedge C_4 +4. .. math:: C_3 +5. .. math:: C_3 + +Conditions of Convergence for Integral (2) +========================================== + +We introduce the following notation: + +.. many of the latex expressions below were generated semi-automatically + +.. math:: b^* = s + t - \frac{u + v}{2} +.. math:: c^* = m + n - \frac{p + q}{2} +.. math:: \rho = \sum_{j=1}^v d_j - \sum_{j=1}^u c_j + \frac{u - v}{2} + 1 +.. math:: \mu = \sum_{j=1}^q b_j - \sum_{j=1}^p a_j + \frac{p - q}{2} + 1 +.. math:: \phi = q - p - \frac{u - v}{2} + 1 +.. math:: \eta = 1 - (v - u) - \mu - \rho +.. math:: \psi = \frac{\pi(q - m - n) + |\arg(\omega)|}{q - p} +.. math:: \theta = \frac{\pi(v - s - t) + |\arg(\sigma)|)}{v - u} +.. math:: \lambda_c = (q - p)|\omega|^{1/(q - p)} \cos{\psi} + + (v - u)|\sigma|^{1/(v - u)} \cos{\theta} +.. math:: \lambda_{s0}(c_1, c_2) = c_1 (q - p)|\omega|^{1/(q - p)} \sin{\psi} + + c_2 (v - u)|\sigma|^{1/(v - u)} \sin{\theta} +.. math:: \lambda_s = + \begin{cases} \lambda_{s0}\left(-1,-1\right) \lambda_{s0}\left(1,1\right) & \text{for}\: \arg(\omega) = 0 \wedge \arg(\sigma) = 0 \\\lambda_{s0}\left(\operatorname{sign}\left(\operatorname{\arg}\left(\omega\right)\right),-1\right) \lambda_{s0}\left(\operatorname{sign}\left(\operatorname{\arg}\left(\omega\right)\right),1\right) & \text{for}\: \arg(\omega) \ne 0 \wedge \arg(\sigma) = 0 \\\lambda_{s0}\left(-1,\operatorname{sign}\left(\operatorname{\arg}\left(\sigma\right)\right)\right) \lambda_{s0}\left(1,\operatorname{sign}\left(\operatorname{\arg}\left(\sigma\right)\right)\right) & \text{for}\: \arg(\omega) = 0 \wedge \arg(\sigma) \ne 0) \\\lambda_{s0}\left(\operatorname{sign}\left(\operatorname{\arg}\left(\omega\right)\right),\operatorname{sign}\left(\operatorname{\arg}\left(\sigma\right)\right)\right) & \text{otherwise} \end{cases} +.. math:: z_0 = \frac{\omega}{\sigma} e^{-i\pi (b^* + c^*)} +.. math:: z_1 = \frac{\sigma}{\omega} e^{-i\pi (b^* + c^*)} + +The following conditions will be helpful: + +.. math:: C_1: (a_i - b_j \notin \mathbb{Z}_{>0} \text{ for } i = 1, \ldots, n, j = 1, \ldots, m) \\ + \wedge + (c_i - d_j \notin \mathbb{Z}_{>0} \text{ for } i = 1, \ldots, t, j = 1, \ldots, s) +.. math:: C_2: + \Re(1 + b_i + d_j) > 0 \text{ for } i = 1, \ldots, m, j = 1, \ldots, s +.. math:: C_3: + \Re(a_i + c_j) < 1 \text{ for } i = 1, \ldots, n, j = 1, \ldots, t +.. math:: C_4: + (p - q)\Re(c_i) - \Re(\mu) > -\frac{3}{2} \text{ for } i=1, \ldots, t +.. math:: C_5: + (p - q)\Re(1 + d_i) - \Re(\mu) > -\frac{3}{2} \text{ for } i=1, \ldots, s +.. math:: C_6: + (u - v)\Re(a_i) - \Re(\rho) > -\frac{3}{2} \text{ for } i=1, \ldots, n +.. math:: C_7: + (u - v)\Re(1 + b_i) - \Re(\rho) > -\frac{3}{2} \text{ for } i=1, \ldots, m +.. math:: C_8: + 0 < \lvert{\phi}\rvert + 2 \Re\left(\left(\mu -1\right) \left(- u + v\right) + \left(- p + q\right) \left(\rho -1\right) + \left(- p + q\right) \left(- u + v\right)\right) +.. math:: C_9: + 0 < \lvert{\phi}\rvert - 2 \Re\left(\left(\mu -1\right) \left(- u + v\right) + \left(- p + q\right) \left(\rho -1\right) + \left(- p + q\right) \left(- u + v\right)\right) +.. math:: C_{10}: + \lvert{\operatorname{arg}\left(\sigma\right)}\rvert < \pi b^{*} +.. math:: C_{11}: + \lvert{\operatorname{arg}\left(\sigma\right)}\rvert = \pi b^{*} +.. math:: C_{12}: + |\arg(\omega)| < c^*\pi +.. math:: C_{13}: + |\arg(\omega)| = c^*\pi +.. math:: C_{14}^1: + \left(z_0 \ne 1 \wedge |\arg(1 - z_0)| < \pi \right) \vee + \left(z_0 = 1 \wedge \Re(\mu + \rho - u + v) < 1 \right) +.. math:: C_{14}^2: + \left(z_1 \ne 1 \wedge |\arg(1 - z_1)| < \pi \right) \vee + \left(z_1 = 1 \wedge \Re(\mu + \rho - p + q) < 1 \right) +.. math:: C_{14}: + \phi = 0 \wedge b^* + c^* \le 1 \wedge (C_{14}^1 \vee C_{14}^2) +.. math:: C_{15}: + \lambda_c > 0 \vee (\lambda_c = 0 \wedge \lambda_s \ne 0 \wedge \Re(\eta) > -1) + \vee (\lambda_c = 0 \wedge \lambda_s = 0 \wedge \Re(\eta) > 0) +.. math:: C_{16}: \int_0^\infty G_{u, v}^{s, t}(\sigma x) \mathrm{d} x + \text{ converges at infinity } +.. math:: C_{17}: \int_0^\infty G_{p, q}^{m, n}(\omega x) \mathrm{d} x + \text{ converges at infinity } + +Note that `C_{16}` and `C_{17}` are the reason we split the convergence conditions for +integral (1). + +With this notation established, the implemented convergence conditions can be enumerated +as follows: + +1. .. math:: m n s t \neq 0 \wedge 0 < b^{*} \wedge 0 < c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{10} \wedge C_{12} +2. .. math:: u = v \wedge b^{*} = 0 \wedge 0 < c^{*} \wedge 0 < \sigma \wedge \Re{\rho} < 1 \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{12} +3. .. math:: p = q \wedge u = v \wedge b^{*} = 0 \wedge c^{*} = 0 \wedge 0 < \sigma \wedge 0 < \omega \wedge \Re{\mu} < 1 \wedge \Re{\rho} < 1 \wedge \sigma \neq \omega \wedge C_{1} \wedge C_{2} \wedge C_{3} +4. .. math:: p = q \wedge u = v \wedge b^{*} = 0 \wedge c^{*} = 0 \wedge 0 < \sigma \wedge 0 < \omega \wedge \Re\left(\mu + \rho\right) < 1 \wedge \omega \neq \sigma \wedge C_{1} \wedge C_{2} \wedge C_{3} +5. .. math:: p = q \wedge u = v \wedge b^{*} = 0 \wedge c^{*} = 0 \wedge 0 < \sigma \wedge 0 < \omega \wedge \Re\left(\mu + \rho\right) < 1 \wedge \omega \neq \sigma \wedge C_{1} \wedge C_{2} \wedge C_{3} +6. .. math:: q < p \wedge 0 < s \wedge 0 < b^{*} \wedge 0 \leq c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{5} \wedge C_{10} \wedge C_{13} +7. .. math:: p < q \wedge 0 < t \wedge 0 < b^{*} \wedge 0 \leq c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{4} \wedge C_{10} \wedge C_{13} +8. .. math:: v < u \wedge 0 < m \wedge 0 < c^{*} \wedge 0 \leq b^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{7} \wedge C_{11} \wedge C_{12} +9. .. math:: u < v \wedge 0 < n \wedge 0 < c^{*} \wedge 0 \leq b^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{6} \wedge C_{11} \wedge C_{12} +10. .. math:: q < p \wedge u = v \wedge b^{*} = 0 \wedge 0 \leq c^{*} \wedge 0 < \sigma \wedge \Re{\rho} < 1 \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{5} \wedge C_{13} +11. .. math:: p < q \wedge u = v \wedge b^{*} = 0 \wedge 0 \leq c^{*} \wedge 0 < \sigma \wedge \Re{\rho} < 1 \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{4} \wedge C_{13} +12. .. math:: p = q \wedge v < u \wedge 0 \leq b^{*} \wedge c^{*} = 0 \wedge 0 < \omega \wedge \Re{\mu} < 1 \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{7} \wedge C_{11} +13. .. math:: p = q \wedge u < v \wedge 0 \leq b^{*} \wedge c^{*} = 0 \wedge 0 < \omega \wedge \Re{\mu} < 1 \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{6} \wedge C_{11} +14. .. math:: p < q \wedge v < u \wedge 0 \leq b^{*} \wedge 0 \leq c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{4} \wedge C_{7} \wedge C_{11} \wedge C_{13} +15. .. math:: q < p \wedge u < v \wedge 0 \leq b^{*} \wedge 0 \leq c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{5} \wedge C_{6} \wedge C_{11} \wedge C_{13} +16. .. math:: q < p \wedge v < u \wedge 0 \leq b^{*} \wedge 0 \leq c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{5} \wedge C_{7} \wedge C_{8} \wedge C_{11} \wedge C_{13} \wedge C_{14} +17. .. math:: p < q \wedge u < v \wedge 0 \leq b^{*} \wedge 0 \leq c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{4} \wedge C_{6} \wedge C_{9} \wedge C_{11} \wedge C_{13} \wedge C_{14} +18. .. math:: t = 0 \wedge 0 < s \wedge 0 < b^{*} \wedge 0 < \phi \wedge C_{1} \wedge C_{2} \wedge C_{10} +19. .. math:: s = 0 \wedge 0 < t \wedge 0 < b^{*} \wedge \phi < 0 \wedge C_{1} \wedge C_{3} \wedge C_{10} +20. .. math:: n = 0 \wedge 0 < m \wedge 0 < c^{*} \wedge \phi < 0 \wedge C_{1} \wedge C_{2} \wedge C_{12} +21. .. math:: m = 0 \wedge 0 < n \wedge 0 < c^{*} \wedge 0 < \phi \wedge C_{1} \wedge C_{3} \wedge C_{12} +22. .. math:: s t = 0 \wedge 0 < b^{*} \wedge 0 < c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{10} \wedge C_{12} +23. .. math:: m n = 0 \wedge 0 < b^{*} \wedge 0 < c^{*} \wedge C_{1} \wedge C_{2} \wedge C_{3} \wedge C_{10} \wedge C_{12} +24. .. math:: p < m + n \wedge t = 0 \wedge \phi = 0 \wedge 0 < s \wedge 0 < b^{*} \wedge c^{*} < 0 \wedge \lvert{\operatorname{arg}\left(\omega\right)}\rvert < \\ \pi \left(m + n - p + 1\right) \wedge C_{1} \wedge C_{2} \wedge C_{10} \wedge C_{14} \wedge C_{15} +25. .. math:: q < m + n \wedge s = 0 \wedge \phi = 0 \wedge 0 < t \wedge 0 < b^{*} \wedge c^{*} < 0 \wedge \lvert{\operatorname{arg}\left(\omega\right)}\rvert < \\ \pi \left(m + n - q + 1\right) \wedge C_{1} \wedge C_{3} \wedge C_{10} \wedge C_{14} \wedge C_{15} +26. .. math:: p = q -1 \wedge t = 0 \wedge \phi = 0 \wedge 0 < s \wedge 0 < b^{*} \wedge 0 \leq c^{*} \wedge \pi c^{*} < \lvert{\operatorname{arg}\left(\omega\right)}\rvert \wedge C_{1} \wedge C_{2} \wedge C_{10} \wedge C_{14} \wedge C_{15} +27. .. math:: p = q + 1 \wedge s = 0 \wedge \phi = 0 \wedge 0 < t \wedge 0 < b^{*} \wedge 0 \leq c^{*} \wedge \pi c^{*} < \lvert{\operatorname{arg}\left(\omega\right)}\rvert \wedge C_{1} \wedge C_{3} \wedge C_{10} \wedge C_{14} \wedge C_{15} +28. .. math:: p < q -1 \wedge t = 0 \wedge \phi = 0 \wedge 0 < s \wedge 0 < b^{*} \wedge 0 \leq c^{*} \wedge \pi c^{*} < \lvert{\operatorname{arg}\left(\omega\right)}\rvert \wedge \lvert{\operatorname{arg}\left(\omega\right)}\rvert < \\ \pi \left(m + n - p + 1\right) \wedge C_{1} \wedge C_{2} \wedge C_{10} \wedge C_{14} \wedge C_{15} +29. .. math:: q + 1 < p \wedge s = 0 \wedge \phi = 0 \wedge 0 < t \wedge 0 < b^{*} \wedge 0 \leq c^{*} \wedge \pi c^{*} < \lvert{\operatorname{arg}\left(\omega\right)}\rvert \wedge \lvert{\operatorname{arg}\left(\omega\right)}\rvert < \\ \pi \left(m + n - q + 1 \right) \wedge C_{1} \wedge C_{3} \wedge C_{10} \wedge C_{14} \wedge C_{15} +30. .. math:: n = 0 \wedge \phi = 0 \wedge 0 < s + t \wedge 0 < m \wedge 0 < c^{*} \wedge b^{*} < 0 \wedge \lvert{\operatorname{arg}\left(\sigma\right)}\rvert < \\ \pi \left(s + t - u + 1\right) \wedge C_{1} \wedge C_{2} \wedge C_{12} \wedge C_{14} \wedge C_{15} +31. .. math:: m = 0 \wedge \phi = 0 \wedge v < s + t \wedge 0 < n \wedge 0 < c^{*} \wedge b^{*} < 0 \wedge \lvert{\operatorname{arg}\left(\sigma\right)}\rvert < \\ \pi \left(s + t - v + 1\right) \wedge C_{1} \wedge C_{3} \wedge C_{12} \wedge C_{14} \wedge C_{15} +32. .. math:: n = 0 \wedge \phi = 0 \wedge u = v -1 \wedge 0 < m \wedge 0 < c^{*} \wedge 0 \leq b^{*} \wedge \pi b^{*} < \lvert{\operatorname{arg}\left(\sigma\right)}\rvert \wedge \lvert{\operatorname{arg}\left(\sigma\right)}\rvert < \\ \pi \left(b^{*} + 1\right) \wedge C_{1} \wedge C_{2} \wedge C_{12} \wedge C_{14} \wedge C_{15} +33. .. math:: m = 0 \wedge \phi = 0 \wedge u = v + 1 \wedge 0 < n \wedge 0 < c^{*} \wedge 0 \leq b^{*} \wedge \pi b^{*} < \lvert{\operatorname{arg}\left(\sigma\right)}\rvert \wedge \lvert{\operatorname{arg}\left(\sigma\right)}\rvert < \\ \pi \left(b^{*} + 1\right) \wedge C_{1} \wedge C_{3} \wedge C_{12} \wedge C_{14} \wedge C_{15} +34. .. math:: n = 0 \wedge \phi = 0 \wedge u < v -1 \wedge 0 < m \wedge 0 < c^{*} \wedge 0 \leq b^{*} \wedge \pi b^{*} < \lvert{\operatorname{arg}\left(\sigma\right)}\rvert \wedge \lvert{\operatorname{arg}\left(\sigma\right)}\rvert < \\ \pi \left(s + t - u + 1\right) \wedge C_{1} \wedge C_{2} \wedge C_{12} \wedge C_{14} \wedge C_{15} +35. .. math:: m = 0 \wedge \phi = 0 \wedge v + 1 < u \wedge 0 < n \wedge 0 < c^{*} \wedge 0 \leq b^{*} \wedge \pi b^{*} < \lvert{\operatorname{arg}\left(\sigma\right)}\rvert \wedge \lvert{\operatorname{arg}\left(\sigma\right)}\rvert < \\ \pi \left(s + t - v + 1 \right) \wedge C_{1} \wedge C_{3} \wedge C_{12} \wedge C_{14} \wedge C_{15} +36. .. math:: C_{17} \wedge t = 0 \wedge u < s \wedge 0 < b^{*} \wedge C_{10} \wedge C_{1} \wedge C_{2} \wedge C_{3} +37. .. math:: C_{17} \wedge s = 0 \wedge v < t \wedge 0 < b^{*} \wedge C_{10} \wedge C_{1} \wedge C_{2} \wedge C_{3} +38. .. math:: C_{16} \wedge n = 0 \wedge p < m \wedge 0 < c^{*} \wedge C_{12} \wedge C_{1} \wedge C_{2} \wedge C_{3} +39. .. math:: C_{16} \wedge m = 0 \wedge q < n \wedge 0 < c^{*} \wedge C_{12} \wedge C_{1} \wedge C_{2} \wedge C_{3} + + +The Inverse Laplace Transform of a G-function +********************************************* + +The inverse laplace transform of a Meijer G-function can be expressed as +another G-function. This is a fairly versatile method for computing this +transform. However, I could not find the details in the literature, so I work +them out here. In [Luke1969]_, section 5.6.3, there is a formula for the inverse +Laplace transform of a G-function of argument `bz`, and convergence conditions +are also given. However, we need a formula for argument `bz^a` for rational `a`. + +We are asked to compute + +.. math :: + f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{zt} G(bz^a) \mathrm{d}z, + +for positive real `t`. Three questions arise: + +1. When does this integral converge? +2. How can we compute the integral? +3. When is our computation valid? + + +How to compute the integral +=========================== + +We shall work formally for now. Denote by `\Delta(s)` the product of gamma +functions appearing in the definition of `G`, so that + +.. math :: G(z) = \frac{1}{2\pi i} \int_L \Delta(s) z^s \mathrm{d}s. + +Thus + +.. math :: + f(t) = \frac{1}{(2\pi i)^2} \int_{c - i\infty}^{c + i\infty} \int_L + e^{zt} \Delta(s) b^s z^{as} \mathrm{d}s \mathrm{d}z. + +We interchange the order of integration to get + +.. math :: + f(t) = \frac{1}{2\pi i} \int_L b^s \Delta(s) + \int_{c-i\infty}^{c+i\infty} e^{zt} z^{as} \frac{\mathrm{d}z}{2\pi i} + \mathrm{d}s. + +The inner integral is easily seen to be +`\frac{1}{\Gamma(-as)} \frac{1}{t^{1+as}}`. (Using Cauchy's theorem and Jordan's +lemma deform the contour to run from `-\infty` to `-\infty`, encircling `0` once +in the negative sense. For `as` real and greater than one, +this contour can be pushed onto +the negative real axis and the integral is recognised as a product of a sine and +a gamma function. The formula is then proved using the functional equation of the +gamma function, and extended to the entire domain of convergence of the original +integral by appealing to analytic continuation.) +Hence we find + +.. math :: + f(t) = \frac{1}{t} \frac{1}{2\pi i} \int_L \Delta(s) \frac{1}{\Gamma(-as)} + \left(\frac{b}{t^a}\right)^s \mathrm{d}s, + +which is a so-called Fox H function (of argument `\frac{b}{t^a}`). For rational +`a`, this can be expressed as a Meijer G-function using the gamma function +multiplication theorem. + +When this computation is valid +============================== + +There are a number of obstacles in this computation. Interchange of integrals +is only valid if all integrals involved are absolutely convergent. In +particular the inner integral has to converge. Also, for our identification of +the final integral as a Fox H / Meijer G-function to be correct, the poles of +the newly obtained gamma function must be separated properly. + +It is easy to check that the inner integral converges absolutely for +`\Re(as) < -1`. Thus the contour `L` has to run left of the line `\Re(as) = -1`. +Under this condition, the poles of the newly-introduced gamma function are +separated properly. + +It remains to observe that the Meijer G-function is an analytic, unbranched +function of its parameters, and of the coefficient `b`. Hence so is `f(t)`. +Thus the final computation remains valid as long as the initial integral +converges, and if there exists a changed set of parameters where the computation +is valid. If we assume w.l.o.g. that `a > 0`, then the latter condition is +fulfilled if `G` converges along contours (2) or (3) of [Luke1969]_, +section 5.2, i.e. either `\delta \ge \frac{a}{2}` or `p \ge 1, p \ge q`. + +When the integral exists +======================== + +Using [Luke1969]_, section 5.10, for any given meijer G-function we can find a +dominant term of the form `z^a e^{bz^c}` (although this expression might not be +the best possible, because of cancellation). + +We must thus investigate + +.. math :: \lim_{T \to \infty} \int_{c-iT}^{c+iT} + e^{zt} z^a e^{bz^c} \mathrm{d}z. + +(This principal value integral is the exact statement used in the Laplace +inversion theorem.) We write `z = c + i \tau`. Then +`arg(z) \to \pm \frac{\pi}{2}`, and so `e^{zt} \sim e^{it \tau}` (where `\sim` +shall always mean "asymptotically equivalent up to a positive real +multiplicative constant"). Also +`z^{x + iy} \sim |\tau|^x e^{i y \log{|\tau|}} e^{\pm x i \frac{\pi}{2}}.` + +Set `\omega_{\pm} = b e^{\pm i \Re(c) \frac{\pi}{2}}`. We have three cases: + +1. `b=0` or `\Re(c) \le 0`. + In this case the integral converges if `\Re(a) \le -1`. +2. `b \ne 0`, `\Im(c) = 0`, `\Re(c) > 0`. + In this case the integral converges if `\Re(\omega_{\pm}) < 0`. +3. `b \ne 0`, `\Im(c) = 0`, `\Re(c) > 0`, `\Re(\omega_{\pm}) \le 0`, and at least + one of `\Re(\omega_{\pm}) = 0`. + Here the same condition as in (1) applies. + +Implemented G-Function Formulae +******************************* + +An important part of the algorithm is a table expressing various functions +as Meijer G-functions. This is essentially a table of Mellin Transforms in +disguise. The following automatically generated table shows the formulae +currently implemented in SymPy. An entry "generated" means that the +corresponding G-function has a variable number of parameters. +This table is intended to shrink in future, when the algorithm's capabilities +of deriving new formulae improve. Of course it has to grow whenever a new class +of special functions is to be dealt with. + +.. automodule:: sympy.integrals.meijerint_doc + +Internal API Reference +********************** + +.. automodule:: sympy.integrals.meijerint + :members: + :private-members: diff --git a/rst/math/linear_model_1a957c.rst b/rst/math/linear_model_1a957c.rst new file mode 100644 index 0000000..7e88dbb --- /dev/null +++ b/rst/math/linear_model_1a957c.rst @@ -0,0 +1,1957 @@ +.. _linear_model: + +============= +Linear Models +============= + +.. currentmodule:: sklearn.linear_model + +The following are a set of methods intended for regression in which +the target value is expected to be a linear combination of the features. +In mathematical notation, the predicted value :math:`\hat{y}` can be +written as: + + +.. math:: \hat{y}(w, x) = w_0 + w_1 x_1 + ... + w_p x_p + +Across the module, we designate the vector :math:`w = (w_1, +..., w_p)` as ``coef_`` and :math:`w_0` as ``intercept_``. + +To perform classification with generalized linear models, see +:ref:`Logistic_regression`. + +.. _ordinary_least_squares: + +Ordinary Least Squares +======================= + +:class:`LinearRegression` fits a linear model with coefficients +:math:`w = (w_1, ..., w_p)` to minimize the residual sum +of squares between the observed targets in the dataset, and the +targets predicted by the linear approximation. Mathematically it +solves a problem of the form: + +.. math:: \min_{w} || X w - y||_2^2 + +.. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_ols_ridge_001.png + :target: ../auto_examples/linear_model/plot_ols_ridge.html + :align: center + :scale: 50% + +:class:`LinearRegression` takes in its ``fit`` method arguments ``X``, ``y``, +``sample_weight`` and stores the coefficients :math:`w` of the linear model in its +``coef_`` and ``intercept_`` attributes:: + + >>> from sklearn import linear_model + >>> reg = linear_model.LinearRegression() + >>> reg.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) + LinearRegression() + >>> reg.coef_ + array([0.5, 0.5]) + >>> reg.intercept_ + 0.0 + +The coefficient estimates for Ordinary Least Squares rely on the +independence of the features. When features are correlated and some +columns of the design matrix :math:`X` have an approximately linear +dependence, the design matrix becomes close to singular +and as a result, the least-squares estimate becomes highly sensitive +to random errors in the observed target, producing a large +variance. This situation of *multicollinearity* can arise, for +example, when data are collected without an experimental design. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_ols_ridge.py` + +Non-Negative Least Squares +-------------------------- + +It is possible to constrain all the coefficients to be non-negative, which may +be useful when they represent some physical or naturally non-negative +quantities (e.g., frequency counts or prices of goods). +:class:`LinearRegression` accepts a boolean ``positive`` +parameter: when set to `True` `Non-Negative Least Squares +`_ are then applied. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_nnls.py` + +Ordinary Least Squares Complexity +--------------------------------- + +The least squares solution is computed using the singular value +decomposition of :math:`X`. If :math:`X` is a matrix of shape `(n_samples, n_features)` +this method has a cost of +:math:`O(n_{\text{samples}} n_{\text{features}}^2)`, assuming that +:math:`n_{\text{samples}} \geq n_{\text{features}}`. + +.. _ridge_regression: + +Ridge regression and classification +=================================== + +Regression +---------- + +:class:`Ridge` regression addresses some of the problems of +:ref:`ordinary_least_squares` by imposing a penalty on the size of the +coefficients. The ridge coefficients minimize a penalized residual sum +of squares: + + +.. math:: + + \min_{w} || X w - y||_2^2 + \alpha ||w||_2^2 + + +The complexity parameter :math:`\alpha \geq 0` controls the amount +of shrinkage: the larger the value of :math:`\alpha`, the greater the amount +of shrinkage and thus the coefficients become more robust to collinearity. + +.. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_ridge_path_001.png + :target: ../auto_examples/linear_model/plot_ridge_path.html + :align: center + :scale: 50% + + +As with other linear models, :class:`Ridge` will take in its ``fit`` method +arrays ``X``, ``y`` and will store the coefficients :math:`w` of the linear model in +its ``coef_`` member:: + + >>> from sklearn import linear_model + >>> reg = linear_model.Ridge(alpha=.5) + >>> reg.fit([[0, 0], [0, 0], [1, 1]], [0, .1, 1]) + Ridge(alpha=0.5) + >>> reg.coef_ + array([0.34545455, 0.34545455]) + >>> reg.intercept_ + np.float64(0.13636) + +Note that the class :class:`Ridge` allows for the user to specify that the +solver be automatically chosen by setting `solver="auto"`. When this option +is specified, :class:`Ridge` will choose between the `"lbfgs"`, `"cholesky"`, +and `"sparse_cg"` solvers. :class:`Ridge` will begin checking the conditions +shown in the following table from top to bottom. If the condition is true, +the corresponding solver is chosen. + ++-------------+----------------------------------------------------+ +| **Solver** | **Condition** | ++-------------+----------------------------------------------------+ +| 'lbfgs' | The ``positive=True`` option is specified. | ++-------------+----------------------------------------------------+ +| 'cholesky' | The input array X is not sparse. | ++-------------+----------------------------------------------------+ +| 'sparse_cg' | None of the above conditions are fulfilled. | ++-------------+----------------------------------------------------+ + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_ols_ridge.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_ridge_path.py` +* :ref:`sphx_glr_auto_examples_inspection_plot_linear_model_coefficient_interpretation.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_ridge_coeffs.py` + +Classification +-------------- + +The :class:`Ridge` regressor has a classifier variant: +:class:`RidgeClassifier`. This classifier first converts binary targets to +``{-1, 1}`` and then treats the problem as a regression task, optimizing the +same objective as above. The predicted class corresponds to the sign of the +regressor's prediction. For multiclass classification, the problem is +treated as multi-output regression, and the predicted class corresponds to +the output with the highest value. + +It might seem questionable to use a (penalized) Least Squares loss to fit a +classification model instead of the more traditional logistic or hinge +losses. However, in practice, all those models can lead to similar +cross-validation scores in terms of accuracy or precision/recall, while the +penalized least squares loss used by the :class:`RidgeClassifier` allows for +a very different choice of the numerical solvers with distinct computational +performance profiles. + +The :class:`RidgeClassifier` can be significantly faster than e.g. +:class:`LogisticRegression` with a high number of classes because it can +compute the projection matrix :math:`(X^T X)^{-1} X^T` only once. + +This classifier is sometimes referred to as a `Least Squares Support Vector +Machine +`_ with +a linear kernel. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_text_plot_document_classification_20newsgroups.py` + + +Ridge Complexity +---------------- + +This method has the same order of complexity as +:ref:`ordinary_least_squares`. + +.. FIXME: +.. Not completely true: OLS is solved by an SVD, while Ridge is solved by +.. the method of normal equations (Cholesky), there is a big flop difference +.. between these + + +Setting the regularization parameter: leave-one-out Cross-Validation +-------------------------------------------------------------------- + +:class:`RidgeCV` and :class:`RidgeClassifierCV` implement ridge +regression/classification with built-in cross-validation of the alpha parameter. +They work in the same way as :class:`~sklearn.model_selection.GridSearchCV` except +that it defaults to efficient Leave-One-Out :term:`cross-validation`. +When using the default :term:`cross-validation`, alpha cannot be 0 due to the +formulation used to calculate Leave-One-Out error. See [RL2007]_ for details. + +Usage example:: + + >>> import numpy as np + >>> from sklearn import linear_model + >>> reg = linear_model.RidgeCV(alphas=np.logspace(-6, 6, 13)) + >>> reg.fit([[0, 0], [0, 0.1], [1, 1]], [0, -0.1, 1]) + RidgeCV(alphas=array([1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01, + 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06])) + >>> reg.alpha_ + np.float64(0.1) + +Specifying the value of the :term:`cv` attribute will trigger the use of +cross-validation with :class:`~sklearn.model_selection.GridSearchCV`, for +example `cv=10` for 10-fold cross-validation, rather than Leave-One-Out +Cross-Validation. + +.. dropdown:: References + + .. [RL2007] "Notes on Regularized Least Squares", Rifkin & Lippert (`technical report + `_, + `course slides `_). + +.. _lasso: + +Lasso +===== + +The :class:`Lasso` is a linear model that estimates sparse coefficients, i.e., it is +able to set coefficients exactly to zero. +It is useful in some contexts due to its tendency to prefer solutions +with fewer non-zero coefficients, effectively reducing the number of +features upon which the given solution is dependent. For this reason, +Lasso and its variants are fundamental to the field of compressed sensing. +Under certain conditions, it can recover the exact set of non-zero coefficients (see +:ref:`sphx_glr_auto_examples_applications_plot_tomography_l1_reconstruction.py`). + +Mathematically, it consists of a linear model with an added regularization term. +The objective function to minimize is: + +.. math:: \min_{w} P(w) = {\frac{1}{2n_{\text{samples}}} ||X w - y||_2 ^ 2 + \alpha ||w||_1} + +The lasso estimate thus solves the least-squares with added penalty +:math:`\alpha ||w||_1`, where :math:`\alpha` is a constant and :math:`||w||_1` is the +:math:`\ell_1`-norm of the coefficient vector. + +The implementation in the class :class:`Lasso` uses coordinate descent as +the algorithm to fit the coefficients. See :ref:`least_angle_regression` +for another implementation:: + + >>> from sklearn import linear_model + >>> reg = linear_model.Lasso(alpha=0.1) + >>> reg.fit([[0, 0], [1, 1]], [0, 1]) + Lasso(alpha=0.1) + >>> reg.predict([[1, 1]]) + array([0.8]) + +The function :func:`lasso_path` is useful for lower-level tasks, as it +computes the coefficients along the full path of possible values. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py` +* :ref:`sphx_glr_auto_examples_applications_plot_tomography_l1_reconstruction.py` +* :ref:`sphx_glr_auto_examples_inspection_plot_linear_model_coefficient_interpretation.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_model_selection.py` + + +.. note:: **Feature selection with Lasso** + + As the Lasso regression yields sparse models, it can + thus be used to perform feature selection, as detailed in + :ref:`l1_feature_selection`. + +.. dropdown:: References + + The following references explain the origin of the Lasso as well as properties + of the Lasso problem and the duality gap computation used for convergence control. + + * :doi:`Robert Tibshirani. (1996) Regression Shrinkage and Selection Via the Lasso. + J. R. Stat. Soc. Ser. B Stat. Methodol., 58(1):267-288 + <10.1111/j.2517-6161.1996.tb02080.x>` + * "An Interior-Point Method for Large-Scale L1-Regularized Least Squares," + S. J. Kim, K. Koh, M. Lustig, S. Boyd and D. Gorinevsky, + in IEEE Journal of Selected Topics in Signal Processing, 2007 + (`Paper `__) + +.. _coordinate_descent: + +Coordinate Descent with Gap Safe Screening Rules +------------------------------------------------ + +Coordinate descent (CD) is a strategy to solve a minimization problem that considers a +single feature :math:`j` at a time. This way, the optimization problem is reduced to a +1-dimensional problem which is easier to solve: + +.. math:: \min_{w_j} {\frac{1}{2n_{\text{samples}}} ||x_j w_j + X_{-j}w_{-j} - y||_2 ^ 2 + \alpha |w_j|} + +with index :math:`-j` meaning all features but :math:`j`. The solution is + +.. math:: w_j = \frac{S(x_j^T (y - X_{-j}w_{-j}), \alpha)}{||x_j||_2^2} + +with the soft-thresholding function +:math:`S(z, \alpha) = \operatorname{sign}(z) \max(0, |z|-\alpha)`. +Note that the soft-thresholding function is exactly zero whenever +:math:`\alpha \geq |z|`. +The CD solver then loops over the features either in a cycle, picking one feature after +the other in the order given by `X` (`selection="cyclic"`), or by randomly picking +features (`selection="random"`). +It stops if the duality gap is smaller than the provided tolerance `tol`. + +.. dropdown:: Mathematical details + + The duality gap :math:`G(w, v)` is an upper bound of the difference between the + current primal objective function of the Lasso, :math:`P(w)`, and its minimum + :math:`P(w^\star)`, i.e. :math:`G(w, v) \geq P(w) - P(w^\star)`. It is given by + :math:`G(w, v) = P(w) - D(v)` with dual objective function + + .. math:: D(v) = \frac{1}{2n_{\text{samples}}}(y^Tv - ||v||_2^2) + + subject to :math:`v \in ||X^Tv||_{\infty} \leq n_{\text{samples}}\alpha`. + At optimum, the duality gap is zero, :math:`G(w^\star, v^\star) = 0` (a property + called strong duality). + With (scaled) dual variable :math:`v = c r`, current residual :math:`r = y - Xw` and + dual scaling + + .. math:: + c = \begin{cases} + 1, & ||X^Tr||_{\infty} \leq n_{\text{samples}}\alpha, \\ + \frac{n_{\text{samples}}\alpha}{||X^Tr||_{\infty}}, & \text{otherwise} + \end{cases} + + the stopping criterion is + + .. math:: \text{tol} \frac{||y||_2^2}{n_{\text{samples}}} < G(w, cr)\,. + +A clever method to speedup the coordinate descent algorithm is to screen features such +that at optimum :math:`w_j = 0`. Gap safe screening rules are such a +tool. Anywhere during the optimization algorithm, they can tell which feature we can +safely exclude, i.e., set to zero with certainty. + +.. dropdown:: References + + The first reference explains the coordinate descent solver used in scikit-learn, the + others treat gap safe screening rules. + + * :doi:`Friedman, Hastie & Tibshirani. (2010). + Regularization Path For Generalized linear Models by Coordinate Descent. + J Stat Softw 33(1), 1-22 <10.18637/jss.v033.i01>` + * :arxiv:`O. Fercoq, A. Gramfort, J. Salmon. (2015). + Mind the duality gap: safer rules for the Lasso. + Proceedings of Machine Learning Research 37:333-342, 2015. + <1505.03410>` + * :arxiv:`E. Ndiaye, O. Fercoq, A. Gramfort, J. Salmon. (2017). + Gap Safe Screening Rules for Sparsity Enforcing Penalties. + Journal of Machine Learning Research 18(128):1-33, 2017. + <1611.05780>` + +Setting regularization parameter +-------------------------------- + +The ``alpha`` parameter controls the degree of sparsity of the estimated +coefficients. + +Using cross-validation +^^^^^^^^^^^^^^^^^^^^^^^ + +scikit-learn exposes objects that set the Lasso ``alpha`` parameter by +cross-validation: :class:`LassoCV` and :class:`LassoLarsCV`. +:class:`LassoLarsCV` is based on the :ref:`least_angle_regression` algorithm +explained below. + +For high-dimensional datasets with many collinear features, +:class:`LassoCV` is most often preferable. However, :class:`LassoLarsCV` has +the advantage of exploring more relevant values of `alpha` parameter, and +if the number of samples is very small compared to the number of +features, it is often faster than :class:`LassoCV`. + +.. |lasso_cv_1| image:: ../auto_examples/linear_model/images/sphx_glr_plot_lasso_model_selection_002.png + :target: ../auto_examples/linear_model/plot_lasso_model_selection.html + :scale: 48% + +.. |lasso_cv_2| image:: ../auto_examples/linear_model/images/sphx_glr_plot_lasso_model_selection_003.png + :target: ../auto_examples/linear_model/plot_lasso_model_selection.html + :scale: 48% + +.. centered:: |lasso_cv_1| |lasso_cv_2| + +.. _lasso_lars_ic: + +Information-criteria based model selection +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Alternatively, the estimator :class:`LassoLarsIC` proposes to use the +Akaike information criterion (AIC) and the Bayes Information criterion (BIC). +It is a computationally cheaper alternative to find the optimal value of alpha +as the regularization path is computed only once instead of k+1 times +when using k-fold cross-validation. + +Indeed, these criteria are computed on the in-sample training set. In short, +they penalize the over-optimistic scores of the different Lasso models by +their flexibility (cf. to "Mathematical details" section below). + +However, such criteria need a proper estimation of the degrees of freedom of +the solution, are derived for large samples (asymptotic results) and assume the +correct model is candidates under investigation. They also tend to break when +the problem is badly conditioned (e.g. more features than samples). + +.. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_lasso_lars_ic_001.png + :target: ../auto_examples/linear_model/plot_lasso_lars_ic.html + :align: center + :scale: 50% + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_model_selection.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_lars_ic.py` + +.. _aic_bic: + +AIC and BIC criteria +^^^^^^^^^^^^^^^^^^^^ + +The definition of AIC (and thus BIC) might differ in the literature. In this +section, we give more information regarding the criterion computed in +scikit-learn. + +.. dropdown:: Mathematical details + + The AIC criterion is defined as: + + .. math:: + AIC = -2 \log(\hat{L}) + 2 d + + where :math:`\hat{L}` is the maximum likelihood of the model and + :math:`d` is the number of parameters (as well referred to as degrees of + freedom in the previous section). + + The definition of BIC replaces the constant :math:`2` by :math:`\log(N)`: + + .. math:: + BIC = -2 \log(\hat{L}) + \log(N) d + + where :math:`N` is the number of samples. + + For a linear Gaussian model, the maximum log-likelihood is defined as: + + .. math:: + \log(\hat{L}) = - \frac{n}{2} \log(2 \pi) - \frac{n}{2} \log(\sigma^2) - \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{2\sigma^2} + + where :math:`\sigma^2` is an estimate of the noise variance, + :math:`y_i` and :math:`\hat{y}_i` are respectively the true and predicted + targets, and :math:`n` is the number of samples. + + Plugging the maximum log-likelihood in the AIC formula yields: + + .. math:: + AIC = n \log(2 \pi \sigma^2) + \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{\sigma^2} + 2 d + + The first term of the above expression is sometimes discarded since it is a + constant when :math:`\sigma^2` is provided. In addition, + it is sometimes stated that the AIC is equivalent to the :math:`C_p` statistic + [12]_. In a strict sense, however, it is equivalent only up to some constant + and a multiplicative factor. + + At last, we mentioned above that :math:`\sigma^2` is an estimate of the + noise variance. In :class:`LassoLarsIC` when the parameter `noise_variance` is + not provided (default), the noise variance is estimated via the unbiased + estimator [13]_ defined as: + + .. math:: + \sigma^2 = \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{n - p} + + where :math:`p` is the number of features and :math:`\hat{y}_i` is the + predicted target using an ordinary least squares regression. Note, that this + formula is valid only when `n_samples > n_features`. + + .. rubric:: References + + .. [12] :arxiv:`Zou, Hui, Trevor Hastie, and Robert Tibshirani. + "On the degrees of freedom of the lasso." + The Annals of Statistics 35.5 (2007): 2173-2192. + <0712.0881.pdf>` + + .. [13] :doi:`Cherkassky, Vladimir, and Yunqian Ma. + "Comparison of model selection for regression." + Neural computation 15.7 (2003): 1691-1714. + <10.1162/089976603321891864>` + +Comparison with the regularization parameter of SVM +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The equivalence between ``alpha`` and the regularization parameter of SVM, +``C`` is given by ``alpha = 1 / C`` or ``alpha = 1 / (n_samples * C)``, +depending on the estimator and the exact objective function optimized by the +model. + +.. _multi_task_lasso: + +Multi-task Lasso +================ + +The :class:`MultiTaskLasso` is a linear model that estimates sparse +coefficients for multiple regression problems jointly: ``y`` is a 2D array, +of shape ``(n_samples, n_tasks)``. The constraint is that the selected +features are the same for all the regression problems, also called tasks. + +The following figure compares the location of the non-zero entries in the +coefficient matrix W obtained with a simple Lasso or a MultiTaskLasso. +The Lasso estimates yield scattered non-zeros while the non-zeros of +the MultiTaskLasso are full columns. + +.. |multi_task_lasso_1| image:: ../auto_examples/linear_model/images/sphx_glr_plot_multi_task_lasso_support_001.png + :target: ../auto_examples/linear_model/plot_multi_task_lasso_support.html + :scale: 48% + +.. |multi_task_lasso_2| image:: ../auto_examples/linear_model/images/sphx_glr_plot_multi_task_lasso_support_002.png + :target: ../auto_examples/linear_model/plot_multi_task_lasso_support.html + :scale: 48% + +.. centered:: |multi_task_lasso_1| |multi_task_lasso_2| + +.. centered:: Fitting a time-series model, imposing that any active feature be active at all times. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_multi_task_lasso_support.py` + + +.. dropdown:: Mathematical details + + Mathematically, it consists of a linear model trained with a mixed + :math:`\ell_1` :math:`\ell_2`-norm for regularization. + The objective function to minimize is: + + .. math:: \min_{W} { \frac{1}{2n_{\text{samples}}} ||X W - Y||_{\text{Fro}} ^ 2 + \alpha ||W||_{21}} + + where :math:`\text{Fro}` indicates the Frobenius norm + + .. math:: ||A||_{\text{Fro}} = \sqrt{\sum_{ij} a_{ij}^2} + + and :math:`\ell_1` :math:`\ell_2` reads + + .. math:: ||A||_{2 1} = \sum_i \sqrt{\sum_j a_{ij}^2}. + + The implementation in the class :class:`MultiTaskLasso` uses + coordinate descent as the algorithm to fit the coefficients. + +.. _elastic_net: + +Elastic-Net +=========== +:class:`ElasticNet` is a linear regression model trained with both +:math:`\ell_1` and :math:`\ell_2`-norm regularization of the coefficients. +This combination allows for learning a sparse model where few of +the weights are non-zero like :class:`Lasso`, while still maintaining +the regularization properties of :class:`Ridge`. We control the convex +combination of :math:`\ell_1` and :math:`\ell_2` using the ``l1_ratio`` +parameter. + +Elastic-net is useful when there are multiple features that are +correlated with one another. Lasso is likely to pick one of these +at random, while elastic-net is likely to pick both. + +A practical advantage of trading-off between Lasso and Ridge is that it +allows Elastic-Net to inherit some of Ridge's stability under rotation. + +The objective function to minimize is in this case + +.. math:: + + \min_{w} { \frac{1}{2n_{\text{samples}}} ||X w - y||_2 ^ 2 + \alpha \rho ||w||_1 + + \frac{\alpha(1-\rho)}{2} ||w||_2 ^ 2} + + +.. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_lasso_lasso_lars_elasticnet_path_002.png + :target: ../auto_examples/linear_model/plot_lasso_lasso_lars_elasticnet_path.html + :align: center + :scale: 50% + +The class :class:`ElasticNetCV` can be used to set the parameters +``alpha`` (:math:`\alpha`) and ``l1_ratio`` (:math:`\rho`) by cross-validation. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_lasso_lars_elasticnet_path.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_elastic_net_precomputed_gram_matrix_with_weighted_samples.py` + +.. dropdown:: References + + The following two references explain the iterations + used in the coordinate descent solver of scikit-learn, as well as + the duality gap computation used for convergence control. + + * "Regularization Path For Generalized linear Models by Coordinate Descent", + Friedman, Hastie & Tibshirani, J Stat Softw, 2010 (`Paper + `__). + * "An Interior-Point Method for Large-Scale L1-Regularized Least Squares," + S. J. Kim, K. Koh, M. Lustig, S. Boyd and D. Gorinevsky, + in IEEE Journal of Selected Topics in Signal Processing, 2007 + (`Paper `__) + +.. _multi_task_elastic_net: + +Multi-task Elastic-Net +====================== + +The :class:`MultiTaskElasticNet` is an elastic-net model that estimates sparse +coefficients for multiple regression problems jointly: ``Y`` is a 2D array +of shape ``(n_samples, n_tasks)``. The constraint is that the selected +features are the same for all the regression problems, also called tasks. + +Mathematically, it consists of a linear model trained with a mixed +:math:`\ell_1` :math:`\ell_2`-norm and :math:`\ell_2`-norm for regularization. +The objective function to minimize is: + +.. math:: + + \min_{W} { \frac{1}{2n_{\text{samples}}} ||X W - Y||_{\text{Fro}}^2 + \alpha \rho ||W||_{2 1} + + \frac{\alpha(1-\rho)}{2} ||W||_{\text{Fro}}^2} + +The implementation in the class :class:`MultiTaskElasticNet` uses coordinate descent as +the algorithm to fit the coefficients. + +The class :class:`MultiTaskElasticNetCV` can be used to set the parameters +``alpha`` (:math:`\alpha`) and ``l1_ratio`` (:math:`\rho`) by cross-validation. + +.. _least_angle_regression: + +Least Angle Regression +====================== + +Least-angle regression (LARS) is a regression algorithm for +high-dimensional data, developed by Bradley Efron, Trevor Hastie, Iain +Johnstone and Robert Tibshirani. LARS is similar to forward stepwise +regression. At each step, it finds the feature most correlated with the +target. When there are multiple features having equal correlation, instead +of continuing along the same feature, it proceeds in a direction equiangular +between the features. + +The advantages of LARS are: + +- It is numerically efficient in contexts where the number of features + is significantly greater than the number of samples. + +- It is computationally just as fast as forward selection and has + the same order of complexity as ordinary least squares. + +- It produces a full piecewise linear solution path, which is + useful in cross-validation or similar attempts to tune the model. + +- If two features are almost equally correlated with the target, + then their coefficients should increase at approximately the same + rate. The algorithm thus behaves as intuition would expect, and + also is more stable. + +- It is easily modified to produce solutions for other estimators, + like the Lasso. + +The disadvantages of the LARS method include: + +- Because LARS is based upon an iterative refitting of the + residuals, it would appear to be especially sensitive to the + effects of noise. This problem is discussed in detail by Weisberg + in the discussion section of the Efron et al. (2004) Annals of + Statistics article. + +The LARS model can be used via the estimator :class:`Lars`, or its +low-level implementation :func:`lars_path` or :func:`lars_path_gram`. + + +LARS Lasso +========== + +:class:`LassoLars` is a lasso model implemented using the LARS +algorithm, and unlike the implementation based on coordinate descent, +this yields the exact solution, which is piecewise linear as a +function of the norm of its coefficients. + +.. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_lasso_lasso_lars_elasticnet_path_001.png + :target: ../auto_examples/linear_model/plot_lasso_lasso_lars_elasticnet_path.html + :align: center + :scale: 50% + +:: + + >>> from sklearn import linear_model + >>> reg = linear_model.LassoLars(alpha=.1) + >>> reg.fit([[0, 0], [1, 1]], [0, 1]) + LassoLars(alpha=0.1) + >>> reg.coef_ + array([0.6, 0. ]) + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_lasso_lars_elasticnet_path.py` + +The LARS algorithm provides the full path of the coefficients along +the regularization parameter almost for free, thus a common operation +is to retrieve the path with one of the functions :func:`lars_path` +or :func:`lars_path_gram`. + +.. dropdown:: Mathematical formulation + + The algorithm is similar to forward stepwise regression, but instead + of including features at each step, the estimated coefficients are + increased in a direction equiangular to each one's correlations with + the residual. + + Instead of giving a vector result, the LARS solution consists of a + curve denoting the solution for each value of the :math:`\ell_1` norm of the + parameter vector. The full coefficients path is stored in the array + ``coef_path_`` of shape `(n_features, max_features + 1)`. The first + column is always zero. + + .. rubric:: References + + * Original Algorithm is detailed in the paper `Least Angle Regression + `_ + by Hastie et al. + +.. _omp: + +Orthogonal Matching Pursuit (OMP) +================================= +:class:`OrthogonalMatchingPursuit` and :func:`orthogonal_mp` implement the OMP +algorithm for approximating the fit of a linear model with constraints imposed +on the number of non-zero coefficients (i.e. the :math:`\ell_0` pseudo-norm). + +Being a forward feature selection method like :ref:`least_angle_regression`, +orthogonal matching pursuit can approximate the optimum solution vector with a +fixed number of non-zero elements: + +.. math:: + \underset{w}{\operatorname{arg\,min\,}} ||y - Xw||_2^2 \text{ subject to } ||w||_0 \leq n_{\text{nonzero_coefs}} + +Alternatively, orthogonal matching pursuit can target a specific error instead +of a specific number of non-zero coefficients. This can be expressed as: + +.. math:: + \underset{w}{\operatorname{arg\,min\,}} ||w||_0 \text{ subject to } ||y-Xw||_2^2 \leq \text{tol} + + +OMP is based on a greedy algorithm that includes at each step the atom most +highly correlated with the current residual. It is similar to the simpler +matching pursuit (MP) method, but better in that at each iteration, the +residual is recomputed using an orthogonal projection on the space of the +previously chosen dictionary elements. + + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_omp.py` + +.. dropdown:: References + + * https://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf + + * `Matching pursuits with time-frequency dictionaries + `_, + S. G. Mallat, Z. Zhang, 1993. + +.. _bayesian_regression: + +Bayesian Regression +=================== + +Bayesian regression techniques can be used to include regularization +parameters in the estimation procedure: the regularization parameter is +not set in a hard sense but tuned to the data at hand. + +This can be done by introducing `uninformative priors +`__ +over the hyper parameters of the model. +The :math:`\ell_{2}` regularization used in :ref:`ridge_regression` is +equivalent to finding a maximum a posteriori estimation under a Gaussian prior +over the coefficients :math:`w` with precision :math:`\lambda^{-1}`. +Instead of setting `\lambda` manually, it is possible to treat it as a random +variable to be estimated from the data. + +To obtain a fully probabilistic model, the output :math:`y` is assumed +to be Gaussian distributed around :math:`X w`: + +.. math:: p(y|X,w,\alpha) = \mathcal{N}(y|X w,\alpha^{-1}) + +where :math:`\alpha` is again treated as a random variable that is to be +estimated from the data. + +The advantages of Bayesian Regression are: + +- It adapts to the data at hand. + +- It can be used to include regularization parameters in the + estimation procedure. + +The disadvantages of Bayesian regression include: + +- Inference of the model can be time consuming. + +.. dropdown:: References + + * A good introduction to Bayesian methods is given in `C. Bishop: Pattern + Recognition and Machine Learning + `__. + + * Original Algorithm is detailed in the book `Bayesian learning for neural + networks + `__ + by Radford M. Neal. + +.. _bayesian_ridge_regression: + +Bayesian Ridge Regression +------------------------- + +:class:`BayesianRidge` estimates a probabilistic model of the +regression problem as described above. +The prior for the coefficient :math:`w` is given by a spherical Gaussian: + +.. math:: p(w|\lambda) = + \mathcal{N}(w|0,\lambda^{-1}\mathbf{I}_{p}) + +The priors over :math:`\alpha` and :math:`\lambda` are chosen to be `gamma +distributions `__, the +conjugate prior for the precision of the Gaussian. The resulting model is +called *Bayesian Ridge Regression*, and is similar to the classical +:class:`Ridge`. + +The parameters :math:`w`, :math:`\alpha` and :math:`\lambda` are estimated +jointly during the fit of the model, the regularization parameters +:math:`\alpha` and :math:`\lambda` being estimated by maximizing the +*log marginal likelihood*. The scikit-learn implementation +is based on the algorithm described in Appendix A of (Tipping, 2001) +where the update of the parameters :math:`\alpha` and :math:`\lambda` is done +as suggested in (MacKay, 1992). The initial value of the maximization procedure +can be set with the hyperparameters ``alpha_init`` and ``lambda_init``. + +There are four more hyperparameters, :math:`\alpha_1`, :math:`\alpha_2`, +:math:`\lambda_1` and :math:`\lambda_2` of the gamma prior distributions over +:math:`\alpha` and :math:`\lambda`. These are usually chosen to be +*non-informative*. By default :math:`\alpha_1 = \alpha_2 = \lambda_1 = \lambda_2 = 10^{-6}`. + +Bayesian Ridge Regression is used for regression:: + + >>> from sklearn import linear_model + >>> X = [[0., 0.], [1., 1.], [2., 2.], [3., 3.]] + >>> Y = [0., 1., 2., 3.] + >>> reg = linear_model.BayesianRidge() + >>> reg.fit(X, Y) + BayesianRidge() + +After being fitted, the model can then be used to predict new values:: + + >>> reg.predict([[1, 0.]]) + array([0.50000013]) + +The coefficients :math:`w` of the model can be accessed:: + + >>> reg.coef_ + array([0.49999993, 0.49999993]) + +Due to the Bayesian framework, the weights found are slightly different from the +ones found by :ref:`ordinary_least_squares`. However, Bayesian Ridge Regression +is more robust to ill-posed problems. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_bayesian_ridge_curvefit.py` + +.. dropdown:: References + + * Section 3.3 in Christopher M. Bishop: Pattern Recognition and Machine Learning, 2006 + + * David J. C. MacKay, `Bayesian Interpolation `_, 1992. + + * Michael E. Tipping, `Sparse Bayesian Learning and the Relevance Vector Machine `_, 2001. + +.. _automatic_relevance_determination: + +Automatic Relevance Determination - ARD +--------------------------------------- + +The Automatic Relevance Determination (as being implemented in +:class:`ARDRegression`) is a kind of linear model which is very similar to the +`Bayesian Ridge Regression`_, but that leads to sparser coefficients :math:`w` +[1]_ [2]_. + +:class:`ARDRegression` poses a different prior over :math:`w`: it drops +the spherical Gaussian distribution for a centered elliptic Gaussian +distribution. This means each coefficient :math:`w_{i}` can itself be drawn from +a Gaussian distribution, centered on zero and with a precision +:math:`\lambda_{i}`: + +.. math:: p(w|\lambda) = \mathcal{N}(w|0,A^{-1}) + +with :math:`A` being a positive definite diagonal matrix and +:math:`\text{diag}(A) = \lambda = \{\lambda_{1},...,\lambda_{p}\}`. + +In contrast to the `Bayesian Ridge Regression`_, each coordinate of +:math:`w_{i}` has its own standard deviation :math:`\frac{1}{\lambda_i}`. The +prior over all :math:`\lambda_i` is chosen to be the same gamma distribution +given by the hyperparameters :math:`\lambda_1` and :math:`\lambda_2`. + +ARD is also known in the literature as *Sparse Bayesian Learning* and *Relevance +Vector Machine* [3]_ [4]_. + +See :ref:`sphx_glr_auto_examples_linear_model_plot_ard.py` for a worked-out comparison between ARD and `Bayesian Ridge Regression`_. + +See :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py` for a comparison between various methods - Lasso, ARD and ElasticNet - on correlated data. + +.. rubric:: References + +.. [1] Christopher M. Bishop: Pattern Recognition and Machine Learning, Chapter 7.2.1 + +.. [2] David Wipf and Srikantan Nagarajan: `A New View of Automatic Relevance Determination `_ + +.. [3] Michael E. Tipping: `Sparse Bayesian Learning and the Relevance Vector Machine `_ + +.. [4] Tristan Fletcher: `Relevance Vector Machines Explained `_ + +.. _Logistic_regression: + +Logistic regression +=================== + +The logistic regression is implemented in :class:`LogisticRegression`. Despite +its name, it is implemented as a linear model for classification rather than +regression in terms of the scikit-learn/ML nomenclature. The logistic +regression is also known in the literature as logit regression, +maximum-entropy classification (MaxEnt) or the log-linear classifier. In this +model, the probabilities describing the possible outcomes of a single trial +are modeled using a `logistic function +`_. + +This implementation can fit binary, One-vs-Rest, or multinomial logistic +regression with optional :math:`\ell_1`, :math:`\ell_2` or Elastic-Net +regularization. + +.. note:: **Regularization** + + Regularization is applied by default, which is common in machine + learning but not in statistics. Another advantage of regularization is + that it improves numerical stability. No regularization amounts to + setting C to a very high value. + +.. note:: **Logistic Regression as a special case of the Generalized Linear Models (GLM)** + + Logistic regression is a special case of + :ref:`generalized_linear_models` with a Binomial / Bernoulli conditional + distribution and a Logit link. The numerical output of the logistic + regression, which is the predicted probability, can be used as a classifier + by applying a threshold (by default 0.5) to it. This is how it is + implemented in scikit-learn, so it expects a categorical target, making + the Logistic Regression a classifier. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_logistic_l1_l2_sparsity.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_logistic_path.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_logistic_multinomial.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_sparse_logistic_regression_20newsgroups.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_sparse_logistic_regression_mnist.py` +* :ref:`sphx_glr_auto_examples_classification_plot_classification_probability.py` + +Binary Case +----------- + +For notational ease, we assume that the target :math:`y_i` takes values in the +set :math:`\{0, 1\}` for data point :math:`i`. +Once fitted, the :meth:`~sklearn.linear_model.LogisticRegression.predict_proba` +method of :class:`~sklearn.linear_model.LogisticRegression` predicts +the probability of the positive class :math:`P(y_i=1|X_i)` as + +.. math:: \hat{p}(X_i) = \operatorname{expit}(X_i w + w_0) = \frac{1}{1 + \exp(-X_i w - w_0)}. + + +As an optimization problem, binary +class logistic regression with regularization term :math:`r(w)` minimizes the +following cost function: + +.. math:: + :name: regularized-logistic-loss + + \min_{w} \frac{1}{S}\sum_{i=1}^n s_i + \left(-y_i \log(\hat{p}(X_i)) - (1 - y_i) \log(1 - \hat{p}(X_i))\right) + + \frac{r(w)}{S C}\,, + +where :math:`{s_i}` corresponds to the weights assigned by the user to a +specific training sample (the vector :math:`s` is formed by element-wise +multiplication of the class weights and sample weights), +and the sum :math:`S = \sum_{i=1}^n s_i`. + +We currently provide four choices for the regularization or penalty term :math:`r(w)` +via the arguments `C` and `l1_ratio`: + ++-------------------------------+-------------------------------------------------+ +| penalty | :math:`r(w)` | ++===============================+=================================================+ +| none (`C=np.inf`) | :math:`0` | ++-------------------------------+-------------------------------------------------+ +| :math:`\ell_1` (`l1_ratio=1`) | :math:`\|w\|_1` | ++-------------------------------+-------------------------------------------------+ +| :math:`\ell_2` (`l1_ratio=0`) | :math:`\frac{1}{2}\|w\|_2^2 = \frac{1}{2}w^T w` | ++-------------------------------+-------------------------------------------------+ +| ElasticNet (`00` is equivalent to multiplying the (inverse) regularization +strength `C` by :math:`b`. + +Multinomial Case +---------------- + +The binary case can be extended to :math:`K` classes leading to the multinomial +logistic regression, see also `log-linear model +`_. + +.. note:: + It is possible to parameterize a :math:`K`-class classification model + using only :math:`K-1` weight vectors, leaving one class probability fully + determined by the other class probabilities by leveraging the fact that all + class probabilities must sum to one. We deliberately choose to overparameterize the model + using :math:`K` weight vectors for ease of implementation and to preserve the + symmetrical inductive bias regarding ordering of classes, see [16]_. This effect becomes + especially important when using regularization. The choice of overparameterization can be + detrimental for unpenalized models since then the solution may not be unique, as shown in [16]_. + +.. dropdown:: Mathematical details + + Let :math:`y_i \in \{1, \ldots, K\}` be the label (ordinal) encoded target variable for observation :math:`i`. + Instead of a single coefficient vector, we now have + a matrix of coefficients :math:`W` where each row vector :math:`W_k` corresponds to class + :math:`k`. We aim at predicting the class probabilities :math:`P(y_i=k|X_i)` via + :meth:`~sklearn.linear_model.LogisticRegression.predict_proba` as: + + .. math:: \hat{p}_k(X_i) = \frac{\exp(X_i W_k + W_{0, k})}{\sum_{l=0}^{K-1} \exp(X_i W_l + W_{0, l})}. + + The objective for the optimization becomes + + .. math:: + \min_W -\frac{1}{S}\sum_{i=1}^n \sum_{k=0}^{K-1} s_{ik} [y_i = k] \log(\hat{p}_k(X_i)) + + \frac{r(W)}{S C}\,, + + where :math:`[P]` represents the Iverson bracket which evaluates to :math:`0` + if :math:`P` is false, otherwise it evaluates to :math:`1`. + + Again, :math:`s_{ik}` are the weights assigned by the user (multiplication of sample + weights and class weights) with their sum :math:`S = \sum_{i=1}^n \sum_{k=0}^{K-1} s_{ik}`. + + We currently provide four choices for the regularization or penalty term :math:`r(W)` + via the arguments `C` and `l1_ratio`, where :math:`m` is the number of features: + + +-------------------------------+----------------------------------------------------------------------------------+ + | penalty | :math:`r(W)` | + +===============================+==================================================================================+ + | none (`C=np.inf`) | :math:`0` | + +-------------------------------+----------------------------------------------------------------------------------+ + | :math:`\ell_1` (`l1_ratio=1`) | :math:`\|W\|_{1,1} = \sum_{i=1}^m\sum_{j=1}^{K}|W_{i,j}|` | + +-------------------------------+----------------------------------------------------------------------------------+ + | :math:`\ell_2` (`l1_ratio=0`) | :math:`\frac{1}{2}\|W\|_F^2 = \frac{1}{2}\sum_{i=1}^m\sum_{j=1}^{K} W_{i,j}^2` | + +-------------------------------+----------------------------------------------------------------------------------+ + | ElasticNet (`0> n_features`, "newton-cholesky" is a good choice and can reach high +precision (tiny `tol` values). For large datasets +the "saga" solver is usually faster (than "lbfgs"), in particular for low precision +(high `tol`). +For large dataset, you may also consider using :class:`SGDClassifier` +with `loss="log_loss"`, which might be even faster but requires more tuning. + +.. dropdown:: References + + The following references explain some of the solvers. + + * For "lbfgs", see documentation of + :func:`SciPy minimize ` + + * "liblinear" + + * Fan, R. E., Chang, K. W., Hsieh, C. J., Wang, X. R., & Lin, C. J. (2008). + LIBLINEAR: A library for large linear classification. + the Journal of machine Learning research, 9, 1871-1874. + https://www.jmlr.org/papers/volume9/fan08a/fan08a.pdf + + * :doi:`Yu, H. F., Huang, F. L., & Lin, C. J. (2011). + Dual coordinate descent methods for logistic regression and maximum entropy + models. Machine Learning, 85(1), 41-75. + <10.1007/s10994-010-5221-8>` + + * SAG -- :arxiv:`Schmidt, M., Le Roux, N., & Bach, F. (2017). + Minimizing finite sums with the stochastic average gradient. + Mathematical Programming, 162(1), 83-112. + <1309.2388>` + + * SAGA -- :arxiv:`Defazio, A., Bach, F., & Lacoste-Julien, S. (2014). + SAGA: A fast incremental gradient method with support for non-strongly convex + composite objectives. Advances in neural information processing systems, 27. + <1407.0202>` + +.. _liblinear_differences: + +Differences between solvers +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There might be a difference in the scores obtained between +:class:`LogisticRegression` with ``solver=liblinear`` or +:class:`~sklearn.svm.LinearSVC` and the external liblinear library directly, +when ``fit_intercept=False`` and the fit ``coef_`` (or) the data to be predicted +are zeroes. This is because for the sample(s) with ``decision_function`` zero, +:class:`LogisticRegression` and :class:`~sklearn.svm.LinearSVC` predict the +negative class, while liblinear predicts the positive class. Note that a model +with ``fit_intercept=False`` and having many samples with ``decision_function`` +zero, is likely to be an underfit, bad model and you are advised to set +``fit_intercept=True`` and increase the ``intercept_scaling``. + +.. dropdown:: Solvers' details + + * The solver "liblinear" uses a coordinate descent (CD) algorithm, and relies + on the excellent C++ `LIBLINEAR library + `_, which is shipped with + scikit-learn. However, the CD algorithm implemented in liblinear cannot learn a + true multinomial (multiclass) model. If you still want to use "liblinear" on + multiclass problems, you can use a "one-vs-rest" scheme + `OneVsRestClassifier(LogisticRegression(solver="liblinear"))`, see + `:class:`~sklearn.multiclass.OneVsRestClassifier`. Note that minimizing the + multinomial loss is expected to give better calibrated results as compared to + a "one-vs-rest" scheme. + For :math:`\ell_1` regularization :func:`sklearn.svm.l1_min_c` allows to + calculate the lower bound for C in order to get a non "null" (all feature + weights to zero) model. + + * The "lbfgs", "newton-cg", "newton-cholesky" and "sag" solvers only support + :math:`\ell_2` regularization or no regularization, and are found to converge + faster for some high-dimensional data. These solvers (and "saga") + learn a true multinomial logistic regression model [5]_. + + * The "sag" solver uses Stochastic Average Gradient descent [6]_. It is faster + than other solvers for large datasets, when both the number of samples and the + number of features are large. + + * The "saga" solver [7]_ is a variant of "sag" that also supports the non-smooth + :math:`\ell_1` penalty (`l1_ratio=1`). This is therefore the solver of choice for + sparse multinomial logistic regression. It is also the only solver that supports + Elastic-Net (`0 < l1_ratio < 1`). + + * The "lbfgs" is an optimization algorithm that approximates the + Broyden–Fletcher–Goldfarb–Shanno algorithm [8]_, which belongs to + quasi-Newton methods. As such, it can deal with a wide range of different training + data and is therefore the default solver. Its performance, however, suffers on poorly + scaled datasets and on datasets with one-hot encoded categorical features with rare + categories. + + * The "newton-cholesky" solver is an exact Newton solver that calculates the Hessian + matrix and solves the resulting linear system. It is a very good choice for + `n_samples` >> `n_features` and can reach high precision (tiny values of `tol`), + but has a few shortcomings: Only :math:`\ell_2` regularization is supported. + Furthermore, because the Hessian matrix is explicitly computed, the memory usage + has a quadratic dependency on `n_features` as well as on `n_classes`. + + For a comparison of some of these solvers, see [9]_. + + .. rubric:: References + + .. [5] Christopher M. Bishop: Pattern Recognition and Machine Learning, Chapter 4.3.4 + + .. [6] Mark Schmidt, Nicolas Le Roux, and Francis Bach: `Minimizing Finite Sums with the Stochastic Average Gradient. `_ + + .. [7] Aaron Defazio, Francis Bach, Simon Lacoste-Julien: + :arxiv:`SAGA: A Fast Incremental Gradient Method With Support for + Non-Strongly Convex Composite Objectives. <1407.0202>` + + .. [8] https://en.wikipedia.org/wiki/Broyden%E2%80%93Fletcher%E2%80%93Goldfarb%E2%80%93Shanno_algorithm + + .. [9] Thomas P. Minka `"A comparison of numerical optimizers for logistic regression" + `_ + + .. [16] :arxiv:`Simon, Noah, J. Friedman and T. Hastie. + "A Blockwise Descent Algorithm for Group-penalized Multiresponse and + Multinomial Regression." <1311.6529>` + + +.. note:: **Feature selection with sparse logistic regression** + + A logistic regression with :math:`\ell_1` penalty yields sparse models, and can + thus be used to perform feature selection, as detailed in + :ref:`l1_feature_selection`. + +.. note:: **P-value estimation** + + It is possible to obtain the p-values and confidence intervals for + coefficients in cases of regression without penalization. The `statsmodels + package `_ natively supports this. + Within sklearn, one could use bootstrapping instead as well. + + +:class:`LogisticRegressionCV` implements Logistic Regression with built-in +cross-validation support, to find the optimal `C` and `l1_ratio` parameters +according to the ``scoring`` attribute. The "newton-cg", "sag", "saga" and +"lbfgs" solvers are found to be faster for high-dimensional dense data, due +to warm-starting (see :term:`Glossary `). + +.. _Generalized_linear_regression: + +.. _Generalized_linear_models: + +Generalized Linear Models +========================= + +Generalized Linear Models (GLM) extend linear models in two ways +[10]_. First, the predicted values :math:`\hat{y}` are linked to a linear +combination of the input variables :math:`X` via an inverse link function +:math:`h` as + +.. math:: \hat{y}(w, X) = h(Xw). + +Secondly, the squared loss function is replaced by the unit deviance +:math:`d` of a distribution in the exponential family (or more precisely, a +reproductive exponential dispersion model (EDM) [11]_). + +The minimization problem becomes: + +.. math:: \min_{w} \frac{1}{2 n_{\text{samples}}} \sum_i d(y_i, \hat{y}_i) + \frac{\alpha}{2} ||w||_2^2, + +where :math:`\alpha` is the L2 regularization penalty. When sample weights are +provided, the average becomes a weighted average. + +The following table lists some specific EDMs and their unit deviance : + +================= ================================ ============================================ +Distribution Target Domain Unit Deviance :math:`d(y, \hat{y})` +================= ================================ ============================================ +Normal :math:`y \in (-\infty, \infty)` :math:`(y-\hat{y})^2` +Bernoulli :math:`y \in \{0, 1\}` :math:`2({y}\log\frac{y}{\hat{y}}+({1}-{y})\log\frac{{1}-{y}}{{1}-\hat{y}})` +Categorical :math:`y \in \{0, 1, ..., k\}` :math:`2\sum_{i \in \{0, 1, ..., k\}} I(y = i) y_\text{i}\log\frac{I(y = i)}{\hat{I(y = i)}}` +Poisson :math:`y \in [0, \infty)` :math:`2(y\log\frac{y}{\hat{y}}-y+\hat{y})` +Gamma :math:`y \in (0, \infty)` :math:`2(\log\frac{\hat{y}}{y}+\frac{y}{\hat{y}}-1)` +Inverse Gaussian :math:`y \in (0, \infty)` :math:`\frac{(y-\hat{y})^2}{y\hat{y}^2}` +================= ================================ ============================================ + +The Probability Density Functions (PDF) of these distributions are illustrated +in the following figure, + +.. figure:: ./glm_data/poisson_gamma_tweedie_distributions.png + :align: center + :scale: 100% + + PDF of a random variable Y following Poisson, Tweedie (power=1.5) and Gamma + distributions with different mean values (:math:`\mu`). Observe the point + mass at :math:`Y=0` for the Poisson distribution and the Tweedie (power=1.5) + distribution, but not for the Gamma distribution which has a strictly + positive target domain. + +The Bernoulli distribution is a discrete probability distribution modelling a +Bernoulli trial - an event that has only two mutually exclusive outcomes. +The Categorical distribution is a generalization of the Bernoulli distribution +for a categorical random variable. While a random variable in a Bernoulli +distribution has two possible outcomes, a Categorical random variable can take +on one of K possible categories, with the probability of each category +specified separately. + +The choice of the distribution depends on the problem at hand: + +* If the target values :math:`y` are counts (non-negative integer valued) or + relative frequencies (non-negative), you might use a Poisson distribution + with a log-link. +* If the target values are positive valued and skewed, you might try a Gamma + distribution with a log-link. +* If the target values seem to be heavier tailed than a Gamma distribution, you + might try an Inverse Gaussian distribution (or even higher variance powers of + the Tweedie family). +* If the target values :math:`y` are probabilities, you can use the Bernoulli + distribution. The Bernoulli distribution with a logit link can be used for + binary classification. The Categorical distribution with a softmax link can be + used for multiclass classification. + + +.. dropdown:: Examples of use cases + + * Agriculture / weather modeling: number of rain events per year (Poisson), + amount of rainfall per event (Gamma), total rainfall per year (Tweedie / + Compound Poisson Gamma). + * Risk modeling / insurance policy pricing: number of claim events / + policyholder per year (Poisson), cost per event (Gamma), total cost per + policyholder per year (Tweedie / Compound Poisson Gamma). + * Credit Default: probability that a loan can't be paid back (Bernoulli). + * Fraud Detection: probability that a financial transaction like a cash transfer + is a fraudulent transaction (Bernoulli). + * Predictive maintenance: number of production interruption events per year + (Poisson), duration of interruption (Gamma), total interruption time per year + (Tweedie / Compound Poisson Gamma). + * Medical Drug Testing: probability of curing a patient in a set of trials or + probability that a patient will experience side effects (Bernoulli). + * News Classification: classification of news articles into three categories + namely Business News, Politics and Entertainment news (Categorical). + +.. rubric:: References + +.. [10] McCullagh, Peter; Nelder, John (1989). Generalized Linear Models, + Second Edition. Boca Raton: Chapman and Hall/CRC. ISBN 0-412-31760-5. + +.. [11] Jørgensen, B. (1992). The theory of exponential dispersion models + and analysis of deviance. Monografias de matemática, no. 51. See also + `Exponential dispersion model. + `_ + +Usage +----- + +:class:`TweedieRegressor` implements a generalized linear model for the +Tweedie distribution, that allows to model any of the above mentioned +distributions using the appropriate ``power`` parameter. In particular: + +- ``power = 0``: Normal distribution. Specific estimators such as + :class:`Ridge`, :class:`ElasticNet` are generally more appropriate in + this case. +- ``power = 1``: Poisson distribution. :class:`PoissonRegressor` is exposed + for convenience. However, it is strictly equivalent to + `TweedieRegressor(power=1, link='log')`. +- ``power = 2``: Gamma distribution. :class:`GammaRegressor` is exposed for + convenience. However, it is strictly equivalent to + `TweedieRegressor(power=2, link='log')`. +- ``power = 3``: Inverse Gaussian distribution. + +The link function is determined by the `link` parameter. + +Usage example:: + + >>> from sklearn.linear_model import TweedieRegressor + >>> reg = TweedieRegressor(power=1, alpha=0.5, link='log') + >>> reg.fit([[0, 0], [0, 1], [2, 2]], [0, 1, 2]) + TweedieRegressor(alpha=0.5, link='log', power=1) + >>> reg.coef_ + array([0.2463, 0.4337]) + >>> reg.intercept_ + np.float64(-0.7638) + + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_poisson_regression_non_normal_loss.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_tweedie_regression_insurance_claims.py` + +.. dropdown:: Practical considerations + + The feature matrix `X` should be standardized before fitting. This ensures + that the penalty treats features equally. + + Since the linear predictor :math:`Xw` can be negative and Poisson, + Gamma and Inverse Gaussian distributions don't support negative values, it + is necessary to apply an inverse link function that guarantees the + non-negativeness. For example with `link='log'`, the inverse link function + becomes :math:`h(Xw)=\exp(Xw)`. + + If you want to model a relative frequency, i.e. counts per exposure (time, + volume, ...) you can do so by using a Poisson distribution and passing + :math:`y=\frac{\mathrm{counts}}{\mathrm{exposure}}` as target values + together with :math:`\mathrm{exposure}` as sample weights. For a concrete + example see e.g. + :ref:`sphx_glr_auto_examples_linear_model_plot_tweedie_regression_insurance_claims.py`. + + When performing cross-validation for the `power` parameter of + `TweedieRegressor`, it is advisable to specify an explicit `scoring` function, + because the default scorer :meth:`TweedieRegressor.score` is a function of + `power` itself. + +Stochastic Gradient Descent - SGD +================================= + +Stochastic gradient descent is a simple yet very efficient approach +to fit linear models. It is particularly useful when the number of samples +(and the number of features) is very large. +The ``partial_fit`` method allows online/out-of-core learning. + +The classes :class:`SGDClassifier` and :class:`SGDRegressor` provide +functionality to fit linear models for classification and regression +using different (convex) loss functions and different penalties. +E.g., with ``loss="log"``, :class:`SGDClassifier` +fits a logistic regression model, +while with ``loss="hinge"`` it fits a linear support vector machine (SVM). + +You can refer to the dedicated :ref:`sgd` documentation section for more details. + +.. _perceptron: + +Perceptron +---------- + +The :class:`Perceptron` is another simple classification algorithm suitable for +large scale learning and derives from SGD. By default: + +- It does not require a learning rate. + +- It is not regularized (penalized). + +- It updates its model only on mistakes. + +The last characteristic implies that the Perceptron is slightly faster to +train than SGD with the hinge loss and that the resulting models are +sparser. + +In fact, the :class:`Perceptron` is a wrapper around the :class:`SGDClassifier` +class using a perceptron loss and a constant learning rate. Refer to +:ref:`mathematical section ` of the SGD procedure +for more details. + +.. _passive_aggressive: + +Passive Aggressive Algorithms +----------------------------- + +The passive-aggressive (PA) algorithms are another family of 2 algorithms (PA-I and +PA-II) for large-scale online learning that derive from SGD. They are similar to the +Perceptron in that they do not require a learning rate. However, contrary to the +Perceptron, they include a regularization parameter ``eta0`` (:math:`C` in the +reference paper). + +For classification, +:class:`SGDClassifier(loss="hinge", penalty=None, learning_rate="pa1", eta0=1.0)` can +be used for PA-I or with ``learning_rate="pa2"`` for PA-II. For regression, +:class:`SGDRegressor(loss="epsilon_insensitive", penalty=None, learning_rate="pa1", +eta0=1.0)` can be used for PA-I or with ``learning_rate="pa2"`` for PA-II. + +.. dropdown:: References + + * `"Online Passive-Aggressive Algorithms" + `_ + K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR 7 (2006) + +Robustness regression: outliers and modeling errors +===================================================== + +Robust regression aims to fit a regression model in the +presence of corrupt data: either outliers, or error in the model. + +.. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_theilsen_001.png + :target: ../auto_examples/linear_model/plot_theilsen.html + :scale: 50% + :align: center + +Different scenario and useful concepts +---------------------------------------- + +There are different things to keep in mind when dealing with data +corrupted by outliers: + +.. |y_outliers| image:: ../auto_examples/linear_model/images/sphx_glr_plot_robust_fit_003.png + :target: ../auto_examples/linear_model/plot_robust_fit.html + :scale: 60% + +.. |X_outliers| image:: ../auto_examples/linear_model/images/sphx_glr_plot_robust_fit_002.png + :target: ../auto_examples/linear_model/plot_robust_fit.html + :scale: 60% + +.. |large_y_outliers| image:: ../auto_examples/linear_model/images/sphx_glr_plot_robust_fit_005.png + :target: ../auto_examples/linear_model/plot_robust_fit.html + :scale: 60% + +* **Outliers in X or in y**? + + ==================================== ==================================== + Outliers in the y direction Outliers in the X direction + ==================================== ==================================== + |y_outliers| |X_outliers| + ==================================== ==================================== + +* **Fraction of outliers versus amplitude of error** + + The number of outlying points matters, but also how much they are + outliers. + + ==================================== ==================================== + Small outliers Large outliers + ==================================== ==================================== + |y_outliers| |large_y_outliers| + ==================================== ==================================== + +An important notion of robust fitting is that of breakdown point: the +fraction of data that can be outlying for the fit to start missing the +inlying data. + +Note that in general, robust fitting in high-dimensional setting (large +`n_features`) is very hard. The robust models here will probably not work +in these settings. + + +.. topic:: Trade-offs: which estimator ? + + Scikit-learn provides 3 robust regression estimators: + :ref:`RANSAC `, + :ref:`Theil Sen ` and + :ref:`HuberRegressor `. + + * :ref:`HuberRegressor ` should be faster than + :ref:`RANSAC ` and :ref:`Theil Sen ` + unless the number of samples is very large, i.e. ``n_samples`` >> ``n_features``. + This is because :ref:`RANSAC ` and :ref:`Theil Sen ` + fit on smaller subsets of the data. However, both :ref:`Theil Sen ` + and :ref:`RANSAC ` are unlikely to be as robust as + :ref:`HuberRegressor ` for the default parameters. + + * :ref:`RANSAC ` is faster than :ref:`Theil Sen ` + and scales much better with the number of samples. + + * :ref:`RANSAC ` will deal better with large + outliers in the y direction (most common situation). + + * :ref:`Theil Sen ` will cope better with + medium-size outliers in the X direction, but this property will + disappear in high-dimensional settings. + + When in doubt, use :ref:`RANSAC `. + +.. _ransac_regression: + +RANSAC: RANdom SAmple Consensus +-------------------------------- + +RANSAC (RANdom SAmple Consensus) fits a model from random subsets of +inliers from the complete data set. + +RANSAC is a non-deterministic algorithm producing only a reasonable result with +a certain probability, which is dependent on the number of iterations (see +`max_trials` parameter). It is typically used for linear and non-linear +regression problems and is especially popular in the field of photogrammetric +computer vision. + +The algorithm splits the complete input sample data into a set of inliers, +which may be subject to noise, and outliers, which are e.g. caused by erroneous +measurements or invalid hypotheses about the data. The resulting model is then +estimated only from the determined inliers. + +.. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_ransac_001.png + :target: ../auto_examples/linear_model/plot_ransac.html + :align: center + :scale: 50% + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_ransac.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_robust_fit.py` + +.. dropdown:: Details of the algorithm + + Each iteration performs the following steps: + + 1. Select ``min_samples`` random samples from the original data and check + whether the set of data is valid (see ``is_data_valid``). + 2. Fit a model to the random subset (``estimator.fit``) and check + whether the estimated model is valid (see ``is_model_valid``). + 3. Classify all data as inliers or outliers by calculating the residuals + to the estimated model (``estimator.predict(X) - y``) - all data + samples with absolute residuals smaller than or equal to the + ``residual_threshold`` are considered as inliers. + 4. Save fitted model as best model if number of inlier samples is + maximal. In case the current estimated model has the same number of + inliers, it is only considered as the best model if it has better score. + + These steps are performed either a maximum number of times (``max_trials``) or + until one of the special stop criteria are met (see ``stop_n_inliers`` and + ``stop_score``). The final model is estimated using all inlier samples (consensus + set) of the previously determined best model. + + The ``is_data_valid`` and ``is_model_valid`` functions allow to identify and reject + degenerate combinations of random sub-samples. If the estimated model is not + needed for identifying degenerate cases, ``is_data_valid`` should be used as it + is called prior to fitting the model and thus leading to better computational + performance. + +.. dropdown:: References + + * https://en.wikipedia.org/wiki/RANSAC + * `"Random Sample Consensus: A Paradigm for Model Fitting with Applications to + Image Analysis and Automated Cartography" + `_ + Martin A. Fischler and Robert C. Bolles - SRI International (1981) + * `"Performance Evaluation of RANSAC Family" + `_ + Sunglok Choi, Taemin Kim and Wonpil Yu - BMVC (2009) + +.. _theil_sen_regression: + +Theil-Sen estimator: generalized-median-based estimator +-------------------------------------------------------- + +The :class:`TheilSenRegressor` estimator uses a generalization of the median in +multiple dimensions. It is thus robust to multivariate outliers. Note however +that the robustness of the estimator decreases quickly with the dimensionality +of the problem. It loses its robustness properties and becomes no +better than an ordinary least squares in high dimension. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_theilsen.py` +* :ref:`sphx_glr_auto_examples_linear_model_plot_robust_fit.py` + + +.. dropdown:: Theoretical considerations + + :class:`TheilSenRegressor` is comparable to the :ref:`Ordinary Least Squares + (OLS) ` in terms of asymptotic efficiency and as an + unbiased estimator. In contrast to OLS, Theil-Sen is a non-parametric + method which means it makes no assumption about the underlying + distribution of the data. Since Theil-Sen is a median-based estimator, it + is more robust against corrupted data aka outliers. In univariate + setting, Theil-Sen has a breakdown point of about 29.3% in case of a + simple linear regression which means that it can tolerate arbitrary + corrupted data of up to 29.3%. + + .. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_theilsen_001.png + :target: ../auto_examples/linear_model/plot_theilsen.html + :align: center + :scale: 50% + + The implementation of :class:`TheilSenRegressor` in scikit-learn follows a + generalization to a multivariate linear regression model [#f1]_ using the + spatial median which is a generalization of the median to multiple + dimensions [#f2]_. + + In terms of time and space complexity, Theil-Sen scales according to + + .. math:: + \binom{n_{\text{samples}}}{n_{\text{subsamples}}} + + which makes it infeasible to be applied exhaustively to problems with a + large number of samples and features. Therefore, the magnitude of a + subpopulation can be chosen to limit the time and space complexity by + considering only a random subset of all possible combinations. + + .. rubric:: References + + .. [#f1] Xin Dang, Hanxiang Peng, Xueqin Wang and Heping Zhang: `Theil-Sen Estimators in a Multiple Linear Regression Model. `_ + + .. [#f2] T. Kärkkäinen and S. Äyrämö: `On Computation of Spatial Median for Robust Data Mining. `_ + + Also see the `Wikipedia page `_ + + +.. _huber_regression: + +Huber Regression +---------------- + +The :class:`HuberRegressor` is different from :class:`Ridge` because it applies a +linear loss to samples that are defined as outliers by the `epsilon` parameter. +A sample is classified as an inlier if the absolute error of that sample is +less than the threshold `epsilon`. It differs from :class:`TheilSenRegressor` +and :class:`RANSACRegressor` because it does not ignore the effect of the outliers +but gives a lesser weight to them. + +.. figure:: /auto_examples/linear_model/images/sphx_glr_plot_huber_vs_ridge_001.png + :target: ../auto_examples/linear_model/plot_huber_vs_ridge.html + :align: center + :scale: 50% + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_huber_vs_ridge.py` + +.. dropdown:: Mathematical details + + :class:`HuberRegressor` minimizes + + .. math:: + + \min_{w, \sigma} {\sum_{i=1}^n\left(\sigma + H_{\epsilon}\left(\frac{X_{i}w - y_{i}}{\sigma}\right)\sigma\right) + \alpha {||w||_2}^2} + + where the loss function is given by + + .. math:: + + H_{\epsilon}(z) = \begin{cases} + z^2, & \text {if } |z| < \epsilon, \\ + 2\epsilon|z| - \epsilon^2, & \text{otherwise} + \end{cases} + + It is advised to set the parameter ``epsilon`` to 1.35 to achieve 95% + statistical efficiency. + + .. rubric:: References + + * Peter J. Huber, Elvezio M. Ronchetti: Robust Statistics, Concomitant scale + estimates, p. 172. + +The :class:`HuberRegressor` differs from using :class:`SGDRegressor` with loss set to `huber` +in the following ways. + +- :class:`HuberRegressor` is scaling invariant. Once ``epsilon`` is set, scaling ``X`` and ``y`` + down or up by different values would produce the same robustness to outliers as before. + as compared to :class:`SGDRegressor` where ``epsilon`` has to be set again when ``X`` and ``y`` are + scaled. + +- :class:`HuberRegressor` should be more efficient to use on data with small number of + samples while :class:`SGDRegressor` needs a number of passes on the training data to + produce the same robustness. + +Note that this estimator is different from the `R implementation of Robust +Regression `_ because the R +implementation does a weighted least squares implementation with weights given to each +sample on the basis of how much the residual is greater than a certain threshold. + +.. _quantile_regression: + +Quantile Regression +=================== + +Quantile regression estimates the median or other quantiles of :math:`y` +conditional on :math:`X`, while ordinary least squares (OLS) estimates the +conditional mean. + +Quantile regression may be useful if one is interested in predicting an +interval instead of point prediction. Sometimes, prediction intervals are +calculated based on the assumption that prediction error is distributed +normally with zero mean and constant variance. Quantile regression provides +sensible prediction intervals even for errors with non-constant (but +predictable) variance or non-normal distribution. + +.. figure:: /auto_examples/linear_model/images/sphx_glr_plot_quantile_regression_002.png + :target: ../auto_examples/linear_model/plot_quantile_regression.html + :align: center + :scale: 50% + +Based on minimizing the pinball loss, conditional quantiles can also be +estimated by models other than linear models. For example, +:class:`~sklearn.ensemble.GradientBoostingRegressor` can predict conditional +quantiles if its parameter ``loss`` is set to ``"quantile"`` and parameter +``alpha`` is set to the quantile that should be predicted. See the example in +:ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_quantile.py`. + +Most implementations of quantile regression are based on linear programming +problem. The current implementation is based on +:func:`scipy.optimize.linprog`. + +.. rubric:: Examples + +* :ref:`sphx_glr_auto_examples_linear_model_plot_quantile_regression.py` + +.. dropdown:: Mathematical details + + As a linear model, the :class:`QuantileRegressor` gives linear predictions + :math:`\hat{y}(w, X) = Xw` for the :math:`q`-th quantile, :math:`q \in (0, 1)`. + The weights or coefficients :math:`w` are then found by the following + minimization problem: + + .. math:: + \min_{w} {\frac{1}{n_{\text{samples}}} + \sum_i PB_q(y_i - X_i w) + \alpha ||w||_1}. + + This consists of the pinball loss (also known as linear loss), + see also :class:`~sklearn.metrics.mean_pinball_loss`, + + .. math:: + PB_q(t) = q \max(t, 0) + (1 - q) \max(-t, 0) = + \begin{cases} + q t, & t > 0, \\ + 0, & t = 0, \\ + (q-1) t, & t < 0 + \end{cases} + + and the L1 penalty controlled by parameter ``alpha``, similar to + :class:`Lasso`. + + As the pinball loss is only linear in the residuals, quantile regression is + much more robust to outliers than squared error based estimation of the mean. + Somewhat in between is the :class:`HuberRegressor`. + +.. dropdown:: References + + * Koenker, R., & Bassett Jr, G. (1978). `Regression quantiles. + `_ + Econometrica: journal of the Econometric Society, 33-50. + + * Portnoy, S., & Koenker, R. (1997). :doi:`The Gaussian hare and the Laplacian + tortoise: computability of squared-error versus absolute-error estimators. + Statistical Science, 12, 279-300 <10.1214/ss/1030037960>`. + + * Koenker, R. (2005). :doi:`Quantile Regression <10.1017/CBO9780511754098>`. + Cambridge University Press. + + +.. _polynomial_regression: + +Polynomial regression: extending linear models with basis functions +=================================================================== + +.. currentmodule:: sklearn.preprocessing + +One common pattern within machine learning is to use linear models trained +on nonlinear functions of the data. This approach maintains the generally +fast performance of linear methods, while allowing them to fit a much wider +range of data. + +.. dropdown:: Mathematical details + + For example, a simple linear regression can be extended by constructing + **polynomial features** from the coefficients. In the standard linear + regression case, you might have a model that looks like this for + two-dimensional data: + + .. math:: \hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2 + + If we want to fit a paraboloid to the data instead of a plane, we can combine + the features in second-order polynomials, so that the model looks like this: + + .. math:: \hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2 + w_3 x_1 x_2 + w_4 x_1^2 + w_5 x_2^2 + + The (sometimes surprising) observation is that this is *still a linear model*: + to see this, imagine creating a new set of features + + .. math:: z = [x_1, x_2, x_1 x_2, x_1^2, x_2^2] + + With this re-labeling of the data, our problem can be written + + .. math:: \hat{y}(w, z) = w_0 + w_1 z_1 + w_2 z_2 + w_3 z_3 + w_4 z_4 + w_5 z_5 + + We see that the resulting *polynomial regression* is in the same class of + linear models we considered above (i.e. the model is linear in :math:`w`) + and can be solved by the same techniques. By considering linear fits within + a higher-dimensional space built with these basis functions, the model has the + flexibility to fit a much broader range of data. + +Here is an example of applying this idea to one-dimensional data, using +polynomial features of varying degrees: + +.. figure:: ../auto_examples/linear_model/images/sphx_glr_plot_polynomial_interpolation_001.png + :target: ../auto_examples/linear_model/plot_polynomial_interpolation.html + :align: center + :scale: 50% + +This figure is created using the :class:`PolynomialFeatures` transformer, which +transforms an input data matrix into a new data matrix of a given degree. +It can be used as follows:: + + >>> from sklearn.preprocessing import PolynomialFeatures + >>> import numpy as np + >>> X = np.arange(6).reshape(3, 2) + >>> X + array([[0, 1], + [2, 3], + [4, 5]]) + >>> poly = PolynomialFeatures(degree=2) + >>> poly.fit_transform(X) + array([[ 1., 0., 1., 0., 0., 1.], + [ 1., 2., 3., 4., 6., 9.], + [ 1., 4., 5., 16., 20., 25.]]) + +The features of ``X`` have been transformed from :math:`[x_1, x_2]` to +:math:`[1, x_1, x_2, x_1^2, x_1 x_2, x_2^2]`, and can now be used within +any linear model. + +This sort of preprocessing can be streamlined with the +:ref:`Pipeline ` tools. A single object representing a simple +polynomial regression can be created and used as follows:: + + >>> from sklearn.preprocessing import PolynomialFeatures + >>> from sklearn.linear_model import LinearRegression + >>> from sklearn.pipeline import Pipeline + >>> import numpy as np + >>> model = Pipeline([('poly', PolynomialFeatures(degree=3)), + ... ('linear', LinearRegression(fit_intercept=False))]) + >>> # fit to an order-3 polynomial data + >>> x = np.arange(5) + >>> y = 3 - 2 * x + x ** 2 - x ** 3 + >>> model = model.fit(x[:, np.newaxis], y) + >>> model.named_steps['linear'].coef_ + array([ 3., -2., 1., -1.]) + +The linear model trained on polynomial features is able to exactly recover +the input polynomial coefficients. + +In some cases it's not necessary to include higher powers of any single feature, +but only the so-called *interaction features* +that multiply together at most :math:`d` distinct features. +These can be gotten from :class:`PolynomialFeatures` with the setting +``interaction_only=True``. + +For example, when dealing with boolean features, +:math:`x_i^n = x_i` for all :math:`n` and is therefore useless; +but :math:`x_i x_j` represents the conjunction of two booleans. +This way, we can solve the XOR problem with a linear classifier:: + + >>> from sklearn.linear_model import Perceptron + >>> from sklearn.preprocessing import PolynomialFeatures + >>> import numpy as np + >>> X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) + >>> y = X[:, 0] ^ X[:, 1] + >>> y + array([0, 1, 1, 0]) + >>> X = PolynomialFeatures(interaction_only=True).fit_transform(X).astype(int) + >>> X + array([[1, 0, 0, 0], + [1, 0, 1, 0], + [1, 1, 0, 0], + [1, 1, 1, 1]]) + >>> clf = Perceptron(fit_intercept=False, max_iter=10, tol=None, + ... shuffle=False).fit(X, y) + +And the classifier "predictions" are perfect:: + + >>> clf.predict(X) + array([0, 1, 1, 0]) + >>> clf.score(X, y) + 1.0 diff --git a/rst/math/lombscargle_bedb55.rst b/rst/math/lombscargle_bedb55.rst new file mode 100644 index 0000000..66880cb --- /dev/null +++ b/rst/math/lombscargle_bedb55.rst @@ -0,0 +1,951 @@ +.. _stats-lombscargle: + +************************* +Lomb-Scargle Periodograms +************************* + +The Lomb-Scargle periodogram (after Lomb [1]_, and Scargle [2]_) is a commonly +used statistical tool designed to detect periodic signals in unevenly spaced +observations. The :class:`~astropy.timeseries.LombScargle` class is a unified +interface to several implementations of the Lomb-Scargle periodogram, including +a fast *O[NlogN]* implementation following the algorithm presented by Press & +Rybicki [3]_ or Ruiz-Antolin & Townsend [12]_. + +Not all of the available implementations are mathematically equivalent: Press & Rybicki [3]_ is the fastest +option but trades accuracy for speed, while Ruiz-Antolin & Townsend [12]_ +achieves significantly higher accuracy at an acceptable cost and is therefore +used by default. + +The code here is adapted from the `astroml`_ package ([4]_, [5]_), the +`gatspy`_ package ([6]_, [7]_) and the `FastTransforms.jl`_ library. For a detailed practical discussion of the +Lomb-Scargle periodogram, with code examples based on ``astropy``, see +*Understanding the Lomb-Scargle Periodogram* [11]_, with associated code at +https://github.com/jakevdp/PracticalLombScargle/. + +.. _gatspy: https://www.astroml.org/gatspy/ +.. _astroml: https://www.astroml.org/ +.. _FastTransforms.jl: https://juliaapproximation.github.io/FastTransforms.jl/stable/ + +Basic Usage +=========== + +.. Note:: + All frequencies in :class:`~astropy.timeseries.LombScargle` are **not** + angular frequencies, but rather frequencies of oscillation (i.e., number of + cycles per unit time). + +The Lomb-Scargle periodogram is designed to detect periodic signals in +unevenly spaced observations. + +Example +------- + +.. EXAMPLE START: Using the Lomb-Scargle Periodogram to Detect Periodic Signals + +To detect periodic signals in unevenly spaced observations, consider the +following data: + +>>> import numpy as np +>>> rand = np.random.default_rng(42) +>>> t = 100 * rand.random(100) +>>> y = np.sin(2 * np.pi * t) + 0.1 * rand.standard_normal(100) + +These are 100 noisy measurements taken at irregular times, with a frequency +of 1 cycle per unit time. + +The Lomb-Scargle periodogram, evaluated at frequencies chosen +automatically based on the input data, can be computed as follows +using the :class:`~astropy.timeseries.LombScargle` class: + +>>> from astropy.timeseries import LombScargle +>>> frequency, power = LombScargle(t, y).autopower() + +Plotting the result with Matplotlib gives: + +>>> import matplotlib.pyplot as plt # doctest: +SKIP +>>> fig, ax = plt.subplots() # doctest: +SKIP +>>> ax.plot(frequency, power) # doctest: +SKIP + +.. plot:: + + from astropy.timeseries import LombScargle + + import numpy as np + import matplotlib.pyplot as plt + + rand = np.random.default_rng(42) + t = 100 * rand.random(100) + y = np.sin(2 * np.pi * t) + 0.1 * rand.standard_normal(100) + + frequency, power = LombScargle(t, y).autopower() + fig, ax = plt.subplots(figsize=(6, 4.5)) + ax.plot(frequency, power) + +The periodogram shows a clear spike at a frequency of 1 cycle per unit time, +as we would expect from the data we constructed. + +.. EXAMPLE END + +Measurement Uncertainties +------------------------- + +The :class:`~astropy.timeseries.LombScargle` interface can also handle data with +measurement uncertainties. + +Example +^^^^^^^ + +.. EXAMPLE START: Using the Lomb-Scargle Periodogram with Measurement Uncertainties + +If all uncertainties are the same, you can pass a scalar: + +>>> dy = 0.1 +>>> frequency, power = LombScargle(t, y, dy).autopower() + +If uncertainties vary from observation to observation, you can pass them as +an array: + +>>> dy = 0.1 * (1 + rand.random(100)) +>>> y = np.sin(2 * np.pi * t) + dy * rand.standard_normal(100) +>>> frequency, power = LombScargle(t, y, dy).autopower() + +Gaussian uncertainties are assumed, and ``dy`` here specifies the standard +deviation (not the variance). + +.. EXAMPLE END + +Periodograms and Units +---------------------- + +The :class:`~astropy.timeseries.LombScargle` interface properly handles +:class:`~astropy.units.Quantity` objects with units attached, +and will validate the inputs to make sure units are appropriate. + +Example +^^^^^^^ + +.. EXAMPLE START: Using the LombScargle Class with Quantity Objects + +To use the :class:`~astropy.timeseries.LombScargle` for +:class:`~astropy.units.Quantity` objects with units attached: + +>>> import astropy.units as u +>>> t_days = t * u.day +>>> y_mags = y * u.mag +>>> dy_mags = y * u.mag +>>> frequency, power = LombScargle(t_days, y_mags, dy_mags).autopower() +>>> frequency.unit +Unit("1 / d") +>>> power.unit +Unit(dimensionless) + +We see that the output is dimensionless, which is always the case for the +standard normalized periodogram (for more on normalizations, +see :ref:`lomb-scargle-normalization` below). If you include arguments to +autopower such as ``minimum_frequency`` or ``maximum_frequency``, make sure to +specify units as well: + +>>> frequency, power = LombScargle(t_days, y_mags, dy_mags).autopower(minimum_frequency=1e-5*u.Hz) + +.. EXAMPLE END + +Specifying the Frequency +------------------------ + +With the :func:`~astropy.timeseries.LombScargle.autopower` method used above, a +heuristic is applied to select a suitable frequency grid. By default, the +heuristic assumes that the width of peaks is inversely proportional to the +observation baseline, and that the maximum frequency is a factor of five larger +than the so-called "average Nyquist frequency," with computation based on the +average observation spacing. + +This heuristic is not universally useful, as the frequencies probed by +irregularly sampled data can be much higher than the average Nyquist frequency. +For this reason, the heuristic can be tuned through keywords passed to the +:func:`~astropy.timeseries.LombScargle.autopower` method. + +Example +^^^^^^^ + +.. EXAMPLE START: Specifying the Frequency with the LombScargle.autopower method + +To tune the heuristic using keywords passed to the +:func:`~astropy.timeseries.LombScargle.autopower` method: + +>>> frequency, power = LombScargle(t, y, dy).autopower(nyquist_factor=2) +>>> len(frequency), frequency.min(), frequency.max() # doctest: +FLOAT_CMP +(500, np.float64(0.0010327803641893758), np.float64(1.0317475838251864)) + +Here the highest frequency is two times the average Nyquist frequency. +If we increase the ``nyquist_factor``, we can probe higher frequencies: + +>>> frequency, power = LombScargle(t, y, dy).autopower(nyquist_factor=10) +>>> len(frequency), frequency.min(), frequency.max() # doctest: +FLOAT_CMP +(2500, np.float64(0.0010327803641893758), np.float64(5.16286904058269)) + +Alternatively, we can use the :func:`~astropy.timeseries.LombScargle.power` +method to evaluate the periodogram at a user-specified set of frequencies: + +>>> frequency = np.linspace(0.5, 1.5, 1000) +>>> power = LombScargle(t, y, dy).power(frequency) + +Note that the fastest Lomb-Scargle implementation requires regularly spaced +frequencies; if frequencies are irregularly spaced, a slower method will be +used instead. + +.. EXAMPLE END + +Frequency Grid Spacing +^^^^^^^^^^^^^^^^^^^^^^ + +One common issue with user-specified frequencies is inadvertently choosing +too coarse a grid, such that significant peaks lie between grid points and +are missed entirely. + +Example +""""""" + +.. EXAMPLE START: Frequency Grid Spacing in Periodograms + +Imagine you chose to evaluate your periodogram at 100 points: + +>>> frequency = np.linspace(0.1, 1.9, 100) +>>> power = LombScargle(t, y, dy).power(frequency) +>>> fig, ax = plt.subplots() # doctest: +SKIP +>>> ax.plot(frequency, power) # doctest: +SKIP + +.. plot:: + + import numpy as np + import matplotlib.pyplot as plt + from astropy.timeseries import LombScargle + + rand = np.random.default_rng(42) + t = 100 * rand.random(100) + dy = 0.1 + y = np.sin(2 * np.pi * t) + dy * rand.standard_normal(100) + + frequency = np.linspace(0.1, 1.9, 100) + power = LombScargle(t, y, dy).power(frequency) + + fig, ax = plt.subplots(figsize=(6, 4.5)) + ax.plot(frequency, power) + ax.set(xlabel='frequency', ylabel='Lomb-Scargle Power', ylim=(0, 1)) + +From this plot alone, you might conclude that no clear periodic signal exists in +the data. But this conclusion is in error: there is in fact a strong periodic +signal, but the periodogram peak falls in the gap between the chosen grid +points! + +A more reliable approach is to use the frequency heuristic to decide on the +appropriate grid spacing, optionally passing a minimum and maximum frequency to +the :func:`~astropy.timeseries.LombScargle.autopower` method: + +>>> frequency, power = LombScargle(t, y, dy).autopower(minimum_frequency=0.1, +... maximum_frequency=1.9) +>>> len(frequency) +872 +>>> fig, ax = plt.subplots() # doctest: +SKIP +>>> ax.plot(frequency, power) # doctest: +SKIP + +.. plot:: + + import numpy as np + import matplotlib.pyplot as plt + from astropy.timeseries import LombScargle + + rand = np.random.default_rng(42) + t = 100 * rand.random(100) + dy = 0.1 + y = np.sin(2 * np.pi * t) + dy * rand.standard_normal(100) + + frequency, power = LombScargle(t, y, dy).autopower(minimum_frequency=0.1, + maximum_frequency=1.9) + + fig, ax = plt.subplots(figsize=(6, 4.5)) + ax.plot(frequency, power) + ax.set(xlabel='frequency', ylabel='Lomb-Scargle Power', ylim=(0, 1)) + +With a finer grid (here 884 points between 0.1 and 1.9), +it is clear that there is a very strong periodic signal in the data. + +.. EXAMPLE END + +By default, the heuristic aims to have roughly five grid points across each +significant periodogram peak; this can be increased by changing the +``samples_per_peak`` argument: + +>>> frequency, power = LombScargle(t, y, dy).autopower(minimum_frequency=0.1, +... maximum_frequency=1.9, +... samples_per_peak=10) +>>> len(frequency) +1744 + +Keep in mind that the width of the peak scales inversely with the baseline of +the observations (i.e., the difference between the maximum and minimum time), +and the required number of grid points will scale linearly with the size of +the baseline. + +The Lomb-Scargle Model +---------------------- + +The Lomb-Scargle periodogram fits a sinusoidal model to the data at each +frequency, with a larger power reflecting a better fit. With this in mind, it is +often helpful to plot the best-fit sinusoid over the phased data. + +Example +^^^^^^^ + +.. EXAMPLE START: Computing a Best-Fit Sinusoid Using the LombScargle Class + +This best-fit sinusoid can be computed using the +:func:`~astropy.timeseries.LombScargle.model` method of the +:class:`~astropy.timeseries.LombScargle` object: + +>>> best_frequency = frequency[np.argmax(power)] +>>> t_fit = np.linspace(0, 1) +>>> ls = LombScargle(t, y, dy) +>>> y_fit = ls.model(t_fit, best_frequency) + +We can then phase the data and plot the Lomb-Scargle model fit: + +.. plot:: + + import numpy as np + import matplotlib.pyplot as plt + + from astropy.timeseries import LombScargle + + rand = np.random.default_rng(42) + t = 100 * rand.random(100) + dy = 0.1 + y = np.sin(2 * np.pi * t) + dy * rand.standard_normal(100) + + frequency, power = LombScargle(t, y, dy).autopower(minimum_frequency=0.1, + maximum_frequency=1.9) + best_frequency = frequency[np.argmax(power)] + phase_fit = np.linspace(0, 1) + y_fit = LombScargle(t, y, dy).model(t=phase_fit / best_frequency, + frequency=best_frequency) + phase = (t * best_frequency) % 1 + + fig, ax = plt.subplots(figsize=(6, 4.5)) + ax.errorbar(phase, y, dy, fmt='o', mew=0, capsize=0, elinewidth=1.5) + ax.plot(phase_fit, y_fit, color='black') + ax.invert_yaxis() + ax.set(xlabel='phase', + ylabel='magnitude', + title=f'phased data at frequency={best_frequency:.2f}') + +The best-fit model parameters can be computed with the +:func:`~astropy.timeseries.LombScargle.model_parameters` method of the +:class:`~astropy.timeseries.LombScargle` object at a given frequency: + +>>> theta = ls.model_parameters(best_frequency) +>>> theta.round(2) +array([-0.01, 0.99, 0.11]) + +These parameters :math:`\vec{\theta}` are fit using the following model: + +.. math:: + + y(t; f, \vec{\theta}) = \theta_0 + \sum_{n=1}^{\tt nterms} [\theta_{2n-1}\sin(2\pi n f t) + \theta_{2n}\cos(2\pi n f t)] + +The model can be constructed from these parameters by computing the associated +:func:`~astropy.timeseries.LombScargle.offset`, which accounts for the +pre-centering of data (i.e., the ``center_data`` argument), and +:func:`~astropy.timeseries.LombScargle.design_matrix`, which computes the sine +and cosine terms for you: + +>>> offset = ls.offset() +>>> design_matrix = ls.design_matrix(best_frequency, t_fit) +>>> np.allclose(y_fit, offset + design_matrix.dot(theta)) +True + +.. EXAMPLE END + +Additional Arguments +-------------------- + +On initialization, :class:`~astropy.timeseries.LombScargle` takes a few +additional arguments which control the model for the data: + +- ``center_data`` (``True`` by default) controls whether the ``y`` values are + pre-centered before the algorithm fits the data. The only time it is really + warranted to change the default is if you are computing the periodogram of a + sequence of constant values to, for example, estimate the window power + spectrum for a series of observations. +- ``fit_mean`` (``True`` by default) controls whether the model fits for the + mean of the data, rather than assuming the mean is zero. When + ``fit_mean=True``, the periodogram is more robust than the original + Lomb-Scargle formalism, particularly in the case of smaller sample sizes + and/or data with nontrivial selection bias. In the literature, this model has + variously been called the *date-compensated discrete Fourier transform*, the + *floating-mean periodogram*, the *generalized Lomb-Scargle method*, and likely + other names as well. +- ``nterms`` (``1`` by default) controls how many Fourier terms are used in the + model. As seen above, the standard Lomb-Scargle periodogram is equivalent to + a single-term sinusoidal fit to the data at each frequency; the + generalization is to expand this to a truncated Fourier series with multiple + frequencies. While this can be very useful in some cases, in others the + additional model complexity can lead to spurious periodogram peaks that + outweigh the benefit of the more flexible model. + +.. _lomb-scargle-normalization: + +Periodogram Normalizations +========================== + +There are several normalizations of the Lomb-Scargle periodogram found in the +literature. :class:`~astropy.timeseries.LombScargle` makes four options +available via the ``normalization`` argument: ``normalization='standard'`` (the +default), ``normalization='model'``, ``normalization='log'``, and +``normalization='psd'``. These normalizations can be thought of in terms of +least-squares fits around a constant reference model :math:`M_{ref}` and a +periodic model :math:`M(f)` at each frequency, with best-fit sum of residuals +that we will denote by :math:`\chi^2_{ref}` and :math:`\chi^2(f)` respectively. + +Standard Normalization +---------------------- + +The default, the standard normalized periodogram is normalized by the residuals +of the data around the constant reference model: + +.. math:: + + P_{standard}(f) = \frac{\chi^2_{ref} - \chi^2(f)}{\chi^2_{ref}} + +This form of the normalization (``normalization='standard'``) is the default +choice used in :class:`~astropy.timeseries.LombScargle`. The resulting power +*P* is a dimensionless quantity that lies in the range *0 ≤ P ≤ 1*. + +Model Normalization +------------------- + +Alternatively, the periodogram is sometimes normalized instead by the residuals +around the periodic model: + +.. math:: + + P_{model}(f) = \frac{\chi^2_{ref} - \chi^2(f)}{\chi^2(f)} + +This form of the normalization can be specified with ``normalization='model'``. +As above, the resulting power is a dimensionless quantity that lies in the +range *0 ≤ P ≤ ∞*. + +Logarithmic Normalization +------------------------- + +Another form of normalization is to scale the periodogram logarithmically: + +.. math:: + + P_{log}(f) = \log \frac{\chi^2_{ref}}{\chi^2(f)} + +This normalization can be specified with ``normalization='log'``, and the +resulting power is a dimensionless quantity in the range *0 ≤ P ≤ ∞*. + +PSD Normalization (Unnormalized) +-------------------------------- + +Finally, it is sometimes useful to compute an unnormalized periodogram +(``normalization='psd'``): + +.. math:: + + P_{psd}(f) = \frac{1}{2}\left(\chi^2_{ref} - \chi^2(f)\right) + +Which, in the case of no-uncertainty, will have units ``y.unit ** 2``. +This normalization is constructed to be comparable to the standard Fourier +power spectral density (PSD): + +>>> ls = LombScargle(t_days, y_mags, normalization='psd') +>>> frequency, power = ls.autopower() +>>> power.unit +Unit("mag2") + +Note, however, that the ``normalization='psd'`` result only has these units +*if uncertainties are not specified*. In the presence of uncertainties, +even the unnormalized PSD periodogram will be dimensionless; this is due to +the scaling of data by uncertainty within the Lomb-Scargle computation: + +>>> # with uncertainties, PSD power is unitless +>>> ls = LombScargle(t_days, y_mags, dy_mags, normalization='psd') +>>> frequency, power = ls.autopower() +>>> power.unit +Unit(dimensionless) + +The equivalence of the PSD-normalized periodogram and the Fourier PSD +in the unnormalized, no-uncertainty case can be confirmed by comparing +results directly for uniformly sampled inputs. + +We will first define a convenience function to compute the basic +Fourier periodogram for uniformly sampled quantities: + +>>> def fourier_periodogram(t, y): +... N = len(t) +... frequency = np.fft.fftfreq(N, t[1] - t[0]) +... y_fft = np.fft.fft(y.value) * y.unit +... positive = (frequency > 0) +... return frequency[positive], (1. / N) * abs(y_fft[positive]) ** 2 + +Next we compute the two versions of the PSD from uniformly sampled data: + +>>> t_days = np.arange(100) * u.day +>>> y_mags = rand.standard_normal(100) * u.mag +>>> frequency, PSD_fourier = fourier_periodogram(t_days, y_mags) +>>> ls = LombScargle(t_days, y_mags, normalization='psd') +>>> PSD_LS = ls.power(frequency) + +Examining the results, we see that the two outputs match: + +>>> u.allclose(PSD_fourier, PSD_LS) +True + +This equivalence is one reason that the Lomb-Scargle periodogram is considered +to be an extension of the Fourier PSD. + +For more information on the statistical properties of these normalizations, +see, for example, Baluev 2008 [8]_. + +Peak Significance and False Alarm Probabilities +=============================================== + +.. Note:: + Interpretation of Lomb-Scargle peak significance via false alarm + probabilities is a subtle subject, and the quantities computed below are + commonly misinterpreted or misused. For a detailed discussion of periodogram + peak significance, see [11]_. + +When using the Lomb-Scargle periodogram to decide whether a signal contains a +periodic component, an important consideration is the significance of the +periodogram peak. This significance is usually expressed in terms of a +false alarm probability, which encodes the probability of measuring a +peak of a given height (or higher) conditioned on the assumption that +the data consists of Gaussian noise with no periodic component. + +Example +------- + +.. EXAMPLE START: Lomb-Scargle Peak Significance via False Alarm Probabilities + +To use the Lomb-Scargle periodogram to decide if our signal contains a periodic +component, we can start by simulating 60 observations of a sine wave with noise: + +>>> t = 100 * rand.random(60) +>>> dy = 1.0 +>>> y = np.sin(2 * np.pi * t) + dy * rand.standard_normal(60) +>>> ls = LombScargle(t, y, dy) +>>> freq, power = ls.autopower() +>>> print(power.max()) # doctest: +FLOAT_CMP +0.28800558204470955 + +The peak of the periodogram has a value of 0.288, but how significant is +this peak? We can address this question using the +:func:`~astropy.timeseries.LombScargle.false_alarm_probability` method: + +.. doctest-requires:: scipy + + >>> ls.false_alarm_probability(power.max()) # doctest: +FLOAT_CMP + np.float64(0.03302491900289183) + +What this tells us is that under the assumption that there is no periodic +signal in the data, we will observe a peak this high or higher approximately +0.4% of the time, which gives a strong indication that a periodic signal is +present in the data. + +.. Note:: + Users must interpret this probability carefully: it is a measurement + conditioned on the assumption of the null hypothesis of no signal; in symbols, + you might write :math:`P({\rm data} \mid {\rm noise-only})`. + + Although it may seem like this quantity could be interpreted with a statement + such as "there is an 0.4% chance that this data is noise only," this is *not* + a correct statement; in symbols, this statement describes the quantity + :math:`P({\rm noise-only} \mid {\rm data})`, and in general :math:`P(A\mid B) + \ne P(B\mid A)`. + + See [11]_ for a more detailed discussion of such caveats. + +We might also wish to compute the required peak height to attain any given +false alarm probability, which can be done with the +:func:`~astropy.timeseries.LombScargle.false_alarm_level` method: + +.. doctest-requires:: scipy + + >>> probabilities = [0.1, 0.05, 0.01] + >>> ls.false_alarm_level(probabilities) # doctest: +FLOAT_CMP + array([0.25681381, 0.27663466, 0.31928202]) + +This tells us that to attain a 10% false alarm probability requires the highest +periodogram peak to be approximately 0.25; 5% requires 0.27, and 1% requires +0.32. + +.. EXAMPLE END + +False Alarm Approximations +-------------------------- + +Although the false alarm probability at any particular frequency is analytically +computable, there is no closed-form analytic expression for the more relevant +quantity of the false alarm level of the *highest* peak in a particular +periodogram. This must be either determined through bootstrap simulations, or +approximated by various means. + +``astropy`` provides four options for approximating the false alarm probability, +which can be chosen using the ``method`` keyword: + +- ``method="baluev"`` (the default) implements the approximation proposed by + Baluev 2008 [8]_, which employs extreme value statistics to compute an upper + bound of the false alarm probability for the alias-free case. Experiments show + that the bound is also useful even for highly aliased observing patterns. + +.. doctest-requires:: scipy + + >>> ls.false_alarm_probability(power.max(), method='baluev') # doctest: +FLOAT_CMP + np.float64(0.03302491900289183) + +- ``method="bootstrap"`` implements a bootstrap simulation: effectively it + computes many Lomb-Scargle periodograms on simulated data at the same + observation times. The bootstrap approach can very accurately determine + the false alarm probability, but is very computationally expensive. + To estimate the level corresponding to a false alarm probability + :math:`P_{false}`, it requires on order :math:`n_{boot} \approx 10/P_{false}` + individual periodograms to be computed for the dataset. + +.. doctest-requires:: scipy + + >>> ls.false_alarm_probability(power.max(), method='bootstrap') # doctest: +SKIP + np.float64(0.0030000000000000027) + +- ``method="davies"`` is related to the Baluev method, but loses accuracy + at large false alarm probabilities. + +.. doctest-requires:: scipy + + >>> ls.false_alarm_probability(power.max(), method='davies') # doctest: +FLOAT_CMP + np.float64(0.03358255130320076) + +- ``method="naive"`` is a basic method based on the assumption that + well-separated areas in the periodogram are independent. In general, it + provides a very poor estimate of the false alarm probability and should + not be used in practice, but is included for completeness. + +.. doctest-requires:: scipy + + >>> ls.false_alarm_probability(power.max(), method='naive') # doctest: +FLOAT_CMP + np.float64(0.009331314848518398) + +The following figure compares these false alarm estimates at a range of +peak heights for 100 observations with a heavily aliased observing pattern: + +.. plot:: + + import numpy as np + import matplotlib.pyplot as plt + + from astropy.timeseries import LombScargle + + rng = np.random.default_rng(42) + + N = 100 + t = 5 * rng.random(N) + t -= 0.5 * (t % 1) # create alias-inducing structure in the window function + dy = 0.5 * (1 + rng.random(N)) + y = dy * rng.standard_normal(N) + + ls = LombScargle(t, y, dy, normalization='standard') + z = np.linspace(1E-3, 0.15, 1000) + + def false_alarm(method): + return ls.false_alarm_probability(z, method=method, maximum_frequency=5) + + fa_boot = ls.false_alarm_probability(z, method='bootstrap', + maximum_frequency=5, + method_kwds=dict(random_seed=42)) + + fig, ax = plt.subplots(figsize=(6, 4.5)) + + ax.plot(z, false_alarm('naive'), label='naive estimate') + ax.plot(z, false_alarm('baluev'), label='Baluev estimate') + ax.plot(z, false_alarm('davies'), ':k', label='Davies bound') + ax.plot(z, fa_boot, '-k', label='bootstrap estimate') + + ax.legend(loc='lower left') + ax.set(yscale='log', + title='False Alarm Estimates (N=100)', + xlim=(0, 0.15), ylim=(0.01, 1.5), + xlabel='Value of Highest Periodogram Peak', + ylabel='False Alarm Probability'); + +In general, users should use the bootstrap approach when computationally +feasible, and the Baluev approach otherwise. + +In all of this, it is important to keep in mind a few caveats: + +- False alarm probabilities are computed relative to a particular set of + observing times, and a particular choice of frequency grid. +- False alarm probabilities are conditioned upon the null hypothesis of + data with no periodic component, and in particular say nothing + quantitative about whether the data are actually consistent with a + periodic model. +- False alarm probabilities are not related to the question of whether the + highest peak in a periodogram is the *correct* peak, and in particular + are not especially useful in the case of observations with a strong + aliasing pattern. + +For a detailed discussion of these caveats and others when computing and +interpreting false alarm probabilities, please refer to [11]_. + +Periodogram Algorithms +====================== + +The :class:`~astropy.timeseries.LombScargle` class makes available +several complementary implementations of the Lomb-Scargle periodogram, +which can be selected using the ``method`` keyword of the Lomb-Scargle power. +By design all methods will return the same results (some approximate), +and each has its advantages and disadvantages. + +For example, to compute a periodogram using the Fast Chi-squared method +of Palmer (2009) [9]_, you can specify ``method='fastchi2'``: + + >>> frequency, power = LombScargle(t, y).autopower(method='fastchi2') + +There are currently six methods available in the package: + +``method='auto'`` +----------------- + +The ``auto`` method is the default, and will attempt to select the best option +from the following methods using heuristics driven by the input data. + +``method='slow'`` +----------------- + +The ``slow`` method is a pure Python implementation of the original Lomb-Scargle +periodogram ([1]_, [2]_), enhanced to account for observational noise, +and to allow a floating mean (sometimes called the *generalized periodogram*; +see [10]_). The method is not particularly fast, scaling approximately +as :math:`O[NM]` for :math:`N` data points and :math:`M` frequencies. + +``method='cython'`` +------------------- + +The ``cython`` method is a Cython implementation of the same algorithm used for +``method='slow'``. It is slightly faster than the pure Python implementation, +but much more memory-efficient as the size of the inputs grow. The computational +scaling is approximately :math:`O[NM]` for :math:`N` data points and +:math:`M` frequencies. + +``method='scipy'`` +------------------ + +The ``scipy`` method wraps the C implementation of the original Lomb-Scargle +periodogram which is available in :func:`scipy.signal.lombscargle`. This is +slightly faster than the ``slow`` method, but does not allow for errors in +data or extensions such as the floating mean. The scaling is approximately +:math:`O[NM]` for :math:`N` data points and :math:`M` frequencies. + +``method='fast'`` +----------------- + +The ``fast`` method is a pure Python implementation of the fast periodogram of +Press & Rybicki [3]_ and Ruiz-Antolin & Townsend [12]_. It uses an *extrapolation* approach to approximate the +periodogram frequencies using a fast Fourier transform. As with the ``slow`` +method, it can handle data errors and floating mean. The scaling is +approximately :math:`O[N\log M]` for :math:`N` data points and :math:`M` +frequencies. The fast algorithm trades accuracy for speed, and produces a close +approximation to the true periodogram. In particular, you may observe powers +less than zero in some cases. + +``method='chi2'`` +----------------- + +The ``chi2`` method is a pure Python implementation based on matrix algebra +(see [7]_). It utilizes the fact that the Lomb-Scargle periodogram at +each frequency is equivalent to the least-squares fit of a sinusoid to the +data. The advantage of the ``chi2`` method is that it allows extensions of +the periodogram to multiple Fourier terms, specified by the ``nterms`` +parameter. For the standard problem, it is slightly slower than +``method='slow'`` and scales as :math:`O[n_fNM]` for :math:`N` data points, +:math:`M` frequencies, and :math:`n_f` Fourier terms. + +``method='fastchi2'`` +--------------------- + +The Fast Chi-squared method of Palmer (2009) [9]_ is equivalent to the ``chi2`` +method, but the matrices are constructed using an FFT-based approach similar to +that of the ``fast`` method. The result is a relatively efficient periodogram +(though not nearly as efficient as the ``fast`` method) which can be extended to +multiple terms. The scaling is approximately :math:`O[n_f(M + N\log M)]` for +:math:`N` data points, :math:`M` frequencies, and :math:`n_f` Fourier terms. + +Summary +------- + +The following table summarizes the features of the above algorithms: + +============== ============================ ============= =============== ======== +Method Computational Observational Bias Term Multiple + Scaling Uncertainties (Floating Mean) Terms +============== ============================ ============= =============== ======== +``"slow"`` :math:`O[NM]` Yes Yes No +``"cython"`` :math:`O[NM]` Yes Yes No +``"scipy"`` :math:`O[NM]` No No No +``"fast"`` :math:`O[N\log M]` Yes Yes No +``"chi2"`` :math:`O[n_fNM]` Yes Yes Yes +``"fastchi2"`` :math:`O[n_f(M + N\log M)]` Yes Yes Yes +============== ============================ ============= =============== ======== + +In the Computational Scaling column, :math:`N` is the number of data points, +:math:`M` is the number of frequencies, and :math:`n_f` is the number of +Fourier terms for a multi-term fit. + +.. _lomb-scargle-example: + +RR Lyrae Example +================ + +.. EXAMPLE START: Computing a Periodogram for RR Lyrae Data + +An example of computing the periodogram for a more realistic dataset is shown in +the following figure. The data here consists of 50 nightly observations of a +simulated RR Lyrae-like variable star, with a lightcurve shape that is more +complicated than a simple sine wave: + +.. plot:: + + import numpy as np + import matplotlib.pyplot as plt + + from astropy.timeseries import LombScargle + + + def simulated_data(N, rseed=2, period=0.41, phase=0.0): + """Simulate data based from a pre-computed empirical fit""" + + # coefficients from a 5-term Fourier fit to SDSS object 1019544 + coeffs = [-0.0191, 0.1375, -0.1968, 0.0959, 0.075, + -0.0686, 0.0307, -0.0045, -0.0421, 0.0216, 0.0041] + + rand = np.random.default_rng(rseed) + t = phase + np.arange(N, dtype=float) + t += 0.1 * rand.standard_normal(N) + dmag = 0.01 + 0.03 * rand.random(N) + + omega = 2 * np.pi / period + n = np.arange(1 + len(coeffs) // 2)[:, None] + + mag = (15 + dmag * rand.standard_normal(N) + + np.dot(coeffs[::2], np.cos(n * omega * t)) + + + np.dot(coeffs[1::2], np.sin(n[1:] * omega * t))) + + return t, mag, dmag + + + # generate data and compute the periodogram + t, mag, dmag = simulated_data(50) + ls = LombScargle(t, mag, dmag, normalization='standard') + freq, PLS = ls.autopower(minimum_frequency=1 / 1.2, + maximum_frequency=1 / 0.2) + best_freq = freq[np.argmax(PLS)] + phase = (t * best_freq) % 1 + + # compute the best-fit model + phase_fit = np.linspace(0, 1) + mag_fit = ls.model(t=phase_fit / best_freq, + frequency=best_freq) + + # set up the figure & axes for plotting + fig, ax = plt.subplots(1, 2, figsize=(12, 5)) + fig.suptitle('Lomb-Scargle Periodogram (period=0.41 days)') + fig.subplots_adjust(bottom=0.12, left=0.07, right=0.95) + inset = fig.add_axes([0.78, 0.56, 0.15, 0.3]) + + # plot the raw data + ax[0].errorbar(t, mag, dmag, fmt='ok', elinewidth=1.5, capsize=0) + ax[0].invert_yaxis() + ax[0].set(xlim=(0, 50), + xlabel='Observation time (days)', + ylabel='Observed Magnitude') + + # plot the periodogram + ax[1].plot(1. / freq, PLS) + ax[1].set(xlabel='period (days)', + ylabel='Lomb-Scargle Power', + xlim=(0.2, 1.2), + ylim=(0, 1)); + + # plot the false-alarm levels + z_false = ls.false_alarm_level(0.01, maximum_frequency=1 / 0.2, + method='baluev') + ax[1].axhline(z_false, linestyle='dotted', color='black') + + # plot the phased data & model in the inset + inset.errorbar(phase, mag, dmag, fmt='.k', capsize=0) + inset.plot(phase_fit, mag_fit) + inset.invert_yaxis() + inset.set_xlabel('phase') + inset.set_ylabel('mag') + + +The dotted line shows the periodogram level corresponding to a maximum peak +false alarm probability of 1%. This example demonstrates that for irregularly +sampled data, the Lomb-Scargle periodogram can be sensitive to frequencies +higher than the average Nyquist frequency: the above data are sampled at an +average rate of roughly one observation per night, and the periodogram +relatively cleanly reveals the true period of 0.41 days. + +Still, the periodogram has many spurious peaks, which are due to several +factors: + +1. Errors in observations lead to leakage of power from the true peaks. +2. The signal is not a perfect sinusoid, so additional peaks can indicate + higher frequency components in the signal. +3. The observations take place only at night, meaning that the survey window has + non-negligible power at a frequency of 1 cycle per day. Thus we expect + aliases to appear at :math:`f_{\rm alias} = f_{\rm true} + n f_{\rm window}` + for integer values of :math:`n`. With a true period of 0.41 days and a 1-day + signal in the observing window, the :math:`n=+1` and :math:`n=-1` aliases to + lie at periods of 0.29 and 0.69 days, respectively: these aliases are + prominent in the above plot. + +The interaction of these effects means that in practice there is no absolute +guarantee that the highest peak corresponds to the best frequency, and results +must be interpreted carefully. For a detailed discussion of these effects, see +[11]_. + +.. EXAMPLE END + +Literature References +===================== + +.. [1] Lomb, N.R. *Least-squares frequency analysis of unequally spaced data*. + Ap&SS 39 pp. 447-462 (1976) +.. [2] Scargle, J. D. *Studies in astronomical time series analysis. II - + Statistical aspects of spectral analysis of unevenly spaced data*. + ApJ 1:263 pp. 835-853 (1982) +.. [3] Press W.H. and Rybicki, G.B, *Fast algorithm for spectral analysis + of unevenly sampled data*. ApJ 1:338, p. 277 (1989) +.. [4] Vanderplas, J., Connolly, A. Ivezic, Z. & Gray, A. *Introduction to + astroML: Machine learning for astrophysics*. Proceedings of the + Conference on Intelligent Data Understanding (2012) +.. [5] Vanderplas, J., Connolly, A. Ivezic, Z. & Gray, A. *Statistics, + Data Mining and Machine Learning in Astronomy*. Princeton Press (2014) +.. [6] VanderPlas, J. *Gatspy: General Tools for Astronomical Time Series + in Python* (2015) https://zenodo.org/record/14833 +.. [7] VanderPlas, J. & Ivezic, Z. *Periodograms for Multiband Astronomical + Time Series*. ApJ 812.1:18 (2015) +.. [8] Baluev, R.V. *Assessing Statistical Significance of Periodogram Peaks* + MNRAS 385, 1279 (2008) +.. [9] Palmer, D. *A Fast Chi-squared Technique for Period Search of + Irregularly Sampled Data*. ApJ 695.1:496 (2009) +.. [10] Zechmeister, M. and Kurster, M. *The generalised Lomb-Scargle + periodogram. A new formalism for the floating-mean and Keplerian + periodograms*, A&A 496, 577-584 (2009) +.. [11] VanderPlas, J. *Understanding the Lomb-Scargle Periodogram* + ApJS 236.1:16 (2018) + https://ui.adsabs.harvard.edu/abs/2018ApJS..236...16V +.. [12] Ruiz-Antolin, D. and Townsend, A. *A nonuniform fast Fourier transform based on low rank approximation* + SIAM 40.1 (2018) + https://ui.adsabs.harvard.edu/abs/2018SJSC...40A.529R diff --git a/rst/math/math_776aea.rst b/rst/math/math_776aea.rst new file mode 100644 index 0000000..99f42b6 --- /dev/null +++ b/rst/math/math_776aea.rst @@ -0,0 +1,103 @@ +Mathematics +----------- + +Docutils supports inline math with the prefix or postfix ``:math:`` +role specificator, :math:`n! + \sin(x_n^2)` and `A_\text{c} = +\frac{\pi}{4} d^2`:math:, as well as displayed math via the +`math` directive: + +.. math:: + + f(\epsilon) = \frac{1}{1 + \exp\left(\frac{\varepsilon}{k_\text{B}T}\right)} + +Content may start on the first line of the directive, e.g. + +.. math:: N = \frac{\text{number of apples}}{7} + +Equations can be labeled with a reference name using the ``:name:`` option. +See `eq:M`_ and `eq:schrödinger`_ below. + +The determinant of the matrix + +.. math:: :name: eq:M + + \mathbf{M} = \left(\begin{matrix}a&b\\c&d\end{matrix}\right) + +is :math:`|\mathbf{M}| = ad - bc`. + +More than one display math block can be put in one math directive. +For example, the following sum and integral with limits: + +.. math:: + + \int_0^1 x^n dx = \frac{1}{n + 1} + + \sum_{n=1}^m n = \frac{m(m+1)}{2} + +LaTeX-supported Unicode math symbols can be used in math roles and +directives: + +The Schrödinger equation + +.. math:: :name: eq:schrödinger + + i\hbar \frac{∂}{∂t}Ψ = \hat{H}Ψ, + +with the *wave function* :math:`Ψ`, describes how the quantum state of a +physical system changes in time. + +Math-Accents: + .. list-table:: + :class: borderless + :width: 100% + + * - :math:`\acute{a}` ``\acute{a}`` + - :math:`\dot{t}` ``\dot{t}`` + - :math:`\hat{\gamma}` ``\hat{\gamma}`` + + * - :math:`\grave{a}` ``\grave{a}`` + - :math:`\ddot{t}` ``\ddot{t}`` + - :math:`\tilde{\alpha}` ``\tilde{\alpha}`` + + * - :math:`\breve{x}` ``\breve{x}`` + - :math:`\dddot{t}` ``\dddot{t}`` + - :math:`\vec{\imath}` ``\vec{\imath}`` + + * - :math:`\check{a}` ``\check{a}`` + - :math:`\bar{a}` ``\bar{a}`` + - :math:`\vec{R}` ``\vec{R}`` + +.. + \widetilde{xxx} + \widehat{xxx} + +Modulation Transfer Function: + +.. math:: + + \text{MTF} = \left|\frac{\mathcal{F}\{s(x)\}} + {\mathcal{F}\{ s(x)\} |_{ω_{x}=0}}\right| + = \mathrm{abs}\left(\frac + {∫_{-∞}^{∞}s(x) \mathrm{e}^{\mathrm{i}ω_{x}x}\mathrm{d}{x}} + {∫_{-∞}^{∞}s(x)\mathrm{d}{x}} + \right). + +Math split over two lines: If a double backslash is detected outside a +``\begin{...} \end{...}`` pair, the math code is wrapped in an AMSmath_ +``align`` environment: + +.. math:: + + s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_δ(x-x') \\ + & = ∫ s_{\mathrm{in}}(x')s_δ(x-x')\mathrm{d}x' + +Cases with the AMSmath_ ``cases`` environment: + +.. math:: + + \mathrm{sgn}(x) = \begin{cases} + -1 & x<0\\ + \phantom{-} 1 & x>0 + \end{cases} + +.. _AMSmath: ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf diff --git a/rst/math/math_de2679.rst b/rst/math/math_de2679.rst new file mode 100644 index 0000000..8a186d1 --- /dev/null +++ b/rst/math/math_de2679.rst @@ -0,0 +1,31 @@ +Test math extensions :math:`E = m c^2` +====================================== + +This is inline math: :math:`a^2 + b^2 = c^2`. + +.. math:: a^2 + b^2 = c^2 + +.. math:: + + a + 1 < b + +.. math:: + :label: foo + + e^{i\pi} = 1 + +.. math:: + :label: + + e^{ix} = \cos x + i\sin x + +.. math:: + + n \in \mathbb N + +.. math:: + :no-wrap: + + a + 1 < b + +Referencing equation :eq:`foo` and :math:numref:`foo`. diff --git a/rst/math/mixed_linear_524bae.rst b/rst/math/mixed_linear_524bae.rst new file mode 100644 index 0000000..34ff554 --- /dev/null +++ b/rst/math/mixed_linear_524bae.rst @@ -0,0 +1,204 @@ +.. currentmodule:: statsmodels.regression.mixed_linear_model + +.. _mixedlmmod: + +Linear Mixed Effects Models +=========================== + +Linear Mixed Effects models are used for regression analyses involving +dependent data. Such data arise when working with longitudinal and +other study designs in which multiple observations are made on each +subject. Some specific linear mixed effects models are + +* *Random intercepts models*, where all responses in a group are + additively shifted by a value that is specific to the group. + +* *Random slopes models*, where the responses in a group follow a + (conditional) mean trajectory that is linear in the observed + covariates, with the slopes (and possibly intercepts) varying by + group. + +* *Variance components models*, where the levels of one or more + categorical covariates are associated with draws from distributions. + These random terms additively determine the conditional mean of each + observation based on its covariate values. + +The statsmodels implementation of LME is primarily group-based, +meaning that random effects must be independently-realized for +responses in different groups. There are two types of random effects +in our implementation of mixed models: (i) random coefficients +(possibly vectors) that have an unknown covariance matrix, and (ii) +random coefficients that are independent draws from a common +univariate distribution. For both (i) and (ii), the random effects +influence the conditional mean of a group through their matrix/vector +product with a group-specific design matrix. + +A simple example of random coefficients, as in (i) above, is: + +.. math:: + + Y_{ij} = \beta_0 + \beta_1X_{ij} + \gamma_{0i} + \gamma_{1i}X_{ij} + \epsilon_{ij} + +Here, :math:`Y_{ij}` is the :math:`j^\rm{th}` measured response for subject +:math:`i`, and :math:`X_{ij}` is a covariate for this response. The +"fixed effects parameters" :math:`\beta_0` and :math:`\beta_1` are +shared by all subjects, and the errors :math:`\epsilon_{ij}` are +independent of everything else, and identically distributed (with mean +zero). The "random effects parameters" :math:`\gamma_{0i}` and +:math:`\gamma_{1i}` follow a bivariate distribution with mean zero, +described by three parameters: :math:`{\rm var}(\gamma_{0i})`, +:math:`{\rm var}(\gamma_{1i})`, and :math:`{\rm cov}(\gamma_{0i}, +\gamma_{1i})`. There is also a parameter for :math:`{\rm +var}(\epsilon_{ij})`. + +A simple example of variance components, as in (ii) above, is: + +.. math:: + + Y_{ijk} = \beta_0 + \eta_{1i} + \eta_{2j} + \epsilon_{ijk} + +Here, :math:`Y_{ijk}` is the :math:`k^\rm{th}` measured response under +conditions :math:`i, j`. The only "mean structure parameter" is +:math:`\beta_0`. The :math:`\eta_{1i}` are independent and +identically distributed with zero mean, and variance :math:`\tau_1^2`, +and the :math:`\eta_{2j}` are independent and identically distributed +with zero mean, and variance :math:`\tau_2^2`. + +statsmodels MixedLM handles most non-crossed random effects models, +and some crossed models. To include crossed random effects in a +model, it is necessary to treat the entire dataset as a single group. +The variance components arguments to the model can then be used to +define models with various combinations of crossed and non-crossed +random effects. + +The statsmodels LME framework currently supports post-estimation +inference via Wald tests and confidence intervals on the coefficients, +profile likelihood analysis, likelihood ratio testing, and AIC. + +Examples +-------- + +.. ipython:: python + + import statsmodels.api as sm + import statsmodels.formula.api as smf + + data = sm.datasets.get_rdataset("dietox", "geepack").data + + md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"]) + mdf = md.fit() + print(mdf.summary()) + +Detailed examples can be found here + +* `Mixed LM `_ + +There are some notebook examples on the Wiki: +`Wiki notebooks for MixedLM `_ + + + +Technical Documentation +----------------------- + +The data are partitioned into disjoint groups. +The probability model for group :math:`i` is: + +.. math:: + + Y = X\beta + Z\gamma + Q_1\eta_1 + \cdots + Q_k\eta_k + \epsilon + +where + +* :math:`n_i` is the number of observations in group :math:`i` +* :math:`Y` is a :math:`n_i` dimensional response vector +* :math:`X` is a :math:`n_i * k_{fe}` dimensional matrix of fixed effects + coefficients +* :math:`\beta` is a :math:`k_{fe}`-dimensional vector of fixed effects slopes +* :math:`Z` is a :math:`n_i * k_{re}` dimensional matrix of random effects + coefficients +* :math:`\gamma` is a :math:`k_{re}`-dimensional random vector with mean 0 + and covariance matrix :math:`\Psi`; note that each group + gets its own independent realization of gamma. +* :math:`Q_j` is a :math:`n_i \times q_j` dimensional design matrix for the + :math:`j^\rm{th}` variance component. +* :math:`\eta_j` is a :math:`q_j`-dimensional random vector containing independent + and identically distributed values with variance :math:`\tau_j^2`. +* :math:`\epsilon` is a :math:`n_i` dimensional vector of i.i.d normal + errors with mean 0 and variance :math:`\sigma^2`; the :math:`\epsilon` + values are independent both within and between groups + +:math:`Y, X, \{Q_j\}` and :math:`Z` must be entirely observed. :math:`\beta`, +:math:`\Psi`, and :math:`\sigma^2` are estimated using ML or REML estimation, +and :math:`\gamma`, :math:`\{\eta_j\}` and :math:`\epsilon` are +random so define the probability model. + +The marginal mean structure is :math:`E[Y|X,Z] = X*\beta`. If only +the marginal mean structure is of interest, GEE is a good alternative +to mixed models. + +Notation: + +* :math:`cov_{re}` is the random effects covariance matrix (referred + to above as :math:`\Psi`) and :math:`scale` is the (scalar) error + variance. There is also a single estimated variance parameter + :math:`\tau_j^2` for each variance component. For a single group, + the marginal covariance matrix of endog given exog is + :math:`scale*I + Z * cov_{re} * Z`, where :math:`Z` is the design + matrix for the random effects in one group. + +References +^^^^^^^^^^ + +The primary reference for the implementation details is: + +* MJ Lindstrom, DM Bates (1988). *Newton Raphson and EM algorithms for + linear mixed effects models for repeated measures data*. Journal of + the American Statistical Association. Volume 83, Issue 404, pages 1014-1022. + +See also this more recent document: + +* https://econ.ucsb.edu/~doug/245a/Papers/Mixed%20Effects%20Implement.pdf + +All the likelihood, gradient, and Hessian calculations closely follow +Lindstrom and Bates. + +The following two documents are written more from the perspective of +users: + +* https://r-forge.r-project.org/scm/viewvc.php/*checkout*/www/lMMwR/lrgprt.pdf?revision=949&root=lme4&pathrev=1781 + +* http://lme4.r-forge.r-project.org/slides/2009-07-07-Rennes/3Longitudinal-4.pdf + +.. Class hierarchy: TODO + + General references for this class of models are + +Module Reference +---------------- + +.. module:: statsmodels.regression.mixed_linear_model + :synopsis: Mixed Linear Models + + +The model class is: + +.. autosummary:: + :toctree: generated/ + + MixedLM + +The result class is: + +.. autosummary:: + :toctree: generated/ + + MixedLMResults + +Custom variance structures (the ``exog_vc`` argument to ``MixedLM``) are +specified with: + +.. autosummary:: + :toctree: generated/ + + VCSpec diff --git a/rst/math/neutron_physics_1490f3.rst b/rst/math/neutron_physics_1490f3.rst new file mode 100644 index 0000000..2b797e3 --- /dev/null +++ b/rst/math/neutron_physics_1490f3.rst @@ -0,0 +1,1775 @@ +.. _methods_neutron_physics: + +=============== +Neutron Physics +=============== + +There are limited differences between physics treatments used in the +continuous-energy and multi-group modes. If distinctions are necessary, each +of the following sections will provide an explanation of the differences. +Otherwise, replacing any references of the particle's energy (`E`) with +references to the particle's energy group (`g`) will suffice. + +----------------------------------- +Sampling Distance to Next Collision +----------------------------------- + +As a particle travels through a homogeneous material, the probability +distribution function for the distance to its next collision :math:`\ell` is + +.. math:: + :label: distance-pdf + + p(\ell) d\ell = \Sigma_t e^{-\Sigma_t \ell} d\ell + +where :math:`\Sigma_t` is the total macroscopic cross section of the +material. Equation :eq:`distance-pdf` tells us that the further the distance is +to the next collision, the less likely the particle will travel that +distance. In order to sample the probability distribution function, we first +need to convert it to a cumulative distribution function + +.. math:: + :label: distance-cdf + + \int_0^{\ell} d\ell' p(\ell') = \int_0^{\ell} d\ell' \Sigma_t e^{-\Sigma_t + \ell'} = 1 - e^{-\Sigma_t \ell}. + +By setting the cumulative distribution function equal to :math:`\xi`, a random +number on the unit interval, and solving for the distance :math:`\ell`, we +obtain a formula for sampling the distance to next collision: + +.. math:: + :label: sample-distance-1 + + \ell = -\frac{\ln (1 - \xi)}{\Sigma_t}. + +Since :math:`\xi` is uniformly distributed on :math:`[0,1)`, this implies that +:math:`1 - \xi` is also uniformly distributed on :math:`[0,1)` as well. Thus, +the formula usually used to calculate the distance to next collision is + +.. math:: + :label: sample-distance-2 + + \ell = -\frac{\ln \xi}{\Sigma_t} + +---------------------------------------------------- +:math:`(n,\gamma)` and Other Disappearance Reactions +---------------------------------------------------- + +All absorption reactions other than fission do not produce any secondary +neutrons. As a result, these are the easiest type of reactions to handle. When a +collision occurs, the first step is to sample a nuclide within a material. Once +the nuclide has been sampled, then a specific reaction for that nuclide is +sampled. Since the total absorption cross section is pre-calculated at the +beginning of a simulation, the first step in sampling a reaction is to determine +whether a "disappearance" reaction occurs where no secondary neutrons are +produced. This is done by sampling a random number :math:`\xi` on the interval +:math:`[0,1)` and checking whether + +.. math:: + :label: disappearance + + \xi \sigma_t (E) < \sigma_a (E) - \sigma_f (E) + +where :math:`\sigma_t` is the total cross section, :math:`\sigma_a` is the +absorption cross section (this includes fission), and :math:`\sigma_f` is the +total fission cross section. If this condition is met, then the neutron is +killed and we proceed to simulate the next neutron from the source bank. + +Note that photons arising from :math:`(n,\gamma)` and other neutron reactions +are not produced in a microscopically correct manner. Instead, photons are +sampled probabilistically at each neutron collision, regardless of what reaction +actually takes place. This is described in more detail in +:ref:`photon_production`. + +------------------ +Elastic Scattering +------------------ + +Note that the multi-group mode makes no distinction between elastic or +inelastic scattering reactions. The specific multi-group scattering +implementation is discussed in the :ref:`multi-group-scatter` section. + +Elastic scattering refers to the process by which a neutron scatters off a +nucleus and does not leave it in an excited state. It is referred to as "elastic" +because in the center-of-mass system, the neutron does not actually lose +energy. However, in lab coordinates, the neutron does indeed lose +energy. Elastic scattering can be treated exactly in a Monte Carlo code thanks +to its simplicity. + +Let us discuss how OpenMC handles two-body elastic scattering kinematics. The +first step is to determine whether the target nucleus has any associated +motion. Above a certain energy threshold (400 kT by default), all scattering is +assumed to take place with the target at rest. Below this threshold though, we +must account for the thermal motion of the target nucleus. Methods to sample the +velocity of the target nucleus are described later in section +:ref:`freegas`. For the time being, let us assume that we have sampled the +target velocity :math:`\mathbf{v}_t`. The velocity of the center-of-mass system +is calculated as + +.. math:: + :label: velocity-com + + \mathbf{v}_{cm} = \frac{\mathbf{v}_n + A \mathbf{v}_t}{A + 1} + +where :math:`\mathbf{v}_n` is the velocity of the neutron and :math:`A` is the +atomic mass of the target nucleus measured in neutron masses (commonly referred +to as the *atomic weight ratio*). With the velocity of the center-of-mass +calculated, we can then determine the neutron's velocity in the center-of-mass +system: + +.. math:: + :label: velocity-neutron-com + + \mathbf{V}_n = \mathbf{v}_n - \mathbf{v}_{cm} + +where we have used uppercase :math:`\mathbf{V}` to denote the center-of-mass +system. The direction of the neutron in the center-of-mass system is + +.. math:: + :label: angle-neutron-com + + \mathbf{\Omega}_n = \frac{\mathbf{V}_n}{|| \mathbf{V}_n ||}. + +At low energies, elastic scattering will be isotropic in the center-of-mass +system, but for higher energies, there may be p-wave and higher order scattering +that leads to anisotropic scattering. Thus, in general, we need to sample a +cosine of the scattering angle which we will refer to as :math:`\mu`. For +elastic scattering, the secondary angle distribution is always given in the +center-of-mass system and is sampled according to the procedure outlined in +:ref:`sample-angle`. After the cosine of the angle of scattering has been +sampled, we need to determine the neutron's new direction +:math:`\mathbf{\Omega}'_n` in the center-of-mass system. This is done with the +procedure in :ref:`transform-coordinates`. The new direction is multiplied by +the speed of the neutron in the center-of-mass system to obtain the new velocity +vector in the center-of-mass: + +.. math:: + :label: velocity-neutron-com-2 + + \mathbf{V}'_n = || \mathbf{V}_n || \mathbf{\Omega}'_n. + +Finally, we transform the velocity in the center-of-mass system back to lab +coordinates: + +.. math:: + :label: velocity-neutron-lab + + \mathbf{v}'_n = \mathbf{V}'_n + \mathbf{v}_{cm} + +In OpenMC, the angle and energy of the neutron are stored rather than the +velocity vector itself, so the post-collision angle and energy can be inferred +from the post-collision velocity of the neutron in the lab system. + +For tallies that require the scattering cosine, it is important to store the +scattering cosine in the lab system. If we know the scattering cosine in the +center-of-mass, the scattering cosine in the lab system can be calculated as + +.. math:: + :label: cosine-lab + + \mu_{lab} = \frac{1 + A\mu}{\sqrt{A^2 + 2A\mu + 1}}. + +However, equation :eq:`cosine-lab` is only valid if the target was at rest. When +the target nucleus does have thermal motion, the cosine of the scattering angle +can be determined by simply taking the dot product of the neutron's initial and +final direction in the lab system. + +.. _inelastic-scatter: + +-------------------- +Inelastic Scattering +-------------------- + +Note that the multi-group mode makes no distinction between elastic or +inelastic scattering reactions. The specific multi-group scattering +implementation is discussed in the :ref:`multi-group-scatter` section. + +The major algorithms for inelastic scattering were described in previous +sections. First, a scattering cosine is sampled using the algorithms in +:ref:`sample-angle`. Then an outgoing energy is sampled using the algorithms in +:ref:`sample-energy`. If the outgoing energy and scattering cosine were given in +the center-of-mass system, they are transformed to laboratory coordinates using +the algorithm described in :ref:`transform-coordinates`. Finally, the direction +of the particle is changed also using the procedure in +:ref:`transform-coordinates`. + +Although inelastic scattering leaves the target nucleus in an excited state, no +secondary photons from nuclear de-excitation are tracked in OpenMC. + +------------------------ +:math:`(n,xn)` Reactions +------------------------ + +Note that the multi-group mode makes no distinction between elastic or +inelastic scattering reactions. The specific multi-group scattering +implementation is discussed in the :ref:`multi-group-scatter` section. + +These types of reactions are just treated as inelastic scattering and as such +are subject to the same procedure as described in :ref:`inelastic-scatter`. For +reactions with integral multiplicity, e.g., :math:`(n,2n)`, an appropriate +number of secondary neutrons are created. For reactions that have a multiplicity +given as a function of the incoming neutron energy (which occasionally occurs +for MT=5), the weight of the outgoing neutron is multiplied by the multiplicity. + +.. _multi-group-scatter: + +---------------------- +Multi-Group Scattering +---------------------- + +In multi-group mode, a scattering collision requires that the outgoing energy +group of the simulated particle be selected from a probability distribution, +the change-in-angle selected from a probability distribution according to +the outgoing energy group, and finally the particle's weight adjusted again +according to the outgoing energy group. + +The first step in selecting an outgoing energy group for a particle in a given +incoming energy group is to select a random number (:math:`\xi`) between 0 and +1. This number is then compared to the cumulative distribution function +produced from the outgoing group (`g'`) data for the given incoming group (`g`): + +.. math:: + CDF = \sum_{g'=1}^{h}\Sigma_{s,g \rightarrow g'} + +If the scattering data is represented as a Legendre expansion, then the +value of :math:`\Sigma_{s,g \rightarrow g'}` above is the 0th order for the +given group transfer. If the data is provided as tabular or histogram data, then +:math:`\Sigma_{s,g \rightarrow g'}` is the sum of all bins of data for a given +`g` and `g'` pair. + +Now that the outgoing energy is known the change-in-angle, :math:`\mu` can be +determined. If the data is provided as a Legendre expansion, this is done by +rejection sampling of the probability distribution represented by the Legendre +series. For efficiency, the selected values of the PDF (:math:`f(\mu)`) are +chosen to be between 0 and the maximum value of :math:`f(\mu)` in the domain of +-1 to 1. Note that this sampling scheme automatically forces negative values of +the :math:`f(\mu)` probability distribution function to be treated as zero +probabilities. + +If the angular data is instead provided as a tabular representation, then the +value of :math:`\mu` is selected as described in the :ref:`angle-tabular` +section with a linear-linear interpolation scheme. + +If the angular data is provided as a histogram representation, then +the value of :math:`\mu` is selected in a similar fashion to that described for +the selection of the outgoing energy (since the energy group representation is +simply a histogram representation) except the CDF is composed of the angular +bins and not the energy groups. However, since we are interested in a specific +value of :math:`\mu` instead of a group, then an angle is selected from a uniform +distribution within from the chosen angular bin. + +The final step in the scattering treatment is to adjust the weight of the +neutron to account for any production of neutrons due to :math:`(n,xn)` +reactions. This data is obtained from the multiplicity data provided in the +multi-group cross section library for the material of interest. +The scaled value will default to 1.0 if no value is provided in the library. + +.. _fission: + +------- +Fission +------- + +While fission is normally considered an absorption reaction, as far as it +concerns a Monte Carlo simulation it actually bears more similarities to +inelastic scattering since fission results in secondary neutrons in the exit +channel. Other absorption reactions like :math:`(n,\gamma)` or +:math:`(n,\alpha)`, on the contrary, produce no neutrons. There are a few other +idiosyncrasies in treating fission. In an eigenvalue calculation, secondary +neutrons from fission are only "banked" for use in the next generation rather +than being tracked as secondary neutrons from elastic and inelastic scattering +would be. On top of this, fission is sometimes broken into first-chance fission, +second-chance fission, etc. The nuclear data file either lists the partial +fission reactions with secondary energy distributions for each one, or a total +fission reaction with a single secondary energy distribution. + +When a fission reaction is sampled in OpenMC (either total fission or, if data +exists, first- or second-chance fission), the following algorithm is used to +create and store fission sites for the following generation. First, the average +number of prompt and delayed neutrons must be determined to decide whether the +secondary neutrons will be prompt or delayed. This is important because delayed +neutrons have a markedly different spectrum from prompt neutrons, one that has a +lower average energy of emission. Furthermore, in simulations where tracking +time of neutrons is important, we need to consider the emission time delay of +the secondary neutrons, which is dependent on the decay constant of the +delayed neutron precursor. The total number of neutrons emitted +:math:`\nu_t` is given as a function of incident energy in the ENDF format. Two +representations exist for :math:`\nu_t`. The first is a polynomial of order +:math:`N` with coefficients :math:`c_0,c_1,\dots,c_N`. If :math:`\nu_t` has this +format, we can evaluate it at incoming energy :math:`E` by using the equation + +.. math:: + :label: nu-polynomial + + \nu_t (E) = \sum_{i = 0}^N c_i E^i. + +The other representation is just a tabulated function with a specified +interpolation law. The number of prompt neutrons released per fission event +:math:`\nu_p` is also given as a function of incident energy and can be +specified in a polynomial or tabular format. The number of delayed neutrons +released per fission event :math:`\nu_d` can only be specified in a tabular +format. In practice, we only need to determine :math:`\nu_t` and +:math:`\nu_d`. Once these have been determined, we can calculate the delayed +neutron fraction + +.. math:: + :label: beta + + \beta = \frac{\nu_d}{\nu_t}. + +We then need to determine how many total neutrons should be emitted from +fission. If no survival biasing is being used, then the number of neutrons +emitted is + +.. math:: + :label: fission-neutrons + + \nu = \frac{w \nu_t}{k_{eff}} + +where :math:`w` is the statistical weight and :math:`k_{eff}` is the effective +multiplication factor from the previous generation. The number of neutrons +produced is biased in this manner so that the expected number of fission +neutrons produced is the number of source particles that we started with in the +generation. Since :math:`\nu` is not an integer, we use the following procedure +to obtain an integral number of fission neutrons to produce. If :math:`\xi > +\nu - \lfloor \nu \rfloor`, then we produce :math:`\lfloor \nu \rfloor` +neutrons. Otherwise, we produce :math:`\lfloor \nu \rfloor + 1` neutrons. Then, +for each fission site produced, we sample the outgoing angle and energy +according to the algorithms given in :ref:`sample-angle` and +:ref:`sample-energy` respectively. If the neutron is to be born delayed, then +there is an extra step of sampling a delayed neutron precursor group to get the +associated secondary energy distribution and the decay constant +:math:`\lambda`, which is needed to sample the emission delay time :math:`t_d`: + +.. math:: + :label: sample-delay-time + + t_d = -\frac{\ln \xi}{\lambda}. + +The sampled outgoing angle and energy of fission neutrons along with the +position of the collision site are stored in an array called the fission +bank. In a subsequent generation, these fission bank sites are used as starting +source sites. + +The above description is similar for the multi-group mode except the data are +provided as group-wise data instead of in a continuous-energy format. In this +case, the outgoing energy of the fission neutrons are represented as histograms +by way of either the nu-fission matrix or chi vector. + +------------------------------------ +Secondary Angle-Energy Distributions +------------------------------------ + +Note that this section is specific to continuous-energy mode since the +multi-group scattering process has already been described including the +secondary energy and angle sampling. + +For a reaction with secondary products, it is necessary to determine the +outgoing angle and energy of the products. For any reaction other than elastic +and level inelastic scattering, the outgoing energy must be determined based on +tabulated or parameterized data. The `ENDF-6 Format`_ specifies a +variety of ways that the secondary energy distribution can be represented. ENDF +File 5 contains uncorrelated energy distribution whereas ENDF File 6 contains +correlated energy-angle distributions. The ACE format specifies its own +representations based loosely on the formats given in ENDF-6. OpenMC's HDF5 +nuclear data files use a combination of ENDF and ACE distributions; in this +section, we will describe how the outgoing angle and energy of secondary +particles are sampled. + +One of the subtleties in the nuclear data format is the fact that a single +reaction product can have multiple angle-energy distributions. This is mainly +useful for reactions with multiple products of the same type in the exit channel +such as :math:`(n,2n)` or :math:`(n,3n)`. In these types of reactions, each +neutron is emitted corresponding to a different excitation level of the compound +nucleus, and thus in general the neutrons will originate from different energy +distributions. If multiple angle-energy distributions are present, they are +assigned incoming-energy-dependent probabilities that can then be used to +randomly select one. + +Once a distribution has been selected, the procedure for determining the +outgoing angle and energy will depend on the type of the distribution. + +Uncorrelated Angle-Energy Distributions +--------------------------------------- + +The first set of distributions we will look at are uncorrelated angle-energy +distributions, where angle and energy are specified separately. For these +distributions, OpenMC first samples the angular distribution as described +:ref:`sample-angle` and then samples an energy as described in +:ref:`sample-energy`. + +.. _sample-angle: + +Sampling Angular Distributions +++++++++++++++++++++++++++++++ + +For elastic scattering, it is only necessary to specific a secondary angle +distribution since the outgoing energy can be determined analytically. Other +reactions may also have separate secondary angle and secondary energy +distributions that are uncorrelated. In these cases, the secondary angle +distribution is represented as either + +- An isotropic angular distribution, +- A tabular distribution. + +Isotropic Angular Distribution +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In the first case, no data is stored in the nuclear data file, and the cosine of +the scattering angle is simply calculated as + +.. math:: + :label: isotropic-angle + + \mu = 2\xi - 1 + +where :math:`\mu` is the cosine of the scattering angle and :math:`\xi` is a +random number sampled uniformly on :math:`[0,1)`. + +.. _angle-tabular: + +Tabular Angular Distribution +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In this case, we have a table of cosines and their corresponding values for a +probability distribution function and cumulative distribution function. For each +incoming neutron energy :math:`E_i`, let us call :math:`p_{i,j}` the j-th value +in the probability distribution function and :math:`c_{i,j}` the j-th value in +the cumulative distribution function. We first find the interpolation factor on +the incoming energy grid: + +.. math:: + :label: interpolation-factor + + f = \frac{E - E_i}{E_{i+1} - E_i} + +where :math:`E` is the incoming energy of the particle. Then, statistical +interpolation is performed to choose between using the cosines and distribution +functions corresponding to energy :math:`E_i` and :math:`E_{i+1}`. Let +:math:`\ell` be the chosen table where :math:`\ell = i` if :math:`\xi_1 > f` and +:math:`\ell = i + 1` otherwise, where :math:`\xi_1` is a random number. Another +random number :math:`\xi_2` is used to sample a scattering cosine bin :math:`j` +using the cumulative distribution function: + +.. math:: + :label: sample-cdf + + c_{\ell,j} < \xi_2 < c_{\ell,j+1} + +The final scattering cosine will depend on whether histogram or linear-linear +interpolation is used. In general, we can write the cumulative distribution +function as + +.. math:: + :label: cdf + + c(\mu) = \int_{-1}^\mu p(\mu') d\mu' + +where :math:`c(\mu)` is the cumulative distribution function and :math:`p(\mu)` +is the probability distribution function. Since we know that +:math:`c(\mu_{\ell,j}) = c_{\ell,j}`, this implies that for :math:`\mu > +\mu_{\ell,j}`, + +.. math:: + :label: cdf-2 + + c(\mu) = c_{\ell,j} + \int_{\mu_{\ell,j}}^{\mu} p(\mu') d\mu' + +For histogram interpolation, we have that :math:`p(\mu') = p_{\ell,j}` for +:math:`\mu_{\ell,j} \le \mu' < \mu_{\ell,j+1}`. Thus, after integrating +:eq:`cdf-2` we have that + +.. math:: + :label: cumulative-dist-histogram + + c(\mu) = c_{\ell,j} + (\mu - \mu_{\ell,j}) p_{\ell,j} = \xi_2 + +Solving for the scattering cosine, we obtain the final form for histogram +interpolation: + +.. math:: + :label: cosine-histogram + + \mu = \mu_{\ell,j} + \frac{\xi_2 - c_{\ell,j}}{p_{\ell,j}}. + +For linear-linear interpolation, we represent the function :math:`p(\mu')` as a +first-order polynomial in :math:`\mu'`. If we interpolate between successive +values on the probability distribution function, we know that + +.. math:: + :label: pdf-interpolation + + p(\mu') - p_{\ell,j} = \frac{p_{\ell,j+1} - p_{\ell,j}}{\mu_{\ell,j+1} - + \mu_{\ell,j}} (\mu' - \mu_{\ell,j}) + +Solving for :math:`p(\mu')` in equation :eq:`pdf-interpolation` and inserting it +into equation :eq:`cdf-2`, we obtain + +.. math:: + :label: cdf-linlin + + c(\mu) = c_{\ell,j} + \int_{\mu_{\ell,j}}^{\mu} \left [ \frac{p_{\ell,j+1} - + p_{\ell,j}}{\mu_{\ell,j+1} - \mu_{\ell,j}} (\mu' - \mu_{\ell,j}) + + p_{\ell,j} \right ] d\mu'. + +Let us now make a change of variables using + +.. math:: + :label: introduce-eta + + \eta = \frac{p_{\ell,j+1} - p_{\ell,j}}{\mu_{\ell,j+1} - \mu_{\ell,j}} + (\mu' - \mu_{\ell,j}) + p_{\ell,j}. + +Equation :eq:`cdf-linlin` then becomes + +.. math:: + :label: cdf-linlin-eta + + c(\mu) = c_{\ell,j} + \frac{1}{m} \int_{p_{\ell,j}}^{m(\mu - \mu_{\ell,j}) + + p_{\ell,j}} \eta \, d\eta + +where we have used + +.. math:: + :label: slope + + m = \frac{p_{\ell,j+1} - p_{\ell,j}}{\mu_{\ell,j+1} - \mu_{\ell,j}}. + +Integrating equation :eq:`cdf-linlin-eta`, we have + +.. math:: + :label: cdf-linlin-integrated + + c(\mu) = c_{\ell,j} + \frac{1}{2m} \left ( \left [ m (\mu - \mu_{\ell,j} ) + + p_{\ell,j} \right ]^2 - p_{\ell,j}^2 \right ) = \xi_2 + +Solving for :math:`\mu`, we have the final form for the scattering cosine using +linear-linear interpolation: + +.. math:: + :label: cosine-linlin + + \mu = \mu_{\ell,j} + \frac{1}{m} \left ( \sqrt{p_{\ell,j}^2 + 2 m (\xi_2 - + c_{\ell,j} )} - p_{\ell,j} \right ) + +.. _sample-energy: + +Sampling Energy Distributions ++++++++++++++++++++++++++++++ + +Inelastic Level Scattering +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +It can be shown (see Foderaro_) that in inelastic level scattering, the outgoing +energy of the neutron :math:`E'` can be related to the Q-value of the reaction +and the incoming energy: + +.. math:: + :label: level-scattering + + E' = \left ( \frac{A}{A+1} \right )^2 \left ( E - \frac{A + 1}{A} Q \right ) + +where :math:`A` is the mass of the target nucleus measured in neutron masses. + +.. _continuous-tabular: + +Continuous Tabular Distribution +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In a continuous tabular distribution, a tabulated energy distribution is +provided for each of a set of incoming energies. While the representation itself +is simple, the complexity lies in how one interpolates between incident as well +as outgoing energies on such a table. If one performs simple interpolation +between tables for neighboring incident energies, it is possible that the +resulting energies would violate laws governing the kinematics, i.e., the +outgoing energy may be outside the range of available energy in the reaction. + +To avoid this situation, the accepted practice is to use a process known as +`scaled interpolation`_. First, we find the tabulated incident energies which +bound the actual incoming energy of the particle, i.e., find :math:`i` such that +:math:`E_i < E < E_{i+1}` and calculate the interpolation factor :math:`f` via +:eq:`interpolation-factor`. Then, we interpolate between the minimum and maximum +energies of the outgoing energy distributions corresponding to :math:`E_i` and +:math:`E_{i+1}`: + +.. math:: + :label: continuous-minmax + + E_{min} = E_{i,1} + f ( E_{i+1,1} - E_{i,1} ) \\ + E_{max} = E_{i,M} + f ( E_{i+1,M} - E_{i,M} ) + +where :math:`E_{min}` and :math:`E_{max}` are the minimum and maximum outgoing +energies of a scaled distribution, :math:`E_{i,j}` is the j-th outgoing energy +corresponding to the incoming energy :math:`E_i`, and :math:`M` is the number of +outgoing energy bins. + +Next, statistical interpolation is performed to choose between using the +outgoing energy distributions corresponding to energy :math:`E_i` and +:math:`E_{i+1}`. Let :math:`\ell` be the chosen table where :math:`\ell = i` if +:math:`\xi_1 > f` and :math:`\ell = i + 1` otherwise, and :math:`\xi_1` is a +random number. For each incoming neutron energy :math:`E_i`, let us call +:math:`p_{i,j}` the j-th value in the probability distribution function, +:math:`c_{i,j}` the j-th value in the cumulative distribution function, and +:math:`E_{i,j}` the j-th outgoing energy. We then sample an outgoing energy bin +:math:`j` using the cumulative distribution function: + +.. math:: + :label: continuous-sample-cdf + + c_{\ell,j} < \xi_2 < c_{\ell,j+1} + +where :math:`\xi_2` is a random number sampled uniformly on :math:`[0,1)`. At +this point, we need to interpolate between the successive values on the outgoing +energy distribution using either histogram or linear-linear interpolation. The +formulas for these can be derived along the same lines as those found in +:ref:`angle-tabular`. For histogram interpolation, the interpolated outgoing +energy on the :math:`\ell`-th distribution is + +.. math:: + :label: energy-histogram + + \hat{E} = E_{\ell,j} + \frac{\xi_2 - c_{\ell,j}}{p_{\ell,j}}. + +If linear-linear interpolation is to be used, the outgoing energy on the +:math:`\ell`-th distribution is + +.. math:: + :label: energy-linlin + + \hat{E} = E_{\ell,j} + \frac{E_{\ell,j+1} - E_{\ell,j}}{p_{\ell,j+1} - + p_{\ell,j}} \left ( \sqrt{p_{\ell,j}^2 + 2 \frac{p_{\ell,j+1} - + p_{\ell,j}}{E_{\ell,j+1} - E_{\ell,j}} ( \xi_2 - c_{\ell,j} )} - p_{\ell,j} + \right ). + +Since this outgoing energy may violate reaction kinematics, we then scale it to +minimum and maximum energies calculated in equation :eq:`continuous-minmax` to +get the final outgoing energy: + +.. math:: + :label: continuous-eout + + E' = E_{min} + \frac{\hat{E} - E_{\ell,1}}{E_{\ell,M} - E_{\ell,1}} + (E_{max} - E_{min}) + +where :math:`E_{min}` and :math:`E_{max}` are defined the same as in equation +:eq:`continuous-minmax`. + +.. _maxwell: + +Maxwell Fission Spectrum +^^^^^^^^^^^^^^^^^^^^^^^^ + +One representation of the secondary energies for neutrons from fission is the +so-called Maxwell spectrum. A probability distribution for the Maxwell spectrum +can be written in the form + +.. math:: + :label: maxwell-spectrum + + p(E') dE' = c E'^{1/2} e^{-E'/T(E)} dE' + +where :math:`E` is the incoming energy of the neutron and :math:`T` is the +so-called nuclear temperature, which is a function of the incoming energy of the +neutron. The ENDF format contains a list of nuclear temperatures versus incoming +energies. The nuclear temperature is interpolated between neighboring incoming +energies using a specified interpolation law. Once the temperature :math:`T` is +determined, we then calculate a candidate outgoing energy based on rule C64 in +the `Monte Carlo Sampler`_: + +.. math:: + :label: maxwell-E-candidate + + E' = -T \left [ \log (\xi_1) + \log (\xi_2) \cos^2 \left ( \frac{\pi + \xi_3}{2} \right ) \right ] + +where :math:`\xi_1, \xi_2, \xi_3` are random numbers sampled on the unit +interval. The outgoing energy is only accepted if + +.. math:: + :label: maxwell-restriction + + 0 \le E' \le E - U + +where :math:`U` is called the restriction energy and is specified in the ENDF +data. If the outgoing energy is rejected, it is resampled using equation +:eq:`maxwell-E-candidate`. + +Evaporation Spectrum +^^^^^^^^^^^^^^^^^^^^ + +Evaporation spectra are primarily used in compound nucleus processes where a +secondary particle can "evaporate" from the compound nucleus if it has +sufficient energy. The probability distribution for an evaporation spectrum can +be written in the form + +.. math:: + :label: evaporation-spectrum + + p(E') dE' = c E' e^{-E'/T(E)} dE' + +where :math:`E` is the incoming energy of the neutron and :math:`T` is the +nuclear temperature, which is a function of the incoming energy of the +neutron. The ENDF format contains a list of nuclear temperatures versus incoming +energies. The nuclear temperature is interpolated between neighboring incoming +energies using a specified interpolation law. Once the temperature :math:`T` is +determined, we then calculate a candidate outgoing energy based on the algorithm +given in LA-UR-14-27694_: + +.. math:: + :label: evaporation-E + + E' = -T \log ((1 - g\xi_1)(1 - g\xi_2)) + +where :math:`g = 1 - e^{-w}`, :math:`w = (E - U)/T`, :math:`U` is the +restriction energy, and :math:`\xi_1, \xi_2` are random numbers sampled on the +unit interval. The outgoing energy is only accepted according to the restriction +energy as in equation :eq:`maxwell-restriction`. This algorithm has a much +higher rejection efficiency than the standard technique, i.e. rule C45 in the +`Monte Carlo Sampler`_. + +Energy-Dependent Watt Spectrum +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The probability distribution for a `Watt fission spectrum`_ can be written in +the form + +.. math:: + :label: watt-spectrum + + p(E') dE' = c e^{-E'/a(E)} \sinh \sqrt{b(E) \, E'} dE' + +where :math:`a` and :math:`b` are parameters for the distribution and are given +as tabulated functions of the incoming energy of the neutron. These two +parameters are interpolated on the incoming energy grid using a specified +interpolation law. Once the parameters have been determined, we sample a +Maxwellian spectrum with nuclear temperature :math:`a` using the algorithm +described in :ref:`maxwell` to get an energy :math:`W`. Then, the outgoing +energy is calculated as + +.. math:: + :label: watt-E + + E' = W + \frac{a^2 b}{4} + (2\xi - 1) \sqrt{a^2 b W} + +where :math:`\xi` is a random number sampled on the interval :math:`[0,1)`. The +outgoing energy is only accepted according to a specified restriction energy +:math:`U` as defined in equation :eq:`maxwell-restriction`. + +A derivation of the algorithm described here can be found in a paper by Romano_. + +Product Angle-Energy Distributions +---------------------------------- + +If the secondary distribution for a product was given in file 6 in ENDF, the +angle and energy are correlated with one another and cannot be sampled +separately. Several representations exist in ENDF/ACE for correlated +angle-energy distributions. + +Kalbach-Mann Correlated Scattering +++++++++++++++++++++++++++++++++++ + +This law is very similar to the uncorrelated continuous tabular energy +distribution except now the outgoing angle of the neutron is correlated to the +outgoing energy and is not sampled from a separate distribution. For each +incident neutron energy :math:`E_i` tabulated, there is an array of precompound +factors :math:`R_{i,j}` and angular distribution slopes :math:`A_{i,j}` +corresponding to each outgoing energy bin :math:`j` in addition to the outgoing +energies and distribution functions as in :ref:`continuous-tabular`. + +The calculation of the outgoing energy of the neutron proceeds exactly the same +as in the algorithm described in :ref:`continuous-tabular`. In that algorithm, +we found an interpolation factor :math:`f`, statistically sampled an incoming +energy bin :math:`\ell`, and sampled an outgoing energy bin :math:`j` based on +the tabulated cumulative distribution function. Once the outgoing energy has +been determined with equation :eq:`continuous-eout`, we then need to calculate +the outgoing angle based on the tabulated Kalbach-Mann parameters. These +parameters themselves are subject to either histogram or linear-linear +interpolation on the outgoing energy grid. For histogram interpolation, the +parameters are + +.. math:: + :label: KM-parameters-histogram + + R = R_{\ell,j} \\ + A = A_{\ell,j}. + +If linear-linear interpolation is specified, the parameters are + +.. math:: + :label: KM-parameters-linlin + + R = R_{\ell,j} + \frac{\hat{E} - E_{\ell,j}}{E_{\ell,j+1} - E_{\ell,j}} ( + R_{\ell,j+1} - R_{\ell,j} ) \\ + A = A_{\ell,j} + \frac{\hat{E} - E_{\ell,j}}{E_{\ell,j+1} - E_{\ell,j}} ( + A_{\ell,j+1} - A_{\ell,j} ) + +where :math:`\hat{E}` is defined in equation :eq:`energy-linlin`. With the +parameters determined, the probability distribution function for the cosine of +the scattering angle is + +.. math:: + :label: KM-pdf-angle + + p(\mu) d\mu = \frac{A}{2 \sinh (A)} \left [ \cosh (A\mu) + R \sinh (A\mu) + \right ] d\mu. + +The rules for sampling this probability distribution function can be derived +based on rules C39 and C40 in the `Monte Carlo Sampler`_. First, we sample two +random numbers :math:`\xi_3, \xi_4` on the unit interval. If :math:`\xi_3 > R` +then the outgoing angle is + +.. math:: + :label: KM-angle-1 + + \mu = \frac{1}{A} \ln \left ( T + \sqrt{T^2 + 1} \right ) + +where :math:`T = (2 \xi_4 - 1) \sinh (A)`. If :math:`\xi_3 \le R`, then the +outgoing angle is + +.. math:: + :label: KM-angle-2 + + \mu = \frac{1}{A} \ln \left ( \xi_4 e^A + (1 - \xi_4) e^{-A} \right ). + +.. _correlated-energy-angle: + +Correlated Energy and Angle Distribution +++++++++++++++++++++++++++++++++++++++++ + +This distribution is very similar to a Kalbach-Mann distribution in the sense +that the outgoing angle of the neutron is correlated to the outgoing energy and +is not sampled from a separate distribution. In this case though, rather than +being determined from an analytical distribution function, the cosine of the +scattering angle is determined from a tabulated distribution. For each incident +energy :math:`i` and outgoing energy :math:`j`, there is a tabulated angular +distribution. + +The calculation of the outgoing energy of the neutron proceeds exactly the same +as in the algorithm described in :ref:`continuous-tabular`. In that algorithm, +we found an interpolation factor :math:`f`, statistically sampled an incoming +energy bin :math:`\ell`, and sampled an outgoing energy bin :math:`j` based on +the tabulated cumulative distribution function. Once the outgoing energy has +been determined with equation :eq:`continuous-eout`, we then need to decide +which angular distribution to use. If histogram interpolation was used on the +outgoing energy bins, then we use the angular distribution corresponding to +incoming energy bin :math:`\ell` and outgoing energy bin :math:`j`. If +linear-linear interpolation was used on the outgoing energy bins, then we use +the whichever angular distribution was closer to the sampled value of the +cumulative distribution function for the outgoing energy. The actual algorithm +used to sample the chosen tabular angular distribution has been previously +described in :ref:`angle-tabular`. + +N-Body Phase Space Distribution ++++++++++++++++++++++++++++++++ + +Reactions in which there are more than two products of similar masses are +sometimes best treated by using what's known as an N-body phase +distribution. This distribution has the following probability density function +for outgoing energy and angle of the :math:`i`-th particle in the center-of-mass +system: + +.. math:: + :label: n-body-pdf + + p_i(\mu, E') dE' d\mu = C_n \sqrt{E'} (E_i^{max} - E')^{(3n/2) - 4} dE' d\mu + +where :math:`n` is the number of outgoing particles, :math:`C_n` is a +normalization constant, :math:`E_i^{max}` is the maximum center-of-mass energy +for particle :math:`i`, and :math:`E'` is the outgoing energy. We see in +equation :eq:`n-body-pdf` that the angle is simply isotropic in the +center-of-mass system. The algorithm for sampling the outgoing energy is based +on algorithms R28, C45, and C64 in the `Monte Carlo Sampler`_. First we +calculate the maximum energy in the center-of-mass using the following equation: + +.. math:: + :label: n-body-emax + + E_i^{max} = \frac{A_p - 1}{A_p} \left ( \frac{A}{A+1} E + Q \right ) + +where :math:`A_p` is the total mass of the outgoing particles in neutron masses, +:math:`A` is the mass of the original target nucleus in neutron masses, and +:math:`Q` is the Q-value of the reaction. Next we sample a value :math:`x` from +a Maxwell distribution with a nuclear temperature of one using the algorithm +outlined in :ref:`maxwell`. We then need to determine a value :math:`y` that +will depend on how many outgoing particles there are. For :math:`n = 3`, we +simply sample another Maxwell distribution with unity nuclear temperature. For +:math:`n = 4`, we use the equation + +.. math:: + :label: n-body-y4 + + y = -\ln ( \xi_1 \xi_2 \xi_3 ) + +where :math:`\xi_i` are random numbers sampled on the interval +:math:`[0,1)`. For :math:`n = 5`, we use the equation + +.. math:: + :label: n-body-y5 + + y = -\ln ( \xi_1 \xi_2 \xi_3 \xi_4 ) - \ln ( \xi_5 ) \cos^2 \left ( + \frac{\pi}{2} \xi_6 \right ) + +After :math:`x` and :math:`y` have been determined, the outgoing energy is then +calculated as + +.. math:: + :label: n-body-energy + + E' = \frac{x}{x + y} E_i^{max} + +There are two important notes to make regarding the N-body phase space +distribution. First, the documentation (and code) for MCNP5-1.60 has a mistake +in the algorithm for :math:`n = 4`. That being said, there are no existing +nuclear data evaluations which use an N-body phase space distribution with +:math:`n = 4`, so the error would not affect any calculations. In the +ENDF/B-VII.1 nuclear data evaluation, only one reaction uses an N-body phase +space distribution at all, the :math:`(n,2n)` reaction with H-2. + +.. _transform-coordinates: + +------------------------------------- +Transforming a Particle's Coordinates +------------------------------------- + +Since all the multi-group data exists in the laboratory frame of reference, this +section does not apply to the multi-group mode. + +Once the cosine of the scattering angle :math:`\mu` has been sampled either from +a angle distribution or a correlated angle-energy distribution, we are still +left with the task of transforming the particle's coordinates. If the outgoing +energy and scattering cosine were given in the center-of-mass system, then we +first need to transform these into the laboratory system. The relationship +between the outgoing energy in center-of-mass and laboratory is + +.. math:: + :label: energy-com-to-lab + + E' = E'_{cm} + \frac{E + 2\mu_{cm} (A + 1) \sqrt{EE'_{cm}}}{(A+1)^2}. + +where :math:`E'_{cm}` is the outgoing energy in the center-of-mass system, +:math:`\mu_{cm}` is the scattering cosine in the center-of-mass system, +:math:`E'` is the outgoing energy in the laboratory system, and :math:`E` is the +incident neutron energy. The relationship between the scattering cosine in +center-of-mass and laboratory is + +.. math:: + :label: angle-com-to-lab + + \mu = \mu_{cm} \sqrt{\frac{E'_{cm}}{E'}} + \frac{1}{A + 1} + \sqrt{\frac{E}{E'}} + +where :math:`\mu` is the scattering cosine in the laboratory system. The +scattering cosine still only tells us the cosine of the angle between the +original direction of the particle and the new direction of the particle. If we +express the pre-collision direction of the particle as :math:`\mathbf{\Omega} = +(u,v,w)` and the post-collision direction of the particle as +:math:`\mathbf{\Omega}' = (u',v',w')`, it is possible to relate the pre- and +post-collision components. We first need to uniformly sample an azimuthal angle +:math:`\phi` in :math:`[0, 2\pi)`. After the azimuthal angle has been sampled, +the post-collision direction is calculated as + +.. math:: + :label: post-collision-angle + + u' = \mu u + \frac{\sqrt{1 - \mu^2} ( uw \cos\phi - v \sin\phi )}{\sqrt{1 - + w^2}} \\ + + v' = \mu v + \frac{\sqrt{1 - \mu^2} ( vw \cos\phi + u \sin\phi )}{\sqrt{1 - + w^2}} \\ + + w' = \mu w - \sqrt{1 - \mu^2} \sqrt{1 - w^2} \cos\phi. + +.. _freegas: + +------------------------------------------ +Effect of Thermal Motion on Cross Sections +------------------------------------------ + +Since all the multi-group data should be generated with thermal scattering +treatments already, this section does not apply to the multi-group mode. + +When a neutron scatters off of a nucleus, it may often be assumed that the +target nucleus is at rest. However, the target nucleus will have motion +associated with its thermal vibration, even at absolute zero (This is due to the +zero-point energy arising from quantum mechanical considerations). Thus, the +velocity of the neutron relative to the target nucleus is in general not the +same as the velocity of the neutron entering the collision. + +The effect of the thermal motion on the interaction probability can be written +as + +.. math:: + :label: doppler-broaden + + v_n \bar{\sigma} (v_n, T) = \int d\mathbf{v}_T v_r \sigma(v_r) + M (\mathbf{v}_T) + +where :math:`v_n` is the magnitude of the velocity of the neutron, +:math:`\bar{\sigma}` is an effective cross section, :math:`T` is the temperature +of the target material, :math:`\mathbf{v}_T` is the velocity of the target +nucleus, :math:`v_r = || \mathbf{v}_n - \mathbf{v}_T ||` is the magnitude of the +relative velocity, :math:`\sigma` is the cross section at 0 K, and :math:`M +(\mathbf{v}_T)` is the probability distribution for the target nucleus velocity +at temperature :math:`T` (a Maxwellian). In a Monte Carlo code, one must account +for the effect of the thermal motion on both the integrated cross section as +well as secondary angle and energy distributions. For integrated cross sections, +it is possible to calculate thermally-averaged cross sections by applying a +kernel Doppler broadening algorithm to data at 0 K (or some temperature lower +than the desired temperature). The most ubiquitous algorithm for this purpose is +the `SIGMA1 method`_ developed by Red Cullen and subsequently refined by +others. This method is used in the NJOY_ and PREPRO_ data processing codes. + +The effect of thermal motion on secondary angle and energy distributions can be +accounted for on-the-fly in a Monte Carlo simulation. We must first qualify +where it is actually used however. All threshold reactions are treated as being +independent of temperature, and therefore they are not Doppler broadened in NJOY +and no special procedure is used to adjust the secondary angle and energy +distributions. The only non-threshold reactions with secondary neutrons are +elastic scattering and fission. For fission, it is assumed that the neutrons are +emitted isotropically (this is not strictly true, but is nevertheless a good +approximation). This leaves only elastic scattering that needs a special thermal +treatment for secondary distributions. + +Fortunately, it is possible to directly sample the velocity of the target +nuclide and then use it directly in the kinematic calculations. However, this +calculation is a bit more nuanced than it might seem at first glance. One might +be tempted to simply sample a Maxwellian distribution for the velocity of the +target nuclide. Careful inspection of equation :eq:`doppler-broaden` however +tells us that target velocities that produce relative velocities which +correspond to high cross sections will have a greater contribution to the +effective reaction rate. This is most important when the velocity of the +incoming neutron is close to a resonance. For example, if the neutron's velocity +corresponds to a trough in a resonance elastic scattering cross section, a very +small target velocity can cause the relative velocity to correspond to the peak +of the resonance, thus making a disproportionate contribution to the reaction +rate. The conclusion is that if we are to sample a target velocity in the Monte +Carlo code, it must be done in such a way that preserves the thermally-averaged +reaction rate as per equation :eq:`doppler-broaden`. + +The method by which most Monte Carlo codes sample the target velocity for use in +elastic scattering kinematics is outlined in detail by [Gelbard]_. The +derivation here largely follows that of Gelbard. Let us first write the reaction +rate as a function of the velocity of the target nucleus: + +.. math:: + :label: reaction-rate + + R(\mathbf{v}_T) = || \mathbf{v}_n - \mathbf{v}_T || \sigma ( || + \mathbf{v}_n - \mathbf{v}_T || ) M ( \mathbf{v}_T ) + +where :math:`R` is the reaction rate. Note that this is just the right-hand side +of equation :eq:`doppler-broaden`. Based on the discussion above, we want to +construct a probability distribution function for sampling the target velocity +to preserve the reaction rate -- this is different from the overall probability +distribution function for the target velocity, :math:`M ( \mathbf{v}_T )`. This +probability distribution function can be found by integrating equation +:eq:`reaction-rate` to obtain a normalization factor: + +.. math:: + :label: target-pdf-1 + + p( \mathbf{v}_T ) d\mathbf{v}_T = \frac{R(\mathbf{v}_T) d\mathbf{v}_T}{\int + d\mathbf{v}_T \, R(\mathbf{v}_T)} + +Let us call the normalization factor in the denominator of equation +:eq:`target-pdf-1` :math:`C`. + + +Constant Cross Section Model +---------------------------- + +It is often assumed that :math:`\sigma (v_r)` is constant over the range of +relative velocities of interest. This is a good assumption for almost all cases +since the elastic scattering cross section varies slowly with velocity for light +nuclei, and for heavy nuclei where large variations can occur due to resonance +scattering, the moderating effect is rather small. Nonetheless, this assumption +may cause incorrect answers in systems with low-lying resonances that can cause +a significant amount of up-scatter that would be ignored by this assumption +(e.g. U-238 in commercial light-water reactors). We will revisit this assumption +later in :ref:`energy_dependent_xs_model`. For now, continuing with the +assumption, we write :math:`\sigma (v_r) = \sigma_s` which simplifies +:eq:`target-pdf-1` to + +.. math:: + :label: target-pdf-2 + + p( \mathbf{v}_T ) d\mathbf{v}_T = \frac{\sigma_s}{C} || \mathbf{v}_n - + \mathbf{v}_T || M ( \mathbf{v}_T ) d\mathbf{v}_T + +The Maxwellian distribution in velocity is + +.. math:: + :label: maxwellian-velocity + + M (\mathbf{v}_T) = \left ( \frac{m}{2\pi kT} \right )^{3/2} \exp \left ( + \frac{-m || \mathbf{v}_T^2 ||}{2kT} \right ) + +where :math:`m` is the mass of the target nucleus and :math:`k` is Boltzmann's +constant. Notice here that the term in the exponential is dependent only on the +speed of the target, not on the actual direction. Thus, we can change the +Maxwellian into a distribution for speed rather than velocity. The differential +element of velocity is + +.. math:: + :label: differential-velocity + + d\mathbf{v}_T = v_T^2 dv_T d\mu d\phi + +Let us define the Maxwellian distribution in speed as + +.. math:: + :label: maxwellian-speed + + M (v_T) dv_T = \int_{-1}^1 d\mu \int_{0}^{2\pi} d\phi \, dv_T \, v_T^2 + M(\mathbf{v}_T) = \sqrt{ \frac{2}{\pi} \left ( \frac{m}{kT} \right )^3} + v_T^2 \exp \left ( \frac{-m v_T}{2kT} \right ) dv_T. + +To simplify things a bit, we'll define a parameter + +.. math:: + :label: maxwellian-beta + + \beta = \sqrt{\frac{m}{2kT}}. + +Substituting equation :eq:`maxwellian-beta` into equation +:eq:`maxwellian-speed`, we obtain + +.. math:: + :label: maxwellian-speed2 + + M (v_T) dv_T = \frac{4}{\sqrt{\pi}} \beta^3 v_T^2 \exp \left ( -\beta^2 + v_T^2 \right ) dv_T. + +Now, changing variables in equation :eq:`target-pdf-2` by using the result from +equation :eq:`maxwellian-speed`, our new probability distribution function is + +.. math:: + :label: target-pdf-3 + + p( v_T, \mu ) dv_T d\mu = \frac{4\sigma_s}{\sqrt{\pi}C'} || \mathbf{v}_n - + \mathbf{v}_T || \beta^3 v_T^2 \exp \left ( -\beta^2 v_T^2 \right ) dv_T d\mu + +Again, the Maxwellian distribution for the speed of the target nucleus has no +dependence on the angle between the neutron and target velocity vectors. Thus, +only the term :math:`|| \mathbf{v}_n - \mathbf{v}_T ||` imposes any constraint +on the allowed angle. Our last task is to take that term and write it in terms +of magnitudes of the velocity vectors and the angle rather than the vectors +themselves. We can establish this relation based on the law of cosines which +tells us that + +.. math:: + :label: lawcosine + + 2 v_n v_T \mu = v_n^2 + v_T^2 - v_r^2. + +Thus, we can infer that + +.. math:: + :label: change-terms + + || \mathbf{v}_n - \mathbf{v}_T || = || \mathbf{v}_r || = v_r = \sqrt{v_n^2 + + v_T^2 - 2v_n v_T \mu}. + +Inserting equation :eq:`change-terms` into :eq:`target-pdf-3`, we obtain + +.. math:: + :label: target-pdf-4 + + p( v_T, \mu ) dv_T d\mu = \frac{4\sigma_s}{\sqrt{\pi}C'} \sqrt{v_n^2 + + v_T^2 - 2v_n v_T \mu} \beta^3 v_T^2 \exp \left ( -\beta^2 v_T^2 \right ) + dv_T d\mu + +This expression is still quite formidable and does not lend itself to any +natural sampling scheme. We can divide this probability distribution into two +parts as such: + +.. math:: + :label: divide-pdf + + \begin{aligned} + p(v_T, \mu) &= f_1(v_T, \mu) f_2(v_T) \\ + f_1(v_T, \mu) &= \frac{4\sigma_s}{\sqrt{\pi} C'} \frac{ \sqrt{v_n^2 + + v_T^2 - 2v_n v_T \mu}}{v_n + v_T} \\ + f_2(v_T) &= (v_n + v_T) \beta^3 v_T^2 \exp \left ( -\beta^2 v_T^2 \right ). + \end{aligned} + +In general, any probability distribution function of the form :math:`p(x) = +f_1(x) f_2(x)` with :math:`f_1(x)` bounded can be sampled by sampling +:math:`x'` from the distribution + +.. math:: + :label: freegas-f2 + + q(x) dx = \frac{f_2(x) dx}{\int f_2(x) dx} + +and accepting it with probability + +.. math:: + :label: freegas-accept + + p_{accept} = \frac{f_1(x')}{\max f_1(x)} + +The reason for dividing and multiplying the terms by :math:`v_n + v_T` is to +ensure that the first term is bounded. In general, :math:`|| \mathbf{v}_n - +\mathbf{v}_T ||` can take on arbitrarily large values, but if we divide it by +its maximum value :math:`v_n + v_T`, then it ensures that the function will be +bounded. We now must come up with a sampling scheme for equation +:eq:`freegas-f2`. To determine :math:`q(v_T)`, we need to integrate :math:`f_2` +in equation :eq:`divide-pdf`. Doing so we find that + +.. math:: + :label: integrate-f2 + + \int_0^{\infty} dv_T (v_n + v_T) \beta^3 v_T^2 \exp \left ( -\beta^2 v_T^2 + \right ) = \frac{1}{4\beta} \left ( \sqrt{\pi} \beta v_n + 2 \right ). + +Thus, we need to sample the probability distribution function + +.. math:: + :label: freegas-f2-2 + + q(v_T) dv_T = \left ( \frac{4\beta^2 v_n v_T^2}{\sqrt{\pi} \beta v_n + 2} + + \frac{4\beta^4 v_T^3}{\sqrt{\pi} \beta v_n + 2} \right ) exp \left ( + -\beta^2 v_T^2 \right ). + +Now, let us do a change of variables with the following definitions + +.. math:: + :label: beta-to-x + + x = \beta v_T \\ + y = \beta v_n. + +Substituting equation :eq:`beta-to-x` into equation :eq:`freegas-f2-2` along +with :math:`dx = \beta dv_T` and doing some crafty rearranging of terms yields + +.. math:: + :label: freegas-f2-3 + + q(x) dx = \left [ \left ( \frac{\sqrt{\pi} y}{\sqrt{\pi} y + 2} \right ) + \frac{4}{\sqrt{\pi}} x^2 e^{-x^2} + \left ( \frac{2}{\sqrt{\pi} y + 2} + \right ) 2x^3 e^{-x^2} \right ] dx. + +It's important to make note of the following two facts. First, the terms outside +the parentheses are properly normalized probability distribution functions that +can be sampled directly. Secondly, the terms inside the parentheses are always +less than unity. Thus, the sampling scheme for :math:`q(x)` is as follows. We +sample a random number :math:`\xi_1` on the interval :math:`[0,1)` and if + +.. math:: + :label: freegas-alpha + + \xi_1 < \frac{2}{\sqrt{\pi} y + 2} + +then we sample the probability distribution :math:`2x^3 e^{-x^2}` for :math:`x` +using rule C49 in the `Monte Carlo Sampler`_ which we can then use to determine +the speed of the target nucleus :math:`v_T` from equation +:eq:`beta-to-x`. Otherwise, we sample the probability distribution +:math:`\frac{4}{\sqrt{\pi}} x^2 e^{-x^2}` for :math:`x` using rule C61 in the +`Monte Carlo Sampler`_. + +With a target speed sampled, we must then decide whether to accept it based on +the probability in equation :eq:`freegas-accept`. The cosine can be sampled +isotropically as :math:`\mu = 2\xi_2 - 1` where :math:`\xi_2` is a random number +on the unit interval. Since the maximum value of :math:`f_1(v_T, \mu)` is +:math:`4\sigma_s / \sqrt{\pi} C'`, we then sample another random number +:math:`\xi_3` and accept the sampled target speed and cosine if + +.. math:: + :label: freegas-accept-2 + + \xi_3 < \frac{\sqrt{v_n^2 + v_T^2 - 2 v_n v_T \mu}}{v_n + v_T}. + +If is not accepted, then we repeat the process and resample a target speed and +cosine until a combination is found that satisfies equation +:eq:`freegas-accept-2`. + +.. _energy_dependent_xs_model: + +Energy-Dependent Cross Section Model +------------------------------------ + +As was noted earlier, assuming that the elastic scattering cross section is +constant in :eq:`reaction-rate` is not strictly correct, especially when +low-lying resonances are present in the cross sections for heavy nuclides. To +correctly account for energy dependence of the scattering cross section entails +performing another rejection step. The most common method is to sample +:math:`\mu` and :math:`v_T` as in the constant cross section approximation and +then perform a rejection on the ratio of the 0 K elastic scattering cross +section at the relative velocity to the maximum 0 K elastic scattering cross +section over the range of velocities considered: + +.. math:: + :label: dbrc + + p_{dbrc} = \frac{\sigma_s(v_r)}{\sigma_{s,max}} + +where it should be noted that the maximum is taken over the range :math:`[v_n - +4/\beta, 4_n + 4\beta]`. This method is known as Doppler broadening rejection +correction (DBRC) and was first introduced by `Becker et al.`_. OpenMC has an +implementation of DBRC as well as an accelerated sampling method that samples the `relative velocity`_ directly. + +.. _Becker et al.: https://doi.org/10.1016/j.anucene.2008.12.001 +.. _relative velocity: https://doi.org/10.1016/j.anucene.2017.12.044 + +.. _sab_tables: + +------------ +|sab| Tables +------------ + +Note that |sab| tables are only applicable to continuous-energy transport. + +For neutrons with thermal energies, generally less than 4 eV, the kinematics of +scattering can be affected by chemical binding and crystalline effects of the +target molecule. If these effects are not accounted for in a simulation, the +reported results may be highly inaccurate. There is no general analytic +treatment for the scattering kinematics at low energies, and thus when nuclear +data is processed for use in a Monte Carlo code, special tables are created that +give cross sections and secondary angle/energy distributions for thermal +scattering that account for thermal binding effects. These tables are mainly +used for moderating materials such as light or heavy water, graphite, hydrogen +in ZrH, beryllium, etc. + +The theory behind |sab| is rooted in quantum mechanics and is quite +complex. Those interested in first principles derivations for formulae relating +to |sab| tables should be referred to the excellent books by [Williams]_ and +[Squires]_. For our purposes here, we will focus only on the use of already +processed data as it appears in the ACE format. + +Each |sab| table can contain the following: + +- Thermal inelastic scattering cross section; +- Thermal elastic scattering cross section; +- Correlated energy-angle distributions for thermal inelastic and elastic + scattering. + +Note that when we refer to "inelastic" and "elastic" scattering now, we are +actually using these terms with respect to the *scattering system*. Thermal +inelastic scattering means that the scattering system is left in an excited +state; no particular nucleus is left in an excited state as would be the case +for inelastic level scattering. In a crystalline material, the excitation of the +scattering could correspond to the production of phonons. In a molecule, it +could correspond to the excitation of rotational or vibrational modes. + +Both thermal elastic and thermal inelastic scattering are generally divided into +incoherent and coherent parts. Coherent elastic scattering refers to scattering +in crystalline solids like graphite or beryllium. These cross sections are +characterized by the presence of *Bragg edges* that relate to the crystal +structure of the scattering material. Incoherent elastic scattering refers to +scattering in hydrogenous solids such as polyethylene. As it occurs in ACE data, +thermal inelastic scattering includes both coherent and incoherent effects and +is dominant for most other materials including hydrogen in water. + +Calculating Integrated Cross Sections +------------------------------------- + +The first aspect of using |sab| tables is calculating cross sections to replace +the data that would normally appear on the incident neutron data, which do not +account for thermal binding effects. For incoherent inelastic scattering, the +cross section is stored as a linearly interpolable function on a specified +energy grid. For coherent elastic data, the cross section can be expressed as + +.. math:: + :label: coherent-elastic-xs + + \sigma(E) = \frac{1}{E} \sum_{E_i < E} s_i + +where :math:`E_i` are the energies of the Bragg edges and :math:`s_i` are +related to crystallographic structure factors. Since the functional form of the +cross section is just 1/E and the proportionality constant changes only at Bragg +edges, the proportionality constants are stored and then the cross section can +be calculated analytically based on equation :eq:`coherent-elastic-xs`. For +incoherent elastic data, the cross section can be expressed as + +.. math:: + :label: incoherent-elastic-xs + + \sigma(E) = \frac{\sigma_b}{2} \left( \frac{1 - e^{-4EW'}}{2EW'} \right) + +where :math:`\sigma_b` is the characteristic bound cross section and :math:`W'` +is the Debye-Waller integral divided by the atomic mass. + +Outgoing Angle for Coherent Elastic Scattering +---------------------------------------------- + +Another aspect of using |sab| tables is determining the outgoing energy and +angle of the neutron after scattering. For incoherent and coherent elastic +scattering, the energy of the neutron does not actually change, but the angle +does change. For coherent elastic scattering, the angle will depend on which +Bragg edge scattered the neutron. The probability that edge :math:`i` will +scatter then neutron is given by + +.. math:: + :label: coherent-elastic-probability + + \frac{s_i}{\sum_j s_j}. + +After a Bragg edge has been sampled, the cosine of the angle of scattering is +given analytically by + +.. math:: + :label: coherent-elastic-angle + + \mu = 1 - \frac{2E_i}{E} + +where :math:`E_i` is the energy of the Bragg edge that scattered the neutron. + +.. _incoherent elastic angle: + +Outgoing Angle for Incoherent Elastic Scattering +------------------------------------------------ + +For incoherent elastic scattering, OpenMC has two methods for calculating the +cosine of the angle of scattering. The first method uses the Debye-Waller +integral, :math:`W'`, and the characteristic bound cross section as given +directly in an ENDF-6 formatted file. In this case, the cosine of the angle of +scattering can be sampled by inverting equation 7.4 from the `ENDF-6 Format`_: + +.. math:: + :label: incoherent-elastic-mu-exact + + \mu = \frac{1}{c} \log \left( 1 + \xi \left( e^{2c} - 1 \right) \right) - 1 + +where :math:`\xi` is a random number sampled on unit interval and :math:`c = +2EW'`. In the second method, the probability distribution for the cosine of the +angle of scattering is represented as a series of equally-likely discrete +cosines :math:`\mu_{i,j}` for each incoming energy :math:`E_i` on the thermal +elastic energy grid. First the outgoing angle bin :math:`j` is sampled. Then, if +the incoming energy of the neutron satisfies :math:`E_i < E < E_{i+1}` the +cosine of the angle of scattering is + +.. math:: + :label: incoherent-elastic-angle + + \mu' = \mu_{i,j} + f (\mu_{i+1,j} - \mu_{i,j}) + +where the interpolation factor is defined as + +.. math:: + :label: sab-interpolation-factor + + f = \frac{E - E_i}{E_{i+1} - E_i}. + +To better represent the true, continuous nature of the cosine distribution, the +sampled value of :math:`mu'` is then "smeared" based on the neighboring values. +First, values of :math:`\mu` are calculated for outgoing angle bins :math:`j-1` +and :math:`j+1`: + +.. math:: + :label: incoherent-elastic-smear1 + + \mu_\text{left} = \mu_{i,j-1} + f (\mu_{i+1,j-1} - \mu_{i,j-1}) \\ + + \mu_\text{right} = \mu_{i,j+1} + f (\mu_{i+1,j+1} - \mu_{i,j+1}). + +Then, a final cosine is calculated as: + +.. math:: + :label: incoherent-elastic-smear2 + + \mu = \mu' + \min (\mu - \mu_\text{left}, \mu + \mu_\text{right} ) \cdot + \left( \xi - \frac{1}{2} \right) + +where :math:`\xi` is again a random number sampled on the unit interval. Care +must be taken to ensure that :math:`\mu` does not fall outside the interval +:math:`[-1,1]`. + +Outgoing Energy and Angle for Inelastic Scattering +-------------------------------------------------- + +Each |sab| table provides a correlated angle-energy secondary distribution for +neutron thermal inelastic scattering. There are three representations used +in the ACE thermal scattering data: equiprobable discrete outgoing +energies, non-uniform yet still discrete outgoing energies, and continuous +outgoing energies with corresponding probability and cumulative distribution +functions provided in tabular format. These three representations all +represent the angular distribution in a common format, using a series of +discrete equiprobable outgoing cosines. + +Equi-Probable Outgoing Energies ++++++++++++++++++++++++++++++++ + +If the thermal data was processed with :math:`iwt = 1` in NJOY, then the +outgoing energy spectra is represented in the ACE data as a set of discrete and +equiprobable outgoing energies. The procedure to determine the outgoing energy +and angle is as such. First, the interpolation factor is determined from +equation :eq:`sab-interpolation-factor`. Then, an outgoing energy bin is +sampled from a uniform distribution and then interpolated between values +corresponding to neighboring incoming energies: + +.. math:: + :label: inelastic-energy + + E = E_{i,j} + f (E_{i+1,j} - E_{i,j}) + +where :math:`E_{i,j}` is the j-th outgoing energy corresponding to the i-th +incoming energy. For each combination of incoming and outgoing energies, there +is a series equiprobable outgoing cosines. An outgoing cosine bin is sampled +uniformly and then the final cosine is interpolated on the incoming energy grid: + +.. math:: + :label: inelastic-angle + + \mu = \mu_{i,j,k} + f (\mu_{i+1,j,k} - \mu_{i,j,k}) + +where :math:`\mu_{i,j,k}` is the k-th outgoing cosine corresponding to the j-th +outgoing energy and the i-th incoming energy. + +Skewed Equi-Probable Outgoing Energies +++++++++++++++++++++++++++++++++++++++ + +If the thermal data was processed with :math:`iwt=0` in NJOY, then the +outgoing energy spectra is represented in the ACE data according to the +following: the first and last outgoing energies have a relative probability of +1, the second and second-to-last energies have a relative probability of 4, and +all other energies have a relative probability of 10. The procedure to +determine the outgoing energy and angle is similar to the method discussed +above, except that the sampled probability distribution is now skewed +accordingly. + +Continuous Outgoing Energies +++++++++++++++++++++++++++++ + +If the thermal data was processed with :math:`iwt=2` in NJOY, then the outgoing +energy spectra is represented by a continuous outgoing energy spectra in tabular +form with linear-linear interpolation. The sampling of the outgoing energy +portion of this format is very similar to :ref:`correlated-energy-angle`, but +the sampling of the correlated angle is performed as it was in the other two +representations discussed in this sub-section. In the Law 61 algorithm, we +found an interpolation factor :math:`f`, statistically sampled an incoming +energy bin :math:`\ell`, and sampled an outgoing energy bin :math:`j` based on +the tabulated cumulative distribution function. Once the outgoing energy has +been determined with equation :eq:`continuous-eout`, we then need to decide +which angular distribution data to use. Like the linear-linear interpolation +case in Law 61, the angular distribution closest to the sampled value of the +cumulative distribution function for the outgoing energy is utilized. The +actual algorithm utilized to sample the outgoing angle is shown in equation +:eq:`inelastic-angle`. As in the case of incoherent elastic scattering with +discrete cosine bins, the sampled cosine is :ref:`smeared ` over neighboring angle bins to better approximate a continuous +distribution. + +.. _probability_tables: + +---------------------------------------------- +Unresolved Resonance Region Probability Tables +---------------------------------------------- + +Note that unresolved resonance treatments are only applicable to +continuous-energy transport. + +In the unresolved resonance energy range, resonances may be so closely spaced +that it is not possible for experimental measurements to resolve all +resonances. To properly account for self-shielding in this energy range, OpenMC +uses the `probability table method`_. For most thermal reactors, the use +of probability tables will not significantly affect problem results. However, +for some fast reactors and other problems with an appreciable flux spectrum in +the unresolved resonance range, not using probability tables may lead to +incorrect results. + +Probability tables in the ACE format are generated from the UNRESR module in +NJOY following the method of Levitt. A similar method employed for the RACER and +MC21_ Monte Carlo codes is described in a paper by `Sutton and Brown`_. For the +discussion here, we will focus only on use of the probability table table as it +appears in the ACE format. + +Each probability table for a nuclide contains the following information at a +number of incoming energies within the unresolved resonance range: + +- Cumulative probabilities for cross section bands; +- Total cross section (or factor) in each band; +- Elastic scattering cross section (or factor) in each band; +- Fission cross section (or factor) in each band; +- :math:`(n,\gamma)` cross section (or factor) in each band; and +- Neutron heating number (or factor) in each band. + +It should be noted that unresolved resonance probability tables affect only +integrated cross sections and no extra data need be given for secondary +angle/energy distributions. Secondary distributions for elastic and inelastic +scattering would be specified whether or not probability tables were present. + +The procedure for determining cross sections in the unresolved range using +probability tables is as follows. First, the bounding incoming energies are +determined, i.e. find :math:`i` such that :math:`E_i < E < E_{i+1}`. We then +sample a cross section band :math:`j` using the cumulative probabilities for +table :math:`i`. This allows us to then calculate the elastic, fission, and +capture cross sections from the probability tables interpolating between +neighboring incoming energies. If interpolation is specified, then +the cross sections are calculated as + +.. math:: + :label: ptables-linlin + + \sigma = \sigma_{i,j} + f (\sigma_{i+1,j} - \sigma{i,j}) + +where :math:`\sigma_{i,j}` is the j-th band cross section corresponding to the +i-th incoming neutron energy and :math:`f` is the interpolation factor defined +in the same manner as :eq:`sab-interpolation-factor`. If logarithmic +interpolation is specified, the cross sections are calculated as + +.. math:: + :label: ptables-loglog + + \sigma = \exp \left ( \log \sigma_{i,j} + f \log + \frac{\sigma_{i+1,j}}{\sigma_{i,j}} \right ) + +where the interpolation factor is now defined as + +.. math:: + :label: log-interpolation-factor + + f = \frac{\log \frac{E}{E_i}}{\log \frac{E_{i+1}}{E_i}}. + +A flag is also present in the probability table that specifies whether an +inelastic cross section should be calculated. If so, this is done from a normal +reaction cross section (either MT=51 or a special MT). Finally, if the +cross sections defined are above are specified to be factors and not true +cross sections, they are multiplied by the underlying smooth cross section in +the unresolved range to get the actual cross sections. Lastly, the total cross +section is calculated as the sum of the elastic, fission, capture, and inelastic +cross sections. + +----------------------------- +Variance Reduction Techniques +----------------------------- + +.. _survival_biasing: + +Survival Biasing +---------------- + +In problems with highly absorbing materials, a large fraction of neutrons may be +killed through absorption reactions, thus leading to tallies with very few +scoring events. To remedy this situation, an algorithm known as *survival +biasing* or *implicit absorption* (or sometimes *implicit capture*, even though +this is a misnomer) is commonly used. + +In survival biasing, absorption reactions are prohibited from occurring and +instead, at every collision, the weight of neutron is reduced by probability of +absorption occurring, i.e. + +.. math:: + :label: survival-biasing-weight + + w' = w \left ( 1 - \frac{\sigma_a (E)}{\sigma_t (E)} \right ) + +where :math:`w'` is the weight of the neutron after adjustment and :math:`w` is +the weight of the neutron before adjustment. A few other things need to be +handled differently if survival biasing is turned on. Although fission reactions +never actually occur with survival biasing, we still need to create fission +sites to serve as source sites for the next generation in the method of +successive generations. The algorithm for sampling fission sites is the same as +that described in :ref:`fission`. The only difference is in equation +:eq:`fission-neutrons`. We now need to produce + +.. math:: + :label: fission-neutrons-survival + + \nu = \frac{w}{k} \frac{\nu_t \sigma_f(E)}{\sigma_t (E)} + +fission sites, where :math:`w` is the weight of the neutron before being +adjusted. One should note this is just the expected number of neutrons produced +*per collision* rather than the expected number of neutrons produced given that +fission has already occurred. + +Additionally, since survival biasing can reduce the weight of the neutron to +very low values, it is always used in conjunction with a weight cutoff and +Russian rouletting. Two user adjustable parameters :math:`w_c` and :math:`w_s` +are given which are the weight below which neutrons should undergo Russian +roulette and the weight should they survive Russian roulette. The algorithm for +Russian rouletting is as follows. After a collision if :math:`w < w_c`, then the +neutron is killed with probability :math:`1 - w/w_s`. If it survives, the weight +is set equal to :math:`w_s`. One can confirm that the average weight following +Russian roulette is simply :math:`w`, so the game can be considered "fair". By +default, the cutoff weight in OpenMC is :math:`w_c = 0.25` and the survival +weight is :math:`w_s = 1.0`. These parameters vary from one Monte Carlo code to +another. + +Weight Windows +-------------- + +In fixed source problems, it can often be difficult to obtain sufficiently low +variance on tallies in regions that are far from the source. The `weight window +method `_ was developed to increase the +population of particles in important spatial regions and energy ranges by +controlling particle weights. Each spatial region and particle energy range is +assigned upper and lower weight bounds, :math:`w_u` and :math:`w_\ell`, +respectively. When a particle is in a given spatial region / energy range, its +weight, :math:`w`, is compared to the lower and upper bounds. If the weight of +the particle is above the upper weight bound, the particle is split into +:math:`N` particles, where + +.. math:: + :label: ww-split + + N = \min(N_{max}, \lceil w/w_u \rceil) + +and :math:`N_{max}` is a user-defined maximum number of splits. To ensure a +fair game, each of the :math:`N` particles is assigned a weight :math:`w/N`. If +the weight is below :math:`w_\ell`, it is Russian rouletted as described in +:ref:`survival_biasing` with a survival weight :math:`w_s` that is set equal to + +.. math:: + :label: ww-survival-weight + + w_s = \min(N_{max} w, f_s w_l) + +where :math:`f_s` is a user-defined survival weight ratio greater than one. + +On top of the standard weight window method described above, OpenMC implements +two additional checks intended to mitigate problems with long histories. First, +particles with a weight that falls below some very small cutoff (defaults to +:math:`10^{-38}`) are killed with no Russian rouletting. Additionally, the total +number of splits experienced by a particle is tracked and if it reaches some +maximum value, it is prohibited from splitting further. + +At present, OpenMC allows weight windows to be defined on all supported mesh +types. + +.. only:: html + + .. rubric:: References + +.. [Gelbard] Ely M. Gelbard, "Epithermal Scattering in VIM," FRA-TM-123, Argonne + National Laboratory (1979). + +.. [Squires] G. L. Squires, *Introduction to the Theory of Thermal Neutron + Scattering*, Cambridge University Press (1978). + +.. [Williams] M. M. R. Williams, *The Slowing Down and Thermalization of + Neutrons*, North-Holland Publishing Co., Amsterdam (1966). **Note:** This + book can be obtained for free from the OECD_. + +.. |sab| replace:: S(:math:`\alpha,\beta,T`) + +.. _SIGMA1 method: https://doi.org/10.13182/NSE76-1 + +.. _scaled interpolation: https://doi.org/10.13182/NSE73-A26575 + +.. _probability table method: https://doi.org/10.13182/NSE72-3 + +.. _Watt fission spectrum: https://doi.org/10.1103/PhysRev.87.1037 + +.. _Foderaro: https://dspace.mit.edu/handle/1721.1/1716 + +.. _OECD: https://www.oecd-nea.org/tools/abstract/detail/NEA-1792 + +.. _NJOY: https://www.njoy21.io/NJOY2016/ + +.. _PREPRO: https://www-nds.iaea.org/public/endf/prepro/ + +.. _ENDF-6 Format: https://www.oecd-nea.org/dbdata/data/manual-endf/endf102.pdf + +.. _Monte Carlo Sampler: https://mcnp.lanl.gov/pdf_files/TechReport_1983_LANL_LA-9721-MS_EverettCashwell.pdf + +.. _LA-UR-14-27694: https://www.osti.gov/biblio/1159204 + +.. _MC21: https://www.osti.gov/biblio/903083 + +.. _Romano: https://doi.org/10.1016/j.cpc.2014.11.001 + +.. _Sutton and Brown: https://www.osti.gov/biblio/307911 + +.. _lectures: https://mcnp.lanl.gov/pdf_files/TechReport_2005_LANL_LA-UR-05-4983_Brown.pdf diff --git a/rst/math/physical_models_c61dfa.rst b/rst/math/physical_models_c61dfa.rst new file mode 100644 index 0000000..5d666a9 --- /dev/null +++ b/rst/math/physical_models_c61dfa.rst @@ -0,0 +1,329 @@ +.. _predef_physicalmodels: + +*************** +Physical Models +*************** + +These are models that are physical motivated, generally as solutions to +physical problems. This is in contrast to those that are mathematically motivated, +generally as solutions to mathematical problems. + +.. _blackbody-planck-law: + +BlackBody +========= + +The :class:`~astropy.modeling.physical_models.BlackBody` model provides a model +for using `Planck's Law `_. +The blackbody function is + +.. math:: + + B_{\nu}(T) = A \frac{2 h \nu^{3} / c^{2}}{exp(h \nu / k T) - 1} + +where :math:`\nu` is the frequency, :math:`T` is the temperature, +:math:`A` is the scaling factor, +:math:`h` is the Plank constant, :math:`c` is the speed of light, and +:math:`k` is the Boltzmann constant. + +The two parameters of the model the scaling factor ``scale`` (A) and +the absolute temperature ``temperature`` (T). If the ``scale`` factor does not +have units, then the result is in units of spectral radiance, specifically +ergs/(cm^2 Hz s sr). If the ``scale`` factor is passed with spectral radiance units, +then the result is in those units (e.g., ergs/(cm^2 A s sr) or MJy/sr). +Setting the ``scale`` factor with units of ergs/(cm^2 A s sr) will give the +Planck function as :math:`B_\lambda`. +The temperature can be passed as a Quantity with any supported temperature unit. + +An example plot for a blackbody with a temperature of 10000 K and a scale of 1 is +shown below. A scale of 1 shows the Planck function with no scaling in the +default units returned by :class:`~astropy.modeling.physical_models.BlackBody`. + +.. plot:: + :include-source: + + import numpy as np + import matplotlib.pyplot as plt + + from astropy.modeling.models import BlackBody + import astropy.units as u + + wavelengths = np.logspace(np.log10(1000), np.log10(3e4), num=1000) * u.AA + + # blackbody parameters + temperature = 10000 * u.K + + # BlackBody provides the results in ergs/(cm^2 Hz s sr) when scale has no units + bb = BlackBody(temperature=temperature, scale=10000.0) + bb_result = bb(wavelengths) + + fig, ax = plt.subplots(layout='tight') + ax.plot(wavelengths, bb_result, '-') + + ax.set( + xscale="log", + xlabel=fr"$\lambda$ [{wavelengths.unit}]", + ylabel=fr"$F(\lambda)$ [{bb_result.unit}]", + ) + + plt.show() + +The :meth:`~astropy.modeling.physical_models.BlackBody.bolometric_flux` member +function gives the bolometric flux using +:math:`\sigma T^4/\pi` where :math:`\sigma` is the Stefan-Boltzmann constant. + +The :meth:`~astropy.modeling.physical_models.BlackBody.lambda_max` and +:meth:`~astropy.modeling.physical_models.BlackBody.nu_max` member functions +give the wavelength and frequency of the maximum for :math:`B_\lambda` +and :math:`B_\nu`, respectively, calculated using `Wien's Law +`_. + +Drude1D +======= + +The :class:`~astropy.modeling.physical_models.Drude1D` model provides a model +for the behavior of an electron in a material +(see `Drude Model `_). +Like the :class:`~astropy.modeling.functional_models.Lorentz1D` model, the Drude model +has broader wings than the :class:`~astropy.modeling.functional_models.Gaussian1D` +model. The Drude profile has been used to model dust features including the +2175 Angstrom extinction feature and the mid-infrared aromatic/PAH features. +The Drude function at :math:`x` is + +.. math:: + + D(x) = A \frac{(f/x_0)^2}{((x/x_0 - x_0/x)^2 + (f/x_0)^2} + +where :math:`A` is the amplitude, :math:`f` is the full width at half maximum, +and :math:`x_0` is the central wavelength. An example of a Drude1D model +with :math:`x_0 = 2175` Angstrom and :math:`f = 400` Angstrom is shown below. + +.. plot:: + :include-source: + + import numpy as np + import matplotlib.pyplot as plt + + from astropy.modeling.models import Drude1D + import astropy.units as u + + wavelengths = np.linspace(1000, 4000, num=1000) * u.AA + + # Parameters and model + mod = Drude1D(amplitude=1.0, x_0=2175. * u.AA, fwhm=400. * u.AA) + mod_result = mod(wavelengths) + + fig, ax = plt.subplots(layout="tight") + ax.plot(wavelengths, mod_result, '-') + + ax.set(xlabel=fr"$\lambda$ [{wavelengths.unit}]", ylabel=r"$D(\lambda)$") + + plt.show() + +.. _NFW: + +NFW +========= + +The :class:`~astropy.modeling.physical_models.NFW` model computes a +1-dimensional Navarro–Frenk–White profile. The dark matter density in an +NFW profile is given by: + + +.. math:: + + \rho(r)=\frac{\delta_c\rho_{c}}{r/r_s(1+r/r_s)^2} + +where :math:`\rho_{c}` is the critical density of the Universe at the redshift +of the profile, :math:`\delta_c` is the over density, and :math:`r_s` is the +scale radius of the profile. + + +This model relies on three parameters: + + ``mass`` : the mass of the profile (in solar masses if no units are provided) + + ``concentration`` : the profile concentration + + ``redshift`` : the redshift of the profile + +As well as two optional initialization variables: + + ``massfactor`` : tuple or string specifying the overdensity type and factor (default ("critical", 200)) + + ``cosmo`` : the cosmology for density calculation (default default_cosmology) + +.. note:: + Initialization of NFW profile object required before evaluation (in order to set mass + overdensity and cosmology). + + +Sample plots of an NFW profile with the following parameters are displayed below: + ``mass`` = :math:`2.0 x 10^{15} M_{sun}` + + ``concentration`` = 8.5 + + ``redshift`` = 0.63 + +The first plot is of the NFW profile density as a function of radius. +The second plot displays the profile density and radius normalized by the NFW scale +density and scale radius, respectively. The scale density and scale radius are available +as attributes ``rho_s`` and ``r_s``, and the overdensity radius can be accessed via ``r_virial``. + +.. plot:: + :include-source: + + import numpy as np + import matplotlib.pyplot as plt + from astropy.modeling.models import NFW + import astropy.units as u + from astropy import cosmology + + # NFW Parameters + mass = u.Quantity(2.0E15, u.M_sun) + concentration = 8.5 + redshift = 0.63 + cosmo = cosmology.Planck15 + massfactor = ("critical", 200) + + # Create NFW Object + n = NFW(mass=mass, concentration=concentration, redshift=redshift, cosmo=cosmo, + massfactor=massfactor) + + # Radial distribution for plotting + radii = range(1,2001,10) * u.kpc + + # Radial NFW density distribution + n_result = n(radii) + + # Plot creation + fig, axs = plt.subplots(nrows=2) + fig.suptitle('1 Dimensional NFW Profile') + + # Density profile subplot + axs[0].plot(radii, n_result, '-') + axs[0].set( + yscale='log', + xlabel=fr"$r$ [{radii.unit}]", + ylabel=fr"$\rho$ [{n_result.unit}]", + ) + + # Create scaled density / scaled radius subplot + # NFW Object + n = NFW(mass=mass, concentration=concentration, redshift=redshift, cosmo=cosmo, + massfactor=massfactor) + + # Radial distribution for plotting + radii = np.logspace(np.log10(1e-5), np.log10(2), num=1000) * u.Mpc + n_result = n(radii) + + # Scaled density / scaled radius subplot + axs[1].plot(radii / n.radius_s, n_result / n.density_s, '-') + axs[1].set( + xscale='log', + yscale='log', + xlabel=r"$r / r_s$", + ylabel=r"$\rho / \rho_s$", + ) + + # Display plot + fig.tight_layout(rect=[0, 0.03, 1, 0.95]) + plt.show() + + + +The :meth:`~astropy.modeling.physical_models.NFW.circular_velocity` member provides the circular +velocity at each position ``r`` via the equation: + + +.. math:: + + v_{circ}(r)^2=\frac{1}{x}\frac{\ln(1+cx)-(cx)/(1+cx)}{\ln(1+c)-c/(1+c)} + +where x is the ratio ``r``:math:`/r_{vir}`. Circular velocities are provided in km/s. + +A sample plot of circular velocities of an NFW profile with the following parameters is displayed +below: + + ``mass`` = :math:`2.0 x 10^{15} M_{sun}` + + ``concentration`` = 8.5 + + ``redshift`` = 0.63 + +The maximum circular velocity and radius of maximum circular velocity are available as attributes +``v_max`` and ``r_max``. + + +.. plot:: + :include-source: + + import matplotlib.pyplot as plt + from astropy.modeling.models import NFW + import astropy.units as u + from astropy import cosmology + + # NFW Parameters + mass = u.Quantity(2.0E15, u.M_sun) + concentration = 8.5 + redshift = 0.63 + cosmo = cosmology.Planck15 + massfactor = ("critical", 200) + + # Create NFW Object + n = NFW(mass=mass, concentration=concentration, redshift=redshift, cosmo=cosmo, + massfactor=massfactor) + + # Radial distribution for plotting + radii = range(1,200001,10) * u.kpc + + # NFW circular velocity distribution + n_result = n.circular_velocity(radii) + + # Plot creation + fig,ax = plt.subplots() + ax.set_title('NFW Profile Circular Velocity') + ax.plot(radii, n_result, '-') + ax.set_xscale('log') + ax.set_xlabel(fr"$r$ [{radii.unit}]") + ax.set_ylabel(r"$v_{circ}$" + f" [{n_result.unit}]") + + # Display plot + plt.tight_layout(rect=[0, 0.03, 1, 0.95]) + plt.show() + + +.. _Cosmologies: + +Cosmologies +=========== + +The instances of the |Cosmology| class (and subclasses) include +|Cosmology.to_format|, a method to convert a Cosmology to another python +object. Specifically, any redshift method can be converted to a +:class:`~astropy.modeling.FittableModel` instance using the argument +``format="astropy.model"``. +During the conversion, each |Cosmology| :class:`~astropy.cosmology.Parameter` +is converted to a :class:`astropy.modeling.Model` +:class:`~astropy.modeling.Parameter`, while the redshift-method becomes the +model's ``__call__`` / ``evaluate`` method. +This means cosmologies can now be fit with data! + +.. code-block:: + + >>> from astropy.cosmology import Planck18 + >>> model = Planck18.to_format(format="astropy.model", method="lookback_time") + >>> model + + +When finished, e.g. fitting, a model can be turned back into a |Cosmology| +using |Cosmology.from_format|. + +.. code-block:: + + >>> from astropy.cosmology import Cosmology + >>> cosmo = Cosmology.from_format(model, format="astropy.model") + >>> cosmo == Planck18 + True diff --git a/scripts/fetch_math_binaries.py b/scripts/fetch_math_binaries.py new file mode 100755 index 0000000..bb87dc8 --- /dev/null +++ b/scripts/fetch_math_binaries.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Fetch the math corpus binaries from their original sources. + +The binary formats that carry mathematics are gitignored, like every other +corpus binary, so they cannot travel in a pull request. This script downloads +them from the sources recorded in `MATH_PROVENANCE.md` and writes each one to +the repository path it belongs at. + +Run it once, then publish the bytes the usual way: + + python3 scripts/fetch_math_binaries.py + python3 scripts/publish_corpus.py --bucket xberg-test-documents + +`publish_corpus.py` scans the working tree, so the files have to be in place +before it runs. It writes `corpus.lock.json` itself. + +Every entry carries the sha256 of the file this corpus was validated against. +A download whose digest does not match is written to `.mismatch` and +reported, rather than replacing a good file with a source that has changed. +""" + +from __future__ import annotations + +import argparse +import concurrent.futures +import hashlib +import json +import sys +import urllib.request +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +MANIFEST = Path(__file__).resolve().parent / "math-binaries.json" +TIMEOUT = 120 +RETRIES = 3 + + +def fetch_one(path: str, entry: dict, force: bool) -> tuple[str, str]: + """Return (path, status). Status is ok, skipped, mismatch or an error.""" + target = REPO_ROOT / path + if target.exists() and not force: + digest = hashlib.sha256(target.read_bytes()).hexdigest() + if digest == entry["sha256"]: + return path, "skipped" + + last_error = "" + for attempt in range(1, RETRIES + 1): + try: + request = urllib.request.Request(entry["url"], headers={"User-Agent": "xberg-test-documents"}) + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: + payload = response.read() + break + except Exception as error: # noqa: BLE001 - any failure is worth one more try + last_error = f"{type(error).__name__}: {error}" + if attempt == RETRIES: + return path, f"error {last_error}" + else: # pragma: no cover - the loop always breaks or returns + return path, f"error {last_error}" + + digest = hashlib.sha256(payload).hexdigest() + target.parent.mkdir(parents=True, exist_ok=True) + if digest != entry["sha256"]: + (target.with_suffix(target.suffix + ".mismatch")).write_bytes(payload) + return path, f"mismatch got {digest[:12]} want {entry['sha256'][:12]}" + + target.write_bytes(payload) + return path, "ok" + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--jobs", type=int, default=8, help="parallel downloads (default 8)") + parser.add_argument("--force", action="store_true", help="re-download files that already match") + args = parser.parse_args() + + manifest = json.loads(MANIFEST.read_text()) + counts: dict[str, int] = {} + problems: list[str] = [] + + with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as pool: + futures = [pool.submit(fetch_one, path, entry, args.force) for path, entry in sorted(manifest.items())] + for future in concurrent.futures.as_completed(futures): + path, status = future.result() + key = status.split()[0] + counts[key] = counts.get(key, 0) + 1 + if key in {"error", "mismatch"}: + problems.append(f" {path}: {status}") + + print(f"{len(manifest)} binaries: " + ", ".join(f"{n} {k}" for k, n in sorted(counts.items()))) + if problems: + print("\nNeeds attention:", file=sys.stderr) + print("\n".join(problems), file=sys.stderr) + print( + "\nA source that moved or changed needs its entry in scripts/math-binaries.json updated," + "\nand MATH_PROVENANCE.md updated with it.", + file=sys.stderr, + ) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/math-binaries.json b/scripts/math-binaries.json new file mode 100644 index 0000000..6613029 --- /dev/null +++ b/scripts/math-binaries.json @@ -0,0 +1,277 @@ +{ + "epub/math/IS4E_fbdd3c.epub": { + "sha256": "517110e8bb835a54b8fa6b26047f426a27f820584c7794dcf3f4d1a33850e4b7", + "size": 17841570, + "url": "https://bookdown.org/bkrauth/IS4E/IS4E.epub" + }, + "epub/math/cnt_mathml_support_a20d9b.epub": { + "sha256": "61f61f7631c684d2e42ad7384c0c48435517b8908f528165ab83419f129589dd", + "size": 2109, + "url": "https://w3c.github.io/epub-tests/tests/cnt-mathml-support.epub" + }, + "epub/math/quadratic_functions_4ebefc.epub": { + "sha256": "3db31eade669b979099ba01d2846b28713766e5d78a328f64474a2f8e49f5d44", + "size": 47629, + "url": "https://archive.org/download/cnx-org-col11284/quadratic-functions.epub" + }, + "epub/math/statistical_learning_theory_d50966.epub": { + "sha256": "a549ea3e7b66b5d97c13a9164a68f44ebc373beabe3345fa90a71f0baf231c35", + "size": 808958, + "url": "https://archive.org/download/cnx-org-col10532/statistical-learning-theory.epub" + }, + "hwp/math/EC_88_98_EC_8B_9D_2acc8f.hwp": { + "sha256": "b58d59eeb903e2553a7d67049dbca3f639aedf7d8276875663775b0ac4404082", + "size": 11776, + "url": "https://raw.githubusercontent.com/neolord0/hwplib/main/sample_hwp/basic/%EC%88%98%EC%8B%9D.hwp" + }, + "hwp/math/SimpleEquation_4e1760.hwpx": { + "sha256": "15091aadf5dc5ac451383472afbdf02af75c225db894f3f9ace621634db9d57a", + "size": 12416, + "url": "https://raw.githubusercontent.com/neolord0/hwpxlib/main/testFile/reader_writer/SimpleEquation.hwpx" + }, + "hwp/math/doc_8713v3a8b_3D23v9e_3D4av07_3D85v3e_3Dcfafvbb7dv2ad9_v_a3c2e7.hwp": { + "sha256": "99c998a31f6d965ef5aa72981be5a7ce3f2b275bcf27e3bf3716320badc1550f", + "size": 303616, + "url": "https://raw.githubusercontent.com/Ahnd6474/jakal-hwpx/main/hwpx_collection/doc_8713v3a8b%3D23v9e%3D4av07%3D85v3e%3Dcfafvbb7dv2ad9_v4607.hwpx" + }, + "hwp/math/eq_01_71f171.hwp": { + "sha256": "d4b5e4730da12395c953d16c026c979adfdf3235eee4be605cef0ab758a7e5ec", + "size": 16384, + "url": "https://raw.githubusercontent.com/postmelee/alhangeul-macos/main/samples/eq-01.hwp" + }, + "hwp/math/equation_p0_e63f26.hwpx": { + "sha256": "02a3a6defefb73df29081f1415e96cdf14dab20b6f20c2ab5dd881a601bdc757", + "size": 8113, + "url": "https://raw.githubusercontent.com/airmang/python-hwpx/main/tests/fixtures/equation_preview/equation_p0.hwpx" + }, + "hwp/math/from_5d05e0.hwpx": { + "sha256": "49a7c76c740f82e5970306e0904c2d78b3c9712bd3718a27151de3c7a79066a1", + "size": 28084, + "url": "https://raw.githubusercontent.com/neolord0/hwp2hwpx/main/test/equation/from.hwpx" + }, + "hwp/math/from_ecaebf.hwp": { + "sha256": "12d57c6c2138057d9e094e80e117c234a71d479c074af1ed61c2f752b751ed8d", + "size": 26624, + "url": "https://raw.githubusercontent.com/neolord0/hwp2hwpx/main/test/equation/from.hwp" + }, + "hwp/math/hard_20example_3d4d15.hwpx": { + "sha256": "6f1c666deacae0c646a1f271f570f0e643ad88eabd09c3bc4b9061069a91b862", + "size": 677943, + "url": "https://raw.githubusercontent.com/Ahnd6474/jakal-hwpx/main/hwpx_collection/hard%20example.hwpx" + }, + "iwork/math/geometric_means_qcmc_revised_7d7c7a.key": { + "sha256": "3de4f9988d87ad7c7c4ec309ce4ac9b5506f6485dd72af031d08a71d2c0d92ee", + "size": 5401722, + "url": "https://zenodo.org/api/records/14309036/files/geometric-means-qcmc-revised.key/content" + }, + "office/math/03_Inferential_20statistics2024_2025_bd7449.pptx": { + "sha256": "03b0f4c525f33b55a0d36715599abcacd28ea8d381bc103c07ca27c530768ef1", + "size": 3513002, + "url": "https://zenodo.org/api/records/14361416/files/03_Inferential%20statistics2024_2025.pptx/content" + }, + "office/math/Fermat_general_7d3de0.pptx": { + "sha256": "e954b70ded17a50b457115e3cb604f10a694f4f95532a91639b355da709a80f6", + "size": 1681059, + "url": "https://zenodo.org/api/records/15252111/files/Fermat_general.pptx/content" + }, + "office/math/MG35_1_MathGuide_7e950e.odt": { + "sha256": "c0e53945ffb02ff180fce94b652c711353035a67c5c9e5d340dee368a912da58", + "size": 2346986, + "url": "https://wiki.documentfoundation.org/images/8/8b/MG35_1-MathGuide.odt" + }, + "office/math/MG44_MathGuide_ed525b.odt": { + "sha256": "9883969d194db7529f95d56652220d302615b051270e585a643d985250772c86", + "size": 4244438, + "url": "https://wiki.documentfoundation.org/images/b/bc/MG44-MathGuide.odt" + }, + "office/math/MG7001_CrearEditarFormulas_de2112.odt": { + "sha256": "abe50d99993bee2157cc14a95f13784f7027de176bd6f0404475f56c33b8e2f5", + "size": 522897, + "url": "https://wiki.documentfoundation.org/images/4/44/MG7001-CrearEditarFormulas.odt" + }, + "office/math/MG7003_FormulasCalcDrawImpress_0129ab.odt": { + "sha256": "e0511d4f4341a31898400cc43504fe79fa644eb48a0329b0a7710c9f9e76fed9", + "size": 157126, + "url": "https://wiki.documentfoundation.org/images/9/93/MG7003-FormulasCalcDrawImpress.odt" + }, + "office/math/Manju_20Ghalyan_2d1798.docx": { + "sha256": "8c818dde0c722f62f8bc7cd7245e714709e3ff749ab2c1047f60916ebceb4527", + "size": 87656, + "url": "https://zenodo.org/api/records/822996/files/Manju%20Ghalyan.docx/content" + }, + "office/math/OpenDocument_v1_2_os_part1_0fdaaa.odt": { + "sha256": "07c76a5ac11828005399dd4787244892ef6241211e467a61d5b409d0218488d1", + "size": 758963, + "url": "https://raw.githubusercontent.com/tdf/odftoolkit/master/xslt-runner/src/test/resources/odf12/OpenDocument-v1.2-os-part1.odt" + }, + "office/math/OpenDocument_v1_3_cs01_part3_schema_80057c.odt": { + "sha256": "be1260902cc33e52cf8554833b6c2b3125194325ab38a0f4b6945b7968ae8088", + "size": 940234, + "url": "https://raw.githubusercontent.com/tdf/odftoolkit/master/xslt-runner/src/test/resources/odf13/OpenDocument-v1.3-cs01-part3-schema.odt" + }, + "office/math/PSAAP_review_presentation_102022_SAND2022_14495_PE_a5d658.pptx": { + "sha256": "e04de6ae8da82d2a8c0639e58a0cf29d88ce196a169854e13167959f3d7bddda", + "size": 4807104, + "url": "https://zenodo.org/api/records/7232101/files/PSAAP_review_presentation_102022-SAND2022-14495-PE.pptx/content" + }, + "office/math/PejmanJouzdani_f8d8e3.pptx": { + "sha256": "d56022efa248785a1ecb18e33a11c72cef01792924dac030ca3dcec1c840824f", + "size": 6032262, + "url": "https://zenodo.org/api/records/10407797/files/PejmanJouzdani.pptx/content" + }, + "office/math/Single_THz_photon_detector_JuliangLi_ANL_82bc42.pptx": { + "sha256": "1d3f018e81e2834632ca707d7c965382e5f19047c3f95b400f14edfc4ed0244b", + "size": 1937311, + "url": "https://zenodo.org/api/records/4641119/files/Single_THz_photon_detector_JuliangLi_ANL.pptx/content" + }, + "office/math/Supplementry_20Material_1e5dc4.docx": { + "sha256": "277b1f91b026f7716b77b1a9a533dfcfacca464c97bf0d5ef1e5c9aea620ffbe", + "size": 90635, + "url": "https://zenodo.org/api/records/19008259/files/Supplementry%20Material.docx/content" + }, + "office/math/Zucker_EAAT_statistics_16c5f9.pptx": { + "sha256": "672433f3aa9c1fa22e910f459c8b16b50050ce93a09afce7858bdb39bbcb60de", + "size": 3452639, + "url": "https://zenodo.org/api/records/7072775/files/Zucker_EAAT_statistics.pptx/content" + }, + "office/math/editable_04513a.pptx": { + "sha256": "f8984dbdbdc837cebf488ae1549a98fd94c04d35add14732cc59131561269817", + "size": 45633, + "url": "https://raw.githubusercontent.com/giszzt/figedit/main/assets/examples/ast-reveal/editable.pptx" + }, + "office/math/editable_0c0c46.pptx": { + "sha256": "7ac0409c7b10c4a2841505ef942c96e87772bca85e7de958252e4306e1bf6ea0", + "size": 42264, + "url": "https://raw.githubusercontent.com/giszzt/figedit/main/assets/examples/parallel-loops/editable.pptx" + }, + "office/math/equation_16f2f6.docx": { + "sha256": "a0d7a34186e37e303ef10f6469834221d92ae74c886078d7f32f2dc1a7fd96a5", + "size": 12548, + "url": "https://raw.githubusercontent.com/dotnet/Open-XML-SDK/main/test/DocumentFormat.OpenXml.Tests.Assets/assets/TestDataStorage/v2FxTestFiles/wordprocessing/equation/equation.docx" + }, + "office/math/equation_a59623.doc": { + "sha256": "eccab1c32bf3ef27e36dfeb46b3ebfba4981666e0fe9364eef05fa55f6463980", + "size": 13824, + "url": "https://raw.githubusercontent.com/apache/poi/trunk/test-data/document/equation.doc" + }, + "office/math/equations_b6ad03.docx": { + "sha256": "339b064492530598859de0bde8504de7a4aefead88210baf3e9f3db0ed925b40", + "size": 15235, + "url": "https://raw.githubusercontent.com/microsoft/markitdown/main/packages/markitdown/tests/test_files/equations.docx" + }, + "office/math/equations_d0d980.docx": { + "sha256": "32933facc78a062cd504f91286521f7615c86895ebbad410c9a3bf586cbe36d8", + "size": 18917, + "url": "https://raw.githubusercontent.com/docling-project/docling/main/tests/data/docx/sources/equations.docx" + }, + "office/math/math_OOo311_71135a.odt": { + "sha256": "dc25e9b848844a34ca18997090b20f30b9a3b3b10159096c3974be9ca4a4d6ca", + "size": 10485, + "url": "https://raw.githubusercontent.com/tdf/odftoolkit/master/validator/src/test/resources/math_OOo311.odt" + }, + "office/math/pascal_digital_binomial_theorem_Senior_20Seminar_20Thesi_82393b.pptx": { + "sha256": "eb3e1f727a55bec3cda398c91aa8bd1b65616f8ca80cad07101336e028fcd071", + "size": 103918, + "url": "https://zenodo.org/api/records/20702180/files/pascal_digital_binomial_theorem(Senior%20Seminar%20Thesis,%20%ED%95%99%EC%82%AC%20%EC%84%B8%EB%AF%B8%EB%82%98%20%EB%B0%9C%ED%91%9C%20%EC%9E%90%EB%A3%8C,%20%EC%9B%90%EB%B3%B8).pptx/content" + }, + "office/math/strict_20math_53ebf7.docx": { + "sha256": "ab7b91701cfb3b069b287d2ad1c47493b4c0f94820fe79559606d7c555586f35", + "size": 13754, + "url": "https://raw.githubusercontent.com/plutext/docx4j/VERSION_17_0_3/docx4j-samples-docx4j/sample-docs/strict/strict%20math.docx" + }, + "office/math/table_with_equations_f14832.docx": { + "sha256": "fe924e9bef7ab34a7785fcd4fd74c975142e2530ba6e5db75a9ad16421c942a8", + "size": 14228, + "url": "https://raw.githubusercontent.com/docling-project/docling/main/tests/data/docx/sources/table_with_equations.docx" + }, + "office/math/tdf119223_394ffc.odp": { + "sha256": "971a9c8ad5089d8575827f491f52999d369c47539fd653ad57ebceb72567f10f", + "size": 18335, + "url": "https://raw.githubusercontent.com/LibreOffice/core/master/sd/qa/unit/data/odp/tdf119223.odp" + }, + "office/math/tdf130614_9b6224.ods": { + "sha256": "c016ebe42220f29c185f3424937152c33fc667e83977057b4df1902019948cbc", + "size": 11466, + "url": "https://raw.githubusercontent.com/LibreOffice/core/master/sc/qa/unit/uicalc/data/tdf130614.ods" + }, + "office/math/tdf159046_e964cb.ods": { + "sha256": "fe3b2e2c887891e3c6eb3095a16c16de4e4bbf39f474bdea6e8985b6f063f384", + "size": 17146, + "url": "https://raw.githubusercontent.com/LibreOffice/core/master/sc/qa/unit/uicalc/data/tdf159046.ods" + }, + "office/math/testMSEquation_govdocs_863534_a6c49e.doc": { + "sha256": "88619cf1ad37819c2eda2ab13be06a0f377c574e8cf3a3346dbe5af33fd0e704", + "size": 30720, + "url": "https://raw.githubusercontent.com/apache/tika/main/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-microsoft-module/src/test/resources/test-documents/testMSEquation-govdocs-863534.doc" + }, + "office/math/testWORD_2006ml_9696cd.docx": { + "sha256": "a27f2b9244f5147cce25a05d4cddb1eec9c72259a41d52a7bf5eb3806b28207c", + "size": 151733, + "url": "https://raw.githubusercontent.com/apache/tika/main/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-microsoft-module/src/test/resources/test-documents/testWORD_2006ml.docx" + }, + "office/math/unknown_content_bda4e1.odt": { + "sha256": "dc8b8eb66397a7283ebe8e83a0426d27b0aabed8b8179f216086f98067aca07c", + "size": 19437, + "url": "https://raw.githubusercontent.com/tdf/odftoolkit/master/odfdom/src/test/resources/test-input/unknown-content.odt" + }, + "office/math/w11_w11_fore0ww8_8441b1.rtf": { + "sha256": "cde856f45465f2d08ddcde6489e1a85cf706a2269a26dc7a517b29946dde8d6c", + "size": 16253, + "url": "https://raw.githubusercontent.com/dotnet/wpf-test/main/src/Test/Editing/FeatureTests/Data/rtf/rtfcit/w11_w11_fore0ww8.rtf" + }, + "pdf/math/19930091059_e5a481.pdf": { + "sha256": "1971643025181d1216b0b0a359d2a5a3adf5d254d3e158e19ba880b368b86e53", + "size": 6771826, + "url": "https://ntrs.nasa.gov/api/citations/19930091059/downloads/19930091059.pdf" + }, + "pdf/math/19930093947_a3f534.pdf": { + "sha256": "555a041af6af5760df49c3e36b4b598ae83a809e48594e4f3a65edbd5ffae316", + "size": 685508, + "url": "https://ntrs.nasa.gov/api/citations/19930093947/downloads/19930093947.pdf" + }, + "pdf/math/20100014819_ba4d91.pdf": { + "sha256": "45c31c828c0adc581d5b5fe46cbaf5287eedd3fa8c48678ee07dbdb5ddb43d44", + "size": 710491, + "url": "https://ntrs.nasa.gov/api/citations/20100014819/downloads/20100014819.pdf" + }, + "pdf/math/2306_08071_597a81.pdf": { + "sha256": "5cf1d1b6b1ac4785b6a1951f693861e61ac661f94108140ee9ad34239af7c2d9", + "size": 868197, + "url": "https://arxiv.org/pdf/2306.08071" + }, + "pdf/math/2502_20028_047181.pdf": { + "sha256": "35ee55acb80f61cd652fbce785468c80b4eae799a810bc655e0fb1b08a071ff8", + "size": 333066, + "url": "https://arxiv.org/pdf/2502.20028" + }, + "pdf/math/2511_07120_8176dc.pdf": { + "sha256": "0d4c0e948a6157c2fea77ab1cfcf898e1d159daadc7eff867223a027a34240c7", + "size": 611865, + "url": "https://arxiv.org/pdf/2511.07120" + }, + "pdf/math/CollegeAlgebra_OP_7d1fcd.pdf": { + "sha256": "74a89e41f7b2db84e18b158a9a5548a2813f1878927e816536d43229c20439d4", + "size": 56807291, + "url": "https://assets.openstax.org/oscms-prodcms/media/documents/CollegeAlgebra-OP.pdf" + }, + "pdf/math/amsldoc_642b4e.pdf": { + "sha256": "374fcfb073739395a1a5a1eb9416bc9fcec5000255f52ad4acbe9b5e0227985e", + "size": 497706, + "url": "https://mirrors.ctan.org/macros/latex/required/amsmath/amsldoc.pdf" + }, + "pdf/math/journal_pcbi_1012015_type_printable_1eeb41.pdf": { + "sha256": "8ff2319ed38a2b2487f02b5265a156781e9edf2d8d595985a2211911069a7ae7", + "size": 3162336, + "url": "https://journals.plos.org/ploscompbiol/article/file?id=10.1371/journal.pcbi.1012015&type=printable" + }, + "pdf/math/physica_manual_bcb494.pdf": { + "sha256": "1ba158f65aac4f46bb2dd9a6431f4475e691c94042d10889a5b166e36d60c7b0", + "size": 518570, + "url": "https://raw.githubusercontent.com/Leedehai/typst-physics/master/physica-manual.pdf" + }, + "pdf/math/testmath_e28157.pdf": { + "sha256": "2cfed881f790c42e4d36e1f18fde4c949186c41af64f8630199cec97d39f7f34", + "size": 448958, + "url": "https://mirrors.ctan.org/macros/latex/required/amsmath/testmath.pdf" + } +} diff --git a/typst/math/main_979fe4.typ b/typst/math/main_979fe4.typ new file mode 100644 index 0000000..064e969 --- /dev/null +++ b/typst/math/main_979fe4.typ @@ -0,0 +1,86 @@ +// NTNU Physics Lab Report Template +// Initialize with: typst init @preview/ntnu-physics-report-replica + +#import "@preview/ntnu-physics-report-replica:0.1.0": * + +#show: ntnu-report.with( + title: "Tittel på rapporten", + authors: ( + (name: "Ditt Navn", affiliations: (1,)), + (name: "Medstudent", affiliations: (1,)), + ), + affiliations: ( + "Institutt for fysikk, Norges Teknisk-Naturvitenskapelige Universitet, N-7491 Trondheim, Norway.", + ), + supervisor: "Veileders Navn", + abstract: [ + Her skriver du et sammendrag av rapporten. Sammendraget skal være veldig kort + men må inneholde svaret på tre spørsmål: 1. Hva gjorde du (hva målte du)? 2. Hvordan + gjorde du det (hvilken metode)? 3. Hva fant du (resultat)? + ], + // bibliography-file: "references.bib", + two-column: true, +) + += Innledning + +Her begynner rapporten. Beskriv bakgrunnen for eksperimentet og hva du ønsker å undersøke. + + += Teori + +Her presenterer du den relevante teorien. For eksempel kan svingetiden til en pendel uttrykkes som +$ T = 2 pi sqrt(l / g), $ +der $l$ er lengden til pendelen og $g$ er tyngdeakselerasjonen. + +Vi kan referere til ligning @svingetid senere i teksten. + + += Metode og apparatur + +Beskriv utstyret du brukte og hvordan eksperimentet ble utført. + +// Eksempel på figur (fjern kommentar når du har en bildefil): +// #figure( +// image("figur.png", width: 50%), +// caption: [Beskrivelse av figuren.], +// ) + + += Resultat og diskusjon + +Presenter resultatene dine. For eksempel: Vi målte lengden til $l = 1,000 plus.minus 0,001 "m"$. + +// Eksempel på tabell: +#figure( + table( + columns: 3, + align: center, + stroke: none, + inset: (x: 8pt, y: 4pt), + toprule, + [$l$ (m)], [$T$ (s)], [$g$ (m/s²)], + midrule, + [0,50], [1,42], [9,80], + [0,75], [1,74], [9,81], + [1,00], [2,01], [9,79], + bottomrule, + ), + caption: [Målte verdier for pendellengde, svingetid og beregnet tyngdeakselerasjon.], + kind: table, +) + +Resultatene i @resultater viser at... + + += Konklusjon + +Oppsummer funnene dine og gi en konklusjon. + + +// Referanser - bruk enten manuell liste eller .bib-fil +#heading(level: 1)[Referanser] + +#set par(first-line-indent: 0pt, hanging-indent: 1.5em) + +\[1\] Forfatter. _Tittel_. Utgiver, År. diff --git a/typst/math/main_c87a40.typ b/typst/math/main_c87a40.typ new file mode 100644 index 0000000..342721c --- /dev/null +++ b/typst/math/main_c87a40.typ @@ -0,0 +1,116 @@ +#import "@preview/clean-math-paper:0.2.8": * + +#let date = datetime.today().display("[month repr:long] [day], [year]") + +// Modify some arguments, which can be overwritten in the template call +#page-args.insert("numbering", "1/1") +#text-args-title.insert("size", 2em) +#text-args-title.insert("fill", black) +#text-args-authors.insert("size", 12pt) + +#show: template.with( + title: "Typst template for mathematical papers", + authors: ( + (name: "Author 1", affiliation-id: 1, email: "author1@example.com", orcid: "0000-0000-0000-0000"), + (name: "Author 2", affiliation-id: "2,*", email: "author2@example.com"), + ), + affiliations: ( + (id: 1, name: "Affiliation 1, Address 1"), + (id: 2, name: "Affiliation 2, Address 2"), + (id: "*", name: "Corresponding author") + ), + // Use `authors-style: "per-author"` to print the affiliations of each author + // below their name instead of collecting them below all authors + // authors-style: "per-author", + authors-per-row: 3, + date: date, + heading-color: rgb("#374CA9"), + link-color: rgb("#008002"), + // Insert your abstract after the colon, wrapped in brackets. + // Example: `abstract: [This is my abstract...]` + abstract: lorem(30), + keywords: ("First keyword", "Second keyword", "etc."), + AMS: ("65M70", "65M12"), + // Pass page-args to change page settings + // page-args: page-args, + // Pass text-args-authors to change author name text settings + // text-args-authors: text-args-authors, + // Pass text-args-title to change title text settings + // text-args-title: text-args-title, +) + += Introduction +#lorem(20) + += Equations + +The template uses #link("https://typst.app/universe/package/i-figured/")[`i-figured`] for labeling equations. Equations will be numbered only if they are labelled. Here is an equation with a label: + +$ + sum_(k=1)^n k = (n(n+1)) / 2 +$ + +We can reference it by `@eq:label` like this: @eq:equation, i.e., we need to prepend the label with `eq:`. The number of an equation is determined by the section it is in, i.e. the first digit is the section number and the second digit is the equation number within that section. + +Here is an equation without a label: + +$ + exp(x) = sum_(n=0)^oo (x^n) / n! +$ + +As we can see, it is not numbered. + += Theorems + +The template uses #link("https://typst.app/universe/package/great-theorems/")[`great-theorems`] for theorems. Here is an example of a theorem: + +#theorem(title: "Example Theorem")[ + This is an example theorem. +] +#proof[ + This is the proof of the example theorem. +] + + +We also provide `definition`, `lemma`, `remark`, `example`, and `question`s among others. Here is an example of a definition: + +#definition(title: "Example Definition")[ + This is an example definition. +] + +#question(title: "Custom mathblock?")[ + How do you define a custom mathblock? +] + +#let answer = my-mathblock( + blocktitle: "Answer", + bodyfmt: text.with(style: "italic"), +) + +#answer[ + You can define a custom mathblock like this: + ```typst + #let answer = my-mathblock( + blocktitle: "Answer", + bodyfmt: text.with(style: "italic"), + ) + ``` +] + +Similar as for the equations, the numbering of the theorems is determined by the section they are in. We can reference theorems by `@label` like this: @th:example. + +To get a bibliography, we also add a citation @Cooley65. + +#lorem(50) + +#bibliography("bibliography.bib") + +// Create appendix section +#show: appendices += + +If you have appendices, you can add them after `#show: appendices`. The appendices are started with an empty heading `=` and will be numbered alphabetically. Any appendix can also have different subsections. + +== Appendix section + +#lorem(100) diff --git a/typst/math/manual_4ee3cf.typ b/typst/math/manual_4ee3cf.typ new file mode 100644 index 0000000..ae389c1 --- /dev/null +++ b/typst/math/manual_4ee3cf.typ @@ -0,0 +1,740 @@ +#import "@preview/showman:0.1.2": runner +// #import "@preview/mitex:0.2.5": mitex + +#import "src/lib.typ" +#import lib: * + +#show "Instructor:": text.with(fill: color.yellow.darken(33%), weight: "semibold") +#show "Student:": text.with(fill: green.darken(33%), weight: "semibold") + +//SOURCE: https://gist.github.com/felsenhower/a975c137732e20273f47a117e0da3fd1 +#let LaTeX = { + let A = (offset: (x: -0.33em, y: -0.3em), size: 0.7em) + let T = (x_offset: -0.12em) + let E = (x_offset: -0.2em, y_offset: 0.23em, size: 1em) + let X = (x_offset: -0.1em) + [L#h(A.offset.x)#text(size: A.size, baseline: A.offset.y)[A]#h(T.x_offset)T#h(E.x_offset)#text(size: E.size, baseline: E.y_offset)[E]#h(X.x_offset)X] +} +#show "LaTeX": LaTeX + +#let get-orientation(dir) = { + if dir == ltr { + return ( + dir: ltr, + cols: (1fr, 1fr), + align: (x, y) => (right, left).at(calc.rem(x, 2)), + line: grid.vline, + ) + } else if dir == ttb { + return ( + dir: ttb, + cols: 1, + align: (x, y) => (bottom, top).at(calc.rem(y, 2)), + line: grid.hline, + ) + } +} + +#let showcode(code, dir: ltr, wrap: none) = { + let orientation = get-orientation(dir) + let prefix = "" + let suffix = "" + if code.lang == "typc" { + prefix = prefix + "\n#{" + suffix = "}\n" + suffix + } + + if wrap != none { + prefix = prefix + "\n" + (if code.lang == "typst" { "#" }) + wrap + "(" + suffix = ")\n" + suffix + } + + runner.standalone-example( + code, + eval-prefix: prefix, + eval-suffix: suffix, + scope: dictionary(lib), + direction: orientation.dir, + container: (input, output, direction: ltr) => { + block( + width: 100%, + grid( + columns: orientation.cols, + align: orientation.align, + inset: (x: 1em, y: 0.8em), + grid.cell(input), + orientation.at("line")(stroke: 0.5pt), + grid.cell(output), + ), + ) + }, + ) +} + +//START + +#show: setup.with( + config: ( + title: ( + format: text.with(size: 1.5em, weight: "bold"), + ), + ), + title: [ + #text(fill: black.transparentize(67%))[Lacy-UBC] + Math Group Project Template \ User Manual #toml("typst.toml").package.version + ], +) + +This #link("https://typst.app/docs")[Typst] template initially is to help you write and format #link("https://www.math.ubc.ca/undergraduate/courses")[UBC_V MATH 100&101] group projects. It is based on their existing (2025) LaTeX template. Despite the name, it offers a flexible layout for possibly other types of question-solution documents. + +This manual has two specifics: one for "Student:" who consume documents already populated with content, and the other for "Instructor:" (TA's too) who use the template to make projects for the students. + +You can skip to the next page if you already know why you are using a Typst template. + +#line(length: 100%) + +The two popular choices among students for typesetting math content, Word and LaTeX, each has significant drawbacks. + +Word, sounds familiar and easy, but... +- the math formatting (MathType) may be uncomfortable; +- you pretty much have to use MS Word/WPS/Google Doc/Pages, the editing experience using "libre" solutions like LibreOffice are subpar; +- many do not really know how to make use of Word, like styles, ruler, tab stops and template, so documents get messy. + +LaTeX is a powerful and professional academic typesetting system, plus, you can use your favorite text editor, but... +- the syntax may be cryptic; +- the error messages are cryptic; +- compilation (PDF generation) can be slow; + +#block( + breakable: false, + grid( + columns: (1fr, 2fr, 1fr), + align: center + horizon, + inset: 8pt, + [LaTeX], + ```latex + \[ e^{-\frac{x^2}{3}} \] + ```, + grid.cell(rowspan: 2)[#set text(size: 1.5em); $ e^(-x^2 / 3) $], + grid.hline(stroke: 0.25pt), + [Typst], + ```typst + $ e^(-x^2 / 3) $ + ```, + ), +) + +Still in development, Typst is more than enough for our use cases: +- simple math typesetting, much like on WebWork; +- no more `\begin{hell} \backslash \end{hell}`; +- fast compilation, typically in milliseconds; +- friendly manual, function signature and error messages; +- yes, a _fully functional_ #link("https://myriad-dreamin.github.io/tinymist")[language server]: completion, preview and many more; +- integration with your favorite text editor; +- a modern, free and collaborative #link("https://typst.app")[online editor]; +- easy customization by user, relative to LaTeX. + +#counter(page).update(0) +#set page(numbering: "1") + +#outline(depth: 2) + += Getting Started +You have two options: working online or local. Since this is a "group project" template, you probably want to work online for collaboration. Here is a step-by-step guide to get you started. + ++ #link("https://typst.app")[Sign up] for an account of the Typst web app. ++ Follow guides and explore a bit. ++ (Optional) Assemble a team. + + Dashboard → (top left) Team → New Team. + + Team dashboard → (next to big team name) manage team → Add member. + +Voilà! You are ready to start your math group project. + +== Instructor: Initializing a Group Project +To start a math group project in the web app, simply ++ go to the project dashboard; ++ next to "Empty document", click on "Start from a template"; ++ search and select "lacy-ubc-math-project"; ++ enter your own project name, create, that easy! + +In the project just initialized, you will see two files: `config.typ` and `project-1.typ`. + +You will likely focus on editing `project-1.typ` for actual questions. +The `config.typ` file can contain group and theme information that are likely more useful to students. You may also edit and distribute that for reusable theme configuration. + +=== `project-1.typ` +A basic start of project looks like +```typst +#import "@preview/lacy-ubc-math-project:0.2.0": * +#import "config.typ": * // Import the config. +#show: setup.with( //... +``` + +When you create more project files like `project-2.typ`, `project-3.typ`, copy these topmost two ```typc import```'s and ```typc show```. +Below this ```typst #show: setup.with( /*...*/ )``` is your project content. + +== Student: Using a Group Project +Given a project file, populated with typed questions, you may simply insert ```typc solution()``` where fit, and start solving. +Do not forget to surround elements of a solution with (), if there are more than one; and insert commas between elements. +#showcode( + dir: ttb, + ```typst + #qns( + question( + [What is $1 + 1$?], // ← append a comma, if absent + solution[It is 2.] // Make sure it is inside the question you are answering to. + ), + question( + [Good, now solve $integral_0^pi sin(x) dd(x)$.], + solution[ + Ah yes, this is a classic application of the Quantum Turnip Theorem, which tells us that for any integral involving sine, the approach is to first change variables into invisible ducks. + ] + ) + ) + ```, +) + +If the project is provided with a corresponding `config.typ`, consider if it conflicts with yours, if any. + += Learning Typst +Yes, you do have to learn it, but it is simple (for our purpose). +Consult the #link("https://staging.typst.app/docs")[Typst documentation], maybe the #link("https://sitandr.github.io/typst-examples-book/book/about.html")[Typst Examples Book] even if they say "don't rely on it." + +#link("https://typst-doc-cn.github.io/guide/FAQ.html")[There] is a collection of frequently asked, miscellaneous techniques which many find extremely helpful. +That is, if you read Chinese...I guess web translation also works. + += Setup +In ```typc setup()```, we define the project details, including the title, group name and authors. +```typst +#show: setup.with( + title: [The Project Title], + group: [The Group Name], + // The following are from config.typ, keep reading to find out how. + jane-doe, + san-zhang, + // more authors... +) +``` +By default, they are displayed like: +#{ + internal.components.visualize-project-head( + config: defaults, + [The Project Title], + [The Group Name], + author("Jane", "Doe", 31415926), + author( + "San", + "Zhang", + 27182818, + config: (author: (name-format: (f, l, ..s) => [*#l*#lower(f)])), + ), + //SOURCE: https://en.wikipedia.org/wiki/List_of_placeholder_names + author("Fulan", "AlFulani", 31415926), + author( + "Hanako", + "Yamada", + 27182818, + config: (author: (name-format: (f, l, ..s) => [*#l* #f])), + ), + ) +} + + +These title and authors given to ```typc setup()``` are also saved to PDF metadata, which is reflected in the PDF document properties. + +/ Caveat: At this point, only one name format, "first last", is in the defaults. Contribution is welcome. + But, how could Zhangsan and Yamada Hanako work-around their name display? See #link()[Advanced: Custom Name Format]. + +== Reusable Content +Since one group can take on multiple projects, it is wise to save common features like the members' information and the group name for multiple uses. + +The `config.typ` file is a place to store such data. +After the ```typst #import "config.typ": * ```, every variable in the file will be visible to you. +Looking into the template's `config.typ`, it has +```typst +#let jane-doe = author("Jane", "Doe", 31415926) +``` +which is why we could simply type `jane-doe` in the previous example and pass the full author information. + +== Student: Author +The `author` function produces an author object, like above. +Give it your first name, given name, as the first argument (```typc "Jane"```), and your last name, family name, surname, as the second argument (```typc "Doe"```); finally, your student number as the third argument (```typc 31415926```). + +In MATH 100/101 group projects we will suffix "NP" to a student's name if they are not present. +Assume Jane Doe is absent for the project, simply put +```typst +#show: setup.with( + // ... + jane-doe[NP] +) +``` + += Math +Formatting math equations is probably the reason you are here. +#( + ( + "E = m c^2", + "e^(i pi) = -1", + "(-b plus.minus sqrt(b^2 - 4a c)) / (2a)", + ) + .map(eq => [ + #showcode(raw("$" + eq + "$", lang: "typst", block: true)) + ]) + .join() +) +A space is required to display consecutive math letters, like ```typst $m c^2$``` for $m c^2$. + +This package has you covered on some common multi-letter operators: +#showcode(```typst +Inline math: +$lim_(x->oo), limm_(x->oo)$ +$sum_(i=1)^n, summ_(i=1)^n$ + +Block/display math: +$ + lim_(x -> oo) \ + sum_(i = 0)^n \ + dd(t), dv(,x), dv(y,x) +$ +```) + +/ Caution: Though you can, and sometimes want to use block style in inline math, be aware that bigger math expressions occupy more vertical space, separate or overlap with surrounding texts. + +For "block" or "display" math, leave a space or newline between _both_ dollar signs and the equations. +#showcode(```typst +$ E = m c^2 $ +```) + +To break a line in math, use a backslash "\\". +To align expressions in display math, place an "&" on each line where you want them to align to; you may even use multiple "&"s to align equations that are too long to stay in one part. +#showcode(```typst +$ + x + y &= z \ + &= v \ + // place '&' + // anywhere appropriate + x = w - y& +$ +```) + +Documented are the built-in #link("https://staging.typst.app/docs/reference/math/")[math functions] and #link("https://staging.typst.app/docs/reference/symbols/sym/")[symbols] + +== Texts In Math +To display normal text in math mode, surround the text with double quotes function. +#showcode(```typst +$x = "We are going to find out!"$ +```) + +If you are to display units, see #link()[Units and Quantities]. + +For non-unit, single-character normal text, use ```typc upright()```. +#showcode(```typst +$U upright(W) U$ +```) + +There are other text styles available in math mode. +#showcode(```typst +$serif("Serif") \ +sans("Sans-serif") \ +frak("Fraktur") \ +mono("Monospace") \ +bb("Blackboard bold") \ +cal("Calligraphic")$ +```) + +== Numbering and Referencing Equations +Note that you must enable equation numbering to reference equations, which this template does. Attach a ```typm #

O presente estudo avalia os efeitos do Programa Bolsa Família (PBF) no mercado de trabalho das famílias pobres que residem em áreas rurais do Brasil. Para a análise, foi utilizado o Censo Demográfico (2010) e duas metodologias: Balanceamento por Entropia e Efeito Quantílico de Tratamento (EQT), que verificam o efeito médio e ao longo da distribuição, respectivamente. Visando melhorar o equilíbrio entre o grupo de tratados e controle foi aplicado o algoritmo CEM, desenvolvido por Iacus, King e Porro (2009). Dessa forma, combinou-se o CEM com o balanceamento por entropia para determinar o Efeito Médio de Tratamento sobre os Tratados (ATT). Como resultado, observou-se que no Brasil e regiões as horas trabalhadas dos beneficiários são menores que a dos não beneficiários, assim como a renda do trabalho. Quanto aos efeitos na distribuição, para a maioria dos quantis o efeito é nulo, entretanto, em alguns quantis, os beneficiários possuem menos horas trabalhadas que os não beneficiários. Portanto, os resultados na média indicaram um possível “efeito desincentivo” do programa sobre as horas trabalhadas, ocasionando uma redução na renda das famílias proveniente do trabalho. Por outro lado, na análise por quantis não se pode afirmar o mesmo, visto que os resultados dos efeitos nas horas trabalhadas foram distintos.

+ + + + <italic>Abstract:</italic> + +

This study evaluates the effects of the Bolsa Família Program (PBF) in the labor market of poor families living in rural areas of Brazil. For the analysis, we used the Census (2010) and two methodologies: Balancing Entropy Quantílico and treatment effect (EQT), checking the average effect and throughout the distribution, respectively. To improve the balance between the treated group and control was applied CEM algorithm developed by Iacus, King, and Porro (2009). Thus, combined with the CEM balancing entropy to determine the Average Treatment Effect on Treaties (ATT). As a result, it was observed that in Brazil and regions, the working hours of the beneficiaries is lower than that of non-beneficiaries, as well as labor income. The effects on distribution, for most quantile the effect is null, however, in some quantile, beneficiaries have fewer working hours than non beneficiaries. Therefore, the results in the average indicated a possible "disincentive effect" of the program on the hours worked, causing a decrease in household income from work. On the other hand, the analysis by quantile can not say the same, as the results of the effects on hours worked were different.

+
+ + Palavras-Chave: + Programa Bolsa Família + entropia + Efeito Quantílico de Tratamento + mercado de trabalho. + + + + <bold><italic>Keywords</italic>:</bold> + + Bolsa Família Program + Entropy + Quantílico Treatment Effect + Label Market. + + + + + + + + + + + + + 1 Introdução +

O meio rural vem passando por diversas transformações nas últimas décadas, entre elas está a adoção do modelo de modernização do setor agrícola, ocorrida em meados da década de 1960, com a introdução de meios de produção mais avançados e de políticas públicas destinadas a este setor. Consequentemente esse período marcou o início de um novo modelo econômico no país por meio da mudança do chamado modelo de substituição de importações pela modernização do setor agrário e formação do Complexo Agroindustrial (Teixeira, 2005).

+

De acordo com Ferreira et al. (2006), embora tenha havido uma mudança produtiva na agropecuária brasileira, essa mudança se deu de forma desigual entre as regiões do país. Goodman, Sorj e Wilkison (1985apudNascimento et al., 2008), destacam que os médios e grandes produtores foram os mais beneficiados, principalmente aqueles que se direcionavam para a produção de produtos de exportação e/ou ligados às agroindústrias, em especial os do Centro-Sul do país. Conforme Teixeira (2005), os produtores das pequenas propriedades não foram incluídos nesse processo de modernização devido aos altos custos de produção. Assim, alguns pequenos produtores (principalmente aqueles que praticavam agricultura de subsistência) abandonaram as atividades agrícolas, deixando o campo e migrando para os centros urbanos.

+

Já na década de 1990, a abertura comercial brasileira foi implementada pelo governo Collor, na qual foi eliminada a maior parte das barreiras não-tarifárias e reduziu gradativamente o nível e o grau de proteção da indústria local (Averbug, 1999). Com isso, a entrada de produtos agrícolas similares aos nacionais foi permitida, aumentando a concorrência no mercado interno (Carvalho; Marinho, 2003). Aliada à abertura comercial, outras mudanças sofridas no período foram responsáveis pela diminuição da oferta de empregos no setor agrícola, como a redução de incentivos do governo, a sobrevalorização do câmbio e a queda do preço dos produtos agrícolas (Santos et al, 2010).

+

Todos esses desdobramentos ampliaram ainda mais as disparidades de renda no meio rural. Incapazes de competir com a grande indústria rural, os pequenos produtores que escolheram continuar no campo, passaram a buscar outras formas de sobrevivência além da produção para o autoconsumo, assim, conforme Santos et al. (2010), atividades não agrícolas, como artesanato, cultivo de flores, ecoturismo, prestação de serviços e comércio, viraram fontes de renda, viabilizando a permanência nas áreas rurais.

+

Diante disso, o meio rural apresenta uma grande distorção em relação à área urbana quanto a alguns indicadores, como menor rendimento médio familiar e maior percentual de famílias pobres e extremamente pobres (IBGE, 2015). Na tentativa de reverter ou amenizar esse quadro, algumas estratégias vêm sendo empregadas na esperança de fortalecer e promover o segmento rural, como políticas de crédito e programas de transferências de renda, em especial, o Programa Bolsa Família (PBF).1 +

+

O PBF é um programa de transferência direta de renda condicionada e foi criado pelo Governo Federal com o objetivo de, no curto prazo, aliviar a situação de pobreza e promover segurança alimentar e nutricional das famílias que se encontram em posição de vulnerabilidade social em todo o país, impondo condicionalidades nas áreas da educação, saúde e assistência social.

+

As maiores críticas e questionamentos são a respeito de um possível efeito negativo que o programa possui sobre o mercado de trabalho, o chamado “efeito desincentivo” (Costa et al., 2014) ao trabalho. Segundo Tavares (2008), esse efeito, também conhecido como efeito-renda, trata da redução da oferta de trabalho dos membros adultos das famílias beneficiadas em vista das transferências monetárias recebidas por estes. Ou seja, existe um tipo de recompensa pela perda salarial por meio da transferência de renda repassada às famílias, assim, a renda familiar não é comprometida.

+

Alguns trabalhos empíricos foram realizados com o objetivo de mostrar possíveis impactos do Programa Bolsa Família no mercado de trabalho, a exemplo de Ferro e Nicollela (2007), Teixeira (2008), Tavares (2008) e Costa et al. (2014).

+

Ferro e Nicollela (2007) analisaram o efeito das transferências de renda condicionadas quanto à taxa de participação e as horas trabalhadas dos adultos nas áreas urbanas e rurais, com base nos dados da PNAD do ano de 2003. Os efeitos encontrados foram positivos e significativos apenas para homens e mulheres residentes em áreas urbanas e negativo para mulheres residentes em áreas rurais.

+

Teixeira (2008) estima o efeito do PBF na oferta de trabalho em atividades formais e informais de homens e mulheres beneficiários do programa, com dados da PNAD 2006. O cálculo é feito por meio do efeito médio do tratamento (Average Treatment Effect on the Treated - ATT) e a análise gráfica do efeito local do programa (Average Local Effect - ALE). Os resultados apontam que o PBF tem efeito negativo na oferta de trabalho das mulheres. Por sua vez, na oferta de trabalho dos homens, o efeito é negativo para os que trabalham por conta própria e nulo para os que trabalham no mercado formal.

+

Tavares (2008) investigou o impacto do PBF sobre a oferta de trabalho das mães beneficiadas. Foram utilizados dados da Pesquisa Nacional por Amostra Domiciliar (PNAD), referentes ao ano de 2004, e o método do Propensity score Matching (PSM) para assim fazer um confractual e encontrar mães que não foram beneficiadas pelo programa comparáveis às mães que foram. Os resultados encontrados evidenciam um pequeno efeito-renda negativo, mas que não é suficiente para gerar um efeito-desincentivo ao trabalho. Entretanto, também foi observado um efeito positivo que se sobrepõe ao efeito negativo, a autora explica que isso pode decorrer devido a uma maior disponibilidade de tempo das mães para trabalhar, visto que as crianças e jovens têm um aumento da frequência escolar e assim reduzem sua oferta de trabalho.

+

Costa et al. (2014) fizeram uma análise do impacto do PBF na renda e nas horas de trabalho das famílias pobres em todas as regiões brasileiras. Para a análise, foram utilizados dados do Censo (2010) do IBGE e o método do Efeito Quantílico do Tratamento (EQT), em especial o estimador proposto por Firpo (2007). Os resultados mostraram que em grupos específicos de famílias beneficiadas houveram menos horas trabalhadas e uma menor renda do trabalho quando comparado às famílias não beneficiadas. No tocante às regiões, os resultados foram distintos, tendo as regiões Nordeste e Norte efeitos negativos no mercado de trabalho, enquanto os resultados para as demais regiões foram mais homogêneos. Também foi possível observar efeitos para o Brasil urbano e Brasil rural, no qual os impactos foram diferentes, com efeitos neutros, positivos e negativos para os dois casos, entretanto o efeito desincentivo ao trabalho foi mais forte no Brasil rural do que no urbano, especialmente nos quantis mais elevados. Os autores indicam que parte dessas diferenças observadas pode ter ligação com o dinamismo econômico específico de cada região.

+

Diante do exposto, surgem alguns questionamentos: o Programa Bolsa Família gera “efeito-desincentivo” ao trabalho nas famílias beneficiadas pelo programa situadas nas áreas rurais? Caso provoque, esse impacto é observado em todos os estratos de renda e nas horas trabalhadas?

+

Bem como Costa et al. (2014), este estudo fará uso da metodologia de Firpo (2007), entretanto, cabe destacar que os autores verificam os efeitos do Programa Bolsa Família no meio rural do Brasil como um todo, porém, neste artigo, será analisado o meio rural das regiões do Brasil. Além disso, o presente trabalho capta o efeito médio de tratamento sobre os tratados por meio da combinação das metodologias CEM (2009) e Balanceamento por Entropia (2011). Dessa forma, a contribuição deste trabalho para a literatura se apresenta, principalmente, por mensurar o efeito do programa, especificamente para as áreas rurais das regiões brasileiras, na média e em toda a distribuição, permitindo verificar os estratos de renda e as horas de trabalho semanais, nos quais o efeito é mais expressivo.

+

Este artigo está estruturado em quatro seções, incluindo esta introdução. A metodologia será apresentada na segunda seção. Os resultados podem ser observados na seção três. E, por último, as considerações finais do trabalho serão apresentadas na seção quatro.

+
+ + 2 Metodologia e base de dados + + 2.1 Modelos Econométricos + + 2.1.1 Algoritmo CEM +

Um problema associado aos métodos de matching baseados no propensity score é o seu fraco desempenho em encontrar grupos de comparação equilibrados. De fato, o alvo principal dos métodos de matching consiste em eliminar observações de modo a obter um melhor equilíbrio comparativo entre grupos tratados e o grupo de controle (Blackwell et al., 2009).

+

Para tentar contornar esses problemas, Iacus, King e Porro (2009) desenvolveram o algoritmo Coarsened Exact Matching (CEM), o qual não exige nenhuma hipótese sobre o processo de geração de dados (DGP), com exceção da ignorabilidade. Além disso, tal método garante que os desiquilíbrios entre os grupos de tratados e de controle pós o matching não sejam maiores que um limite previamente selecionado.

+

Iacus, King e Porro (2009, 2011) mostraram por meio de simulações de um grande número de DGPs que CEM possui propriedades estatísticas superiores aos métodos tradicionais, como menor desiquilíbrio entre grupos pós matching, menor dependência do modelo, dentre outros. Além disso, o CEM permite a melhora da análise de outros métodos, como o próprio PSM e a Entropia, por exemplo. Diversos autores têm aplicado esse método na literatura em muitas áreas, tais como, Aroca et al. (2014) e Schurer et al. (2015).

+

O algoritmo do CEM segue os seguintes passos:

+

+ + +

Dado as covariadas X, é realizado uma cópia de X, denominada X*;

+ + +

X* é “engrossado” (coarsened) ou de acordo com cortes amostrais previamente selecionados ou utilizando um método automático desenvolvido por Iacus, King e Porro (2009);

+
+ +

Cria-se um estrato por unidade de observação de X* e se coloca cada observação no estrato;

+
+ +

Relaciona o estrato com os dados originais, X, e elimina-se as observações do estrato que não contém ao menos um tratado ou uma unidade de controle.

+
+ +

+

Iacus, King e Porro (2009) desenvolvem uma medida de desequilíbrio global, dada pela estatística L1, em que esta é baseada na diferença entre histogramas multidimensionais de todas as covariadas de pré-tratamento nos grupos de tratados e controles e pode ser representada por: \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \(${{\mathcal{L}}_{1}}\left( f,g \right)=\frac{1}{2}\underset{{{l}_{1}}\ldots {{l}_{k}}}{\mathop \sum }\,\left| {{f}_{{{l}_{1}}\ldots {{l}_{k}}}}-{{g}_{{{l}_{1}}\ldots {{l}_{k}}}} \right| \) \end{document} . O equilíbrio perfeito global é encontrado por L1=0, e valores elevados para L1 indicam grandes desequilíbrios entre os grupos, com valor máximo de L1 = 1, no qual indica completa separação. Denote as frequências relativas dos dados pareados por fm e gm, então uma boa solução para o pareamento produzirá uma redução na estatística L1, ou seja, \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{\mathcal{L}}_{1}}\left( {{f}^{m}},~{{g}^{m}} \right)\le {{\mathcal{L}}_{1}}\left( f,g \right) \) \end{document} .

+

Neste trabalho não será utilizado o CEM para a comparação direta entre grupos de tratados e de controle, mas sim, para melhorar o desempenho de outro método ao escolher mais adequadamente, com menos desequilíbrio, as observações a serem pareadas.

+
+ + 2.1.2 Entropia +

Hainmueller (2012) desenvolveu um método multivariado que permite ponderar um conjunto de dados, tais que, as distribuições das variáveis nas observações reponderadas satisfaçam um conjunto de condições especiais de momentos, de forma que exista equilíbrio exato sobre o primeiro, segundo, e possivelmente maiores momentos das distribuições de variáveis independentes nos grupos de tratamento e controle. Esse método permite que o pesquisador especifique um nível de equilíbrio desejável para as covariadas usando um conjunto de condições associadas aos momentos da distribuição.

+

Considere uma amostra com n1, observações pertencentes ao grupo dos tratados, e n0 unidades de controle, os quais foram selecionados aleatoriamente de uma população de tamanho N1 e N0 respectivamente \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{n}_{1}}\le {{N}_{1}}~e~{{n}_{0}}\le {{N}_{0}}~ \) \end{document} . Seja \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{D}_{i}}\in \left\{ 1,0 \right\} \) \end{document} uma variável de tratamento binária, em que irá assumir o valor igual a 1 se a unidade i pertencer ao tratamento e 0 se pertencer ao grupo de controle. Seja X uma matriz que contém as observações de J variáveis exógenas de pré-tratamento; Xij corresponde o valor da j-ésima covariada da unidade i, tais que, Xi = (Xi1,Xi2,...,Xij), refere-se ao vetor de características da unidade i, e Xj refere-se ao vetor coluna com j-th covariada. A densidade das covariadas nas populações de tratamento e controle são dadas por \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{f}_{X|D=1}}~e~{{f}_{X|D=0}} \) \end{document} respectivamente. O resultado potencial Yi(Di) corresponde ao par de resultados para a unidade i dadas as condições de tratado e controle, assim, o resultado observado é dado por Y=Y1D+1-DY(0) +

+

O Efeito Médio Tratamento sobre os Tratados (EMTT) é dado por τ=EY1D=1-E[Y(0)|D=1]. A primeira esperança pode ser diretamente identificada do grupo de tratados, mas a segunda corresponde ao contrafactual, o qual não é observado. Assumindo seleção nos observáveis, \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( Y\left( 0 \right)\bot D|X \) \end{document} , e sobreposição, Pr(D=1|X=x) menor que 1 para todo x no suporte de \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( ~{{f}_{X|D=1}} \) \end{document} o EMTT é identificado como:

+

+ + + + τ + = + E + + + Y + + + D + + + - + + + + E + + + Y + + + X + = + x + , + D + = + 0 + + + + + f + + + X + | + D + = + 1 + + + + + ( + x + ) + d + x + + + + + +

+

Para estimar o último termo da equação 1, a distribuição da covariável no grupo de controle necessita ser ajustada para torná-la semelhante à distribuição no grupo de tratamento, tal que o indicador de tratamento D se torne mais perto de ser ortogonal em relação às covariáveis. Uma variedade de métodos de pré-processamento de dados, tais como pareamento pelo vizinho mais próximo, cem, escore de propensão têm sido propostos para reduzir o desequilíbrio na distribuição de variáveis independentes. Uma vez que as distribuições de variáveis independentes são ajustadas, métodos de análise padrão, tais como a regressão, podem ser posteriormente utilizados para estimar o tratamento com menor erro e modelo de dependência (Imbens, 2004; Rubin, 2006; Ho et al., 2007; Iacus et al., 2011; Sekhon, 2009).

+

Considere o caso mais simples no qual o efeito tratamento nos dados pré-processados é estimado usando a diferença nos resultados médios entre os grupos de tratados e controle ajustado. Um método de pré-processamento popular é usar escore de propensão ponderado (Hirano; Imbens; Ridder, 2003), em que a média contrafactual é estimada como:

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[E\widehat{Y\left( 0 \right)|D=1}=\frac{\mathop{\sum }_{\{i|D=0\}}{{Y}_{i}}{{d}_{i}}}{\mathop{\sum }_{\{i|D=0\}}{{d}_{i}}}\] \end{document} + + + + +

+

Em que as unidades de controle recebem um peso dado por \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{d}_{i}}=\frac{\hat{p}\left( {{x}_{i}} \right)}{1-\hat{p}\left( {{x}_{i}} \right)}.\hat{p}\left( {{x}_{i}} \right) \) \end{document} na equação 2 é o escore de propensão, o qual é comumente estimado por meio de uma regressão probit ou logit. Se este modelo estiver corretamente especificado, então o peso estimado di vai assegurar que a distribuição do covariável das unidades de controle reponderadas irá corresponder à distribuição no grupo de tratamento. No entanto, na prática, essa abordagem muitas vezes não consegue equilibrar conjuntamente todas as covariáveis.

+

O balanceamento por entropia generaliza a abordagem de ponderação do escore de propensão ao estimar os pesos diretamente de um conjunto de restrições de equilíbrio que exploram o conhecimento do pesquisador sobre os momentos de amostra. Considere 𝑤_𝑖 o peso do balanceamento por entropia escolhido para cada unidade de controle, os quais foram encontrados pelo seguinte esquema de reponderação que minimiza a distância métrica de entropia:

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[\underset{{{w}_{i}}}{\mathop{\min }}\,H\left( w \right)=\underset{\{i|D=0\}}{\mathop \sum }\,{{w}_{i}}\text{log}({{w}_{i}}/{{q}_{i}})\] \end{document} + + + + +

+

Sujeito às restrições de equilíbrio e normalização

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[\underset{\left\{ i\text{ }\!\!|\!\!\text{ }D=0 \right\}}{\mathop \sum }\,{{w}_{i}}{{c}_{ri}}\left( {{X}_{i}} \right)={{m}_{r}}\] \end{document} + + + + +

+

Com r E 1, ..., R

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[\underset{\left\{ i\text{ }\!\!|\!\!\text{ }D=0 \right\}}{\mathop \sum }\,{{w}_{i}}=1\] \end{document} + + + + +

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[{{w}_{i}}\ge 0\] \end{document} + + + + +

+

para todo i, tal que D = 0

+

Onde \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{q}_{i}}=\frac{1}{{{n}_{0}}} \) \end{document} é um peso base e cri(Xi) = mr descreve um conjunto de R restrições impostas aos momentos das covariadas no grupo de controle reponderados. Inicialmente, escolhe-se a covariada que será incluída na reponderação. Para cada covariada, especifica-se um conjunto de restrições de balanceamento (Eq. 04) para equiparar os momentos das distribuições das covariadas entre os grupos de tratamento e controles reponderados. As restrições de momentos podem ser a média (primeiro momento), a variância (segundo momento), e a assimentria (terceiro momento). Uma restrição típica do balanceamento é formulada de tal forma que mr contenha o momento de uma covariada específica Xj para o grupo de tratamento e a função de momento para o grupo de controle é especificada como : \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{c}_{ri}}\left( {{X}_{ij}} \right)=X_{ij}^{r}~ou~{{c}_{ri}}\left( {{X}_{ij}} \right)={{\left( {{X}_{ij}}-{{\mu }_{j}} \right)}^{r}} \) \end{document} com média \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{\mu }_{i}} \) \end{document} +

+

Dessa forma, o balanceamento por entropia procura, para um conjunto de unidades, pesos W = (wi,...wn0)', no qual minimiza a equação (3), distância de entropia entre W e o vetor base de pesos Q=(qi,...,qn0)', sujeita às restrições de balanceamento na equação (4), restrição de normalização (equação 5), e restrição de não-negatividade (Equação 6).

+

Segundo Hainmueller (2012), o método da entropia pode ser combinado com outros métodos de pareamento, tais como, CEM e PEP, visando, assim, equilibrar com maior robustez as covariadas. Nesse caso, o autor sugere aplicar inicialmente o CEM, para desconsiderar as unidades de tratados e controles desequilibradas, e em seguida fazer a ponderação via entropia. Dessa forma, este trabalho irá seguir esse procedimento, minimizando os desequilíbrios entre os grupos de tratados e controle.

+
+ + 2.1.3 Efeito quantílico de tratamento - Modelo de <xref ref-type="bibr" rid="B10">Firpo (2007</xref>) +

O modelo de efeito quantílico de tratamento exógeno e não condicional proposto por Firpo (2007) será utilizado para obter o efeito do PBF nas áreas rurais. Isso porque uma família pode ou não pertencer ao programa devido a fatores aleatórios, dada uma restrição de renda e características observáveis, portanto, o tratamento utilizado deve ser exógeno. E não condicional deve-se ao fato de muitas famílias serem elegíveis ao programa, mas que não são selecionadas devido aos recursos direcionados ao programa serem limitados, dessa forma, a participação ou não condicional das famílias é feita de forma aleatória.

+

Neste estudo, o tratamento diz respeito a receber ou não o benefício do PBF, portanto os beneficiários do PBF fazem parte do grupo de tratamento e os não beneficiários do grupo de controle. Visto isso, o modelo de EQT de Firpo (2007) é definido a seguir.

+

Seja T a variável que indica o tratamento para um indivíduo i, que assume valores de 0 e 1. Se Ti=1 o indivíduo assume a forma de tratado e se Ti=0, de não tratado. Seja Yi a variável de resposta desse evento, ou seja, os resultados potenciais de receber ou não o tratamento, dessa forma, se Yi(1) o indivíduo recebe o tratamento e se Yi(0), não recebe o tratamento. Então, define-se o resultado observado como:

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[{{Y}_{i}}=~{{Y}_{i}}\left( 1 \right)-~{{T}_{i}}+~{{Y}_{i}}\left( 0 \right)-~\left( 1-{{T}_{i}} \right)\] \end{document} + + + + +

+

Diante disso, definindo τ como um número real em [0,1] o efeito quantílico de tratamento (EQT) é dado por:

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[{{q}_{t}}~=~{{q}_{1,\text{ }\!\!\tau\!\!\text{ }}}-~{{q}_{0,\text{ }\!\!\tau\!\!\text{ }}}\] \end{document} + + + + +

+

onde \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{q}_{j,\text{ }\!\!\tau\!\!\text{ }}}\equiv in{{f}_{q}}\Pr \left[ Y\left( j \right)\le ~{{q}_{j,\text{ }\!\!\tau\!\!\text{ }}} \right]\ge \text{ }\!\!\tau\!\!\text{ },\text{ }\!\!~\!\!\text{ j}=0,1 \) \end{document} +

+

A expressão acima mostra que o EQT é a diferença entre os valores do quantil τ das funções de distribuição cumulativas da variável resposta referentes ao grupo de tratamento e o de controle, para um dado quantil. Para estimar o EQT é necessário seguir duas etapas: em primeiro lugar, estima-se o escore de propensão e posteriormente calcula-se a diferença entre tratados e não tratados. Os estimadores do escore de propensão são definidos como a probabilidade condicional de receber um tratamento, dado por características de pré-tratamento observáveis:

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[p\left( X \right)=\Pr \left( T=1\text{ }\!\!|\!\!\text{ }X=x \right)\] \end{document} + + + + +

+

A utilização do escore de propensão requer que sejam adotadas três hipóteses: independência condicional, suporte comum e quantis bem definidos e únicos. A hipótese de independência condicional implica que os valores de Yi independem da aplicação do tratamento, condicionada a um determinado conjunto de variáveis X observáveis:

+

+ + + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[{{Y}_{i}}\left( 1 \right),~{{Y}_{i}}\left( 0 \right)~\bot {{T}_{i}}|{{X}_{i}}$ \] \end{document} + + + +

+

Já a hipótese de suporte comum garante que as observações de tratamento têm observações de comparação "nas proximidades" na distribuição de escore de propensão, ou em outros termos:

+

Para algum

+

+ + + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[c > 0, c < p(x) < 1 – c\] \end{document} + + + +

+

Hipótese 3: Para j=0,1, Y(j) é uma variável aleatória contínua com suporte em R, no qual há um conjunto não vazio de Y1 e Y1, de tal forma que \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( {{Y}_{i}}=\{\text{ }\!\!\tau\!\!\text{ }\in ~\left( 0,1 \right);\text{ }\!\!~\!\!\text{ Pr}\left[ Y\left( j \right)\le {{q}_{j,\text{ }\!\!\tau\!\!\text{ }}}\text{ }\!\!~\!\!\text{ }\text{ }\!\!~\!\!\text{ c} \right]\text{ }\!\!~\!\!\text{ }\left\langle \text{Pr}\left[ Y\left( j \right)\le {{q}_{j,\text{ }\!\!\tau\!\!\text{ }}}+\text{ }\!\!~\!\!\text{ c} \right],~\forall ~c~\in R,c \right\rangle 0~ \) \end{document} . Essa hipótese que mostra que os quantis são bem definidos e únicos.

+

Cabe mencionar que diferentemente da metodologia exposta na subseção anterior, a metodologia de Firpo (2007) não faz o pareamento (matching) dos escores de propensão, e a estimação do escore de propensão é feita por meio de um modelo logit global. Dessa forma, o estimador de EQT é dado por \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \( \overset{\hat{\ }}{\mathop{q}}\,t=~{{\hat{q}}_{1,~\text{ }\!\!\tau\!\!\text{ }}}-{{\hat{q}}_{0,\text{ }\!\!\tau\!\!\text{ }}} \) \end{document} em que:

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[{{\hat{q}}_{j,~\text{ }\!\!\tau\!\!\text{ }}}\equiv \arg mi{{n}_{q}}\underset{i=1}{\overset{N}{\mathop \sum }}\,{{\hat{w}}_{j,\text{ }\!\!\tau\!\!\text{ }}}~.~{{\rho }_{\text{ }\!\!\tau\!\!\text{ }}}\left( {{Y}_{i}}-~q \right)\] \end{document} + + + + +

+

De tal forma que os quantis podem ser estimados mediante a minimização de uma soma da função check 𝜌 (.), assim como foi proposto por Koenker e Basset (1978) apud Cavalcanti (2013). Os pesos de cada uma das observações, wi, é dada pela seguinte expressão:

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[{{\hat{w}}_{1,\text{ }\!\!\tau\!\!\text{ }\!\!~\!\!\text{ }}}=\frac{{{T}_{i}}}{N.\hat{p}\left( {{X}_{i}} \right)}\] \end{document} + + + + +

+

e

+

+ + + \documentclass {article} \usepackage{wasysym} \usepackage[substack]{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsbsy} \usepackage[mathscr]{eucal} \usepackage{mathrsfs} \usepackage{pmc} \usepackage[Euler]{upgreek} \pagestyle{empty} \oddsidemargin -1.0in \begin{document} \[{{\hat{w}}_{o,\text{ }\!\!\tau\!\!\text{ }\!\!~\!\!\text{ }}}=~\frac{1-{{T}_{i}}}{N.\left( 1-\hat{p} \right)\left( {{X}_{i}} \right)}\] \end{document} + + + +

+
+
+ + 2.2 Grupos de tratamento e controle +

A avaliação do impacto do Bolsa Família no mercado de trabalho será realizada por meio da comparação dos resultados de dois grupos, tratamento, o qual considera as famílias que atendem aos critérios de elegibilidade e são beneficiárias do programa; grupo de controle, composto pelas famílias que atendem aos critérios de elegibilidade, mas que não são beneficiárias, pois não foram selecionadas por algum motivo.

+
+ + 2.3 Base de dados e variáveis do modelo +

Os dados utilizados neste trabalho foram retirados do Censo Demográfico realizado pelo Instituto Brasileiro de Geografia e Estatística (IBGE) para o ano de 2010.2 +

+

Seguindo Costal et al. (2014), os impactos dos Programa Bolsa Família no mercado de trabalho serão avaliados utilizando duas variáveis de resultado: horas trabalhadas do chefe familiar, pois, pretende-se analisar se o programa reduz ou não as horas trabalhadas dos chefes beneficiários, verificando se realmente há um efeito desincentivo ao trabalho devido ao repasse monetário; e renda do trabalho per capita, que busca verificar se a renda das famílias oriunda do trabalho está aumentando ou reduzindo por possíveis efeitos negativos, de desincentivo ao trabalho, do programa.

+

Para fazer uma comparação dos resultados dos grupos de tratamento e de controle, é necessário que os dois grupos sejam bastante homogêneos entre eles. Assim, com o intuito de garantir que o modelo capte o efeito do programa, fez-se necessário controlar características observáveis do grupo familiar e do domicílio. Para tanto, o CadÚnico foi utilizado como referência para verificar quais são as variáveis registradas nesse sistema que são pertinentes para a determinação do recebimento do programa.

+

O grupo de covariadas é dividido em quatro categorias, como mostra o quadro 1 abaixo.

+

+ + + + Covariadas utilizadas para o matching + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TipoVariável
Caraterísticas do chefe familiar Idade
+ Gênero (1=homem, 0=mulher)
+ Cor (1=branco, 0=não branco)
+ Cônjuge (1=casado(a), 0=não casado(a))
+ Escolaridade (dummies)
+ Trabalha (1=trabalha, 0=não trabalha)
+ Carteira de trabalho assinada (1=possui, 0=não possui)
Composição familiar: Nº de pessoas
+ Nº de filhos (por faixa etária)
+ Nº de filhos homens (1=filho homem, 0=caso contrário)
+ Nº de filhos brancos (1=filho branco, 0= caso contrário)
Outras características dos componentes domiciliaresDeficiência auditiva (1=possui, 0=não possui)
+ Deficiência física (1=possui, 0=não possui)
+ Deficiência visual (1=possui, 0=não possui)
+ Deficiência mental (1=possui, 0=não possui)
Outras características do município Próprio (1=é, 0=caso contrário)
+ Tipo de domicílio (1=casa/apartamento, 0=oca/barraca/cortiço)
+ Domicílios de alvenaria (1=alvenaria, 0=caso contrário)
+ Rede de água tratada (1=possui, 0=não possui)
+ Eletricidade (1=possui, 0=não possui)
+ Saneamento (1=possui, 0=não possui)
+ Coleta de lixo (1=possui, 0=não possui)
+
+ + +

Fonte: Elaborado pelos autores com base na pesquisa

+ + + +

+
+
+ + 3 Resultados + + 3.1 Estatísticas descritivas +

A distribuição dos domicílios rurais pobres elegíveis para o Programa Bolsa Família pode ser observada na Tabela 1. Os dados amostrais denotam um total de 430.227 unidades domiciliares, e, quando ponderados pelo peso, os dados do Universo mostram que os números de domicílios correspondem a 2.742.705.

+

No Brasil, o percentual de famílias beneficiadas pelo PBF no meio rural equivale a 59,60% do total de famílias elegíveis. Quando a análise é feita por regiões, percebe-se que o Nordeste é responsável pela maior quantidade de famílias beneficiadas, tanto em termos absolutos quanto relativos, com cerca de 68,68% da amostra de 261.500 domicílios e representando 72,03% do total dos beneficiários do país. Em seguida, destacam-se as regiões Norte e Sudeste, que participam com 12,98% e 8,93%, respectivamente, no total de beneficiários no Brasil, mas só contemplam 46,20% (Norte) e 46,94% (Sudeste) das famílias elegíveis em suas regiões. Já as regiões Sul e Centro-Oeste possuem participações menos expressivas, representando 4,02% e 2,03% dos beneficiários no país e com menos de 40% de suas populações recebendo benefícios.

+

+ + + + Estatísticas descritivas - Brasil e Regiões - Rural - 2010 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RegiõesAmostraUniverso¹ Beneficiários do PBF (%)Participação dos Beneficiários do PBF no Total de Beneficiários do Brasil
Brasil430.2272.742.70559,60%100,00%
Nordeste261.5001.714.33468,68%72,03%
Norte62.050459.11946,20%12,98%
Sudeste55.450311.13046,94%8,93%
Sul34.386162.91340,33%4,02%
Centro-Oeste16.84195.21034,93%2,03%
+
+ + +

Nota: (1) Os dados do Universo são obtidos por meio da ponderação com os pesos divulgados pelo Censo (2010).

+ + +

Fonte: Elaborado pelos autores com base nos dados do Censo Demográfico (2010)

+
+ + +

+

Analisando as estatísticas descritivas das variáveis utilizadas para mensurar o impacto do Bolsa Família no mercado de trabalho3 constata-se que as horas trabalhadas dos chefes familiares e a renda do trabalho per capita nas regiões Nordeste e Norte, tanto dos beneficiários como dos não beneficiários do programa, ficam abaixo da média do Brasil e das demais regiões. Além disso, é possível perceber uma grande disparidade entre a renda do trabalho per capita dos beneficiários e não beneficiários.

+

No Brasil, as famílias que são beneficiadas pelo PBF recebem R$37,41 a menos que as famílias não beneficiadas. Regionalmente, essas disparidades são mais expressivas nas regiões Centro-Oeste (R$37,62), Norte (R$35,41) e Nordeste (R$34,01). É interessante observar que, embora os beneficiários possuam uma menor renda do trabalho se comparados aos não beneficiários, a proporção da população beneficiária que trabalha é superior a não beneficiária em quase todas as regiões, à exceção da região Sul (em que as proporções são iguais). Isto é, as ocupações dos beneficiários devem ter baixas remunerações.

+

As famílias que recebem o programa têm em média três filhos, por outro lado, as famílias não beneficiadas têm em média 2 filhos. Outro fator relevante é o baixo nível de instrução dos chefes familiares: a grande maioria apenas sabe ler ou somente possui o grau primário. Essa baixa escolaridade dificulta o processo de qualificação e a conquista de melhores postos de trabalho. Além disso, apesar de uma grande parcela de chefes familiares estar ocupada, somente um pequeno percentual possui carteira de trabalho assinada, ou seja, uma elevada quantidade de trabalhadores deve estar no mercado informal, trabalhando por conta própria ou para o seu próprio sustento. As regiões Sudeste, Centro-Oeste e Sul possuem relativamente mais trabalhadores com carteira assinada - tanto para beneficiários do programa quanto para os não beneficiários - do que as regiões Nordeste e Norte, estas últimas ainda ficam abaixo da média brasileira.

+

As demais características do chefe domiciliar, dos componentes familiares e do domicílio são bastante semelhantes para todas as regiões, porém algumas características do domicílio para a região Norte estão abaixo das demais regiões, a exemplo do percentual de residências com água encanada, coleta de lixo, saneamento e eletricidade.

+
+ + 3.2 Resultados do balanceamento + + 3.2.1 Impacto do Programa Bolsa Família nas horas trabalhadas do chefe familiar +

Conforme Hainmueller e Xu (2013), pode-se combinar o CEM com a Entropia. Assim, foi realizado o balanceamento pelo método CEM e posteriormente o balanceamento por entropia, a fim de permitir que o grupo de tratados e controle fosse o mais semelhante possível. A tabela 2 abaixo mostra os resultados do desequilíbrio global4 entre as covariáveis do grupo de tratados e controle, antes e após a aplicação do algoritmo CEM, bem como as observações para os pareados e não pareados após o balanceamento.

+

Ao comparar os resultados de desequilíbrio (estatística L1 antes do balanceamento; estatística L1 após o balanceamento), observa-se, na Tabela 2, que para as horas trabalhadas houve uma redução dessa medida entre as covariáveis dos dois grupos, tanto para o Brasil como para as regiões, demonstrando que a aplicação desse algoritmo proporcionou um melhor equilíbrio entre tratados e controle. Para o Brasil, a amostra, a partir desse método, passou a conter 19.860 tratados e 18.444 controles comparáveis. Nota-se ainda que ao aplicar o CEM o balanceamento melhorou, mas ainda existem diferenças entre os dois grupos. Portanto, faz-se necessária a aplicação do balanceamento por entropia para dar mais robustez à análise.

+

+ + + + Balanceamento CEM - Brasil e Regiões - Rural + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Brasil Norte Nordeste Sudeste Sul Centro-Oeste
L1 - Antes do CEM 0,8904 0,9299 0,9151 0,9265 0,9258 0,9839
L1 - Após o CEM0,6293 0,4734 0,5411 0,4970 0,5845 0,2212
Algoritmo CEMTratadosControleTratadosControleTratadosControleTratadosControleTratadosControleTratadosControle
+ 101010101010
Total de Observações64.01039.6387.1687.83042.51616.7687.7875.9125.4097.3521.1301.776
Comparáveis – Após o CEM 19.86018.4441.1991.7049.3247.1131.3541.4451.1781.8595895
Não Comparáveis – Após o CEM44.15021.1946.1266.12633.1929.6556.4334.4674.2315.4931.0721.681
+
+ + +

Fonte: Dados da pesquisa.

+ + +

Elaboração: Autores

+
+ + +

+

Com relação ao balanceamento por Entropia, a Tabela 3 abaixo mostra que, para o Brasil Rural, o comportamento da média, variância e assimetria da distribuição antes e após o procedimento de balanceamento eram distintos entre os grupos analisados.

+

+ + + + Balanceamento por Entropia Covariadas das Horas Trabalhadas - Brasil Rural + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Antes do Balanceamento por Entropia Após o Balanceamento por Entropia
CovariadasTratados Controles Tratados Controles
+ MédiaVariânciaAssimetriaMédiaVariânciaAssimetriaMédiaVariânciaAssimetriaMédiaVariânciaAssimetria
chef_homem0,80520,1568-1,54200,81330,1518-1,60800,80520,1568-1,54200,80520,1568-1,5410
chef_branco0,27590,19981,00300,32730,22020,73630,27590,19981,00300,27590,19981,0030
ensino_2 grau0,03970,03814,71600,05760,05433,79800,03970,03814,71600,03970,03814,7160
ensino_ginásio0,13670,11802,11600,17570,14481,70500,13670,11802,11600,13670,11802,1150
ensino_primário0,61800,2361-0,48580,56050,2464-0,24380,61800,2361-0,48580,61800,2361-0,4858
ensino_superior0,00010,0001140,900,00010,0001135,800,00010,0001140,900,00010,0001140,90
nfilho_50,58780,56761,11800,56420,57811,21400,58780,56761,11800,58780,56761,1180
nfilho_100,55600,50661,02900,33050,37461,85200,55600,50661,02900,55590,50661,0300
nfilho_150,45350,48031,36300,27150,32972,19100,45350,48031,36300,45350,48031,3630
nfilho_170,10110,09372,79300,06990,06703,54200,10110,09372,79300,10110,09372,7930
nfilhos_180,23280,36603,12500,21110,33133,34300,23280,36603,12500,23280,36603,1260
filho_branco0,33440,22260,70180,30700,21280,83670,33440,22260,70180,33440,22260,7019
Cegueira0,00860,008510,670,01170,01169,080,00860,008510,670,00860,008510,67
Surdez0,00040,000449,790,00040,000447,980,00040,000449,790,00040,000449,79
Mental0,00030,000363,000,00030,000355,420,00030,000363,000,00030,000363,00
Fisica0,00100,001031,460,00140,001427,110,00100,001031,460,00100,001031,46
cart_trab0,00430,004315,190,00480,004714,370,00430,004315,190,00430,004315,19
agro_chef0,78510,1687-1,38800,80560,1566-1,54500,78510,1687-1,38800,78510,1687-1,3880
condi_dom0,88000,1056-2,33800,86660,1156-2,15700,88000,1056-2,33800,88000,1056-2,3380
material_dom0,75720,1839-1,200,66500,2228-0,69940,75720,1839-1,200,75720,1839-1,20
tipo_dom0,99880,0012-29,330,99840,0016-25,160,99880,0012-29,330,99880,0012-29,33
saneamento0,03280,03185,24300,04130,03964,61300,03280,03185,24300,03280,03185,2430
agua_canalizada0,18660,15181,60900,16250,13611,83000,18660,15181,60900,18660,15181,6090
tratam_lixo0,05960,05603,72200,06970,06483,38100,05960,05603,72200,05960,05603,7220
eletricidade0,86100,1197-2,08700,79900,1606-1,49200,86100,1197-2,08700,86100,1197-2,0870
idade_chefe37,5896,160,354537,56139,100,278037,5896,160,354537,5896,180,3544
+
+ + +

Fonte: Dados da Pesquisa

+ + +

Elaboração: Autores

+
+ +

Nota: O tamanho da amostra após o balanceamento por entropia não se alterou, permanecendo 19.860 tratados e 18.444 controles.

+
+ + +

+

Verificando as covariadas, percebe-se que antes do ajustamento à média, a variância e assimetria entre o grupo dos tratados e controles eram diferentes. Após o balanceamento, houve o ajustamento dessas estatísticas para todas as covariadas inseridas, ou seja, o balanceamento está perfeitamente ajustado para os três primeiros momentos da distribuição das variáveis independentes. Ademais, os resultados para as regiões rurais indicaram resultados similares ao encontrado para o Brasil. A região Centro-Oeste foi a única em que os resultados não foram perfeitamente ajustados, entretanto, são valores muito próximos.5 +

+

Posteriormente ao pareamento por entropia, foi possível calcular o efeito médio do tratamento sobre os tratados (ATT) do Bolsa Família nas horas trabalhadas, que pode ser visto na Tabela 4 abaixo. Os resultados mostram que o impacto do PBF nas horas trabalhadas do chefe familiar, no Brasil, foi em média de -2,65, ou seja, os beneficiários do programa possuem menos horas trabalhadas do que os não beneficiários. O mesmo é observado para todas as regiões, sendo o maior impacto verificado nas regiões Centro-Oeste, Sudeste e Sul, no qual os beneficiários possuem 6,04, 3,13 e 1,80, respectivamente, a menos de horas trabalhadas se comparados às famílias que não recebem o repasse monetário.

+

+ + + + Impacto do PBF nas horas trabalhadas do chefe familiar - Brasil e Regiões - Rural. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RegiõesATTteste t95% Interval, Conf
Brasil-2,65-14,56-3,0077 -2,2940
Norte-0,90-1,41-2,1666 0,3513
Nordeste-1,14-4,43-1,6583 -0,6411
Sudeste-3,13-4,83-4,4085 -1,8624
Sul-1,80-2,71-3,1037 -0,4963
Centro-Oeste-6,04-2,04-11,8991 -0,1985
+
+ + +

Fonte: Elaborado pelos autores com base nas estimações

+ + + +

+

Menor impacto foi observado na região Nordeste, cujo efeito foi de -1,14, porém, este não foi significativo para a região Norte. Vale ressaltar que 2010 foi um ano de seca no Nordeste e que mais de 50% dos beneficiários são agricultores. Assim pode ser que neste ano o repasse monetário do programa tenha ajudado a atender apenas às necessidades fundamentais dos beneficiários, sem que tenha havido grandes incentivos para uma maior redução das horas trabalhadas.

+

Embora os resultados das horas trabalhadas entre os beneficiários e o grupo de controle tenham mostrado que as Regiões Centro-Oeste, Sudeste e Sul são aquelas que apresentam o maior “efeito desincentivo” médio, elas têm em média mais horas trabalhadas que as demais regiões. Por outro lado, o Norte e o Nordeste apresentaram o menor “efeito desincentivo” e são responsáveis pelo maior número de beneficiários do Programa Bolsa Família no Brasil, como visto na Tabela 1, denotando que apesar de serem regiões com mais beneficiários e com problemas estruturais, o efeito desincentivo é menor quando comparado ao Brasil e demais regiões. Isso, provavelmente, decorre do benefício do PBF não permitir que os trabalhadores de regiões mais pobres como as regiões Norte e Nordeste, prescindam do trabalho, não gerando alto desincentivo ao trabalho. Quanto à região Centro-Oeste, uma possível explicação para a grande diferença entre os dois grupos talvez seja o tamanho da amostra para essa região.

+
+ + 3.2.2 Impacto do Programa Bolsa Família na renda do trabalho per capita +

Seguindo os procedimentos realizados para a análise anterior, estimaram-se as medidas de desequilíbrio global, no qual a Tabela 5 abaixo apresenta estatística L1 = 0,8626 antes do balanceamento, e estatística L1 = 0,6547 após o balanceamento para o caso do Brasil Rural. Observa-se que para a renda do trabalho houve uma redução dessa medida entre as covariáveis dos tratados e controles, demonstrando que a aplicação do CEM como ocorrido na análise anterior melhorou o equilíbrio entre os grupos. Então, a amostra após o procedimento passou a conter 35.372 tratados e 49.664 controles, comparáveis. Além disso, percebe-se que antes do balanceamento o número de tratados era muito superior ao número de controles, o que poderia gerar um desequilíbrio no suporte comum. Para todas as regiões, a estatística L1 também apresentava valores altos antes do balanceamento, já após a aplicação do CEM houve uma melhora no equilíbrio entre os grupos.

+

+ + + + Balanceamento CEM - Brasil e Regiões - Rural + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Brasil Norte Nordeste Sudeste Sul Centro-Oeste
L1 - Antes do CEM 0,8626 0,9215 0,8902 0,9182 0,9346 0,9718
L1 - Após o CEM0,6547 0,5848 0,5730 0,5304 0,5611 0,3786
Algoritmo CEMTratadosControleTratadosControleTratadosControleTratadosControleTratadosControleTratadosControle
+ 101010101010
Total de Observações128.04065.04613.87911.43384.97330.50217.27412.2859.1117.5802.8033.426
Comparáveis – Após o CEM 49.66435.3722.8333.37123.12614.8573.8183.4821.5961.795208247
Não Comparáveis – Após o CEM78.37629.67411.0468.06261.84715.64513.4568.8037.5155.7852.5952.999
+
+ + +

Fonte: Dados de pesquisa

+ + +

Elaboração: Autores

+
+ + +

+

Assim como na análise das horas trabalhadas, os resultados do balanceamento por Entropia para a renda do trabalho, Tabela 6, mostram que para o Brasil Rural, a média, variância e assimetria da distribuição antes e após a entropia eram diferentes entre os grupos analisados. Ressalta-se que o mesmo acontece para as regiões.6 +

+

Após o balanceamento pela entropia no Brasil rural, utilizando os três primeiros momentos da distribuição das variáveis independentes, houve o ajustamento dessas estatísticas para todas as covariadas analisadas, ou seja, o balanceamento está perfeitamente ajustado.

+

Por exemplo, a covariada idade do chefe da família, antes do ajustamento tinha como média (38,04), variância (100,00) e assimetria (0,3443) para o grupo dos tratados, para o grupo de controle tinha-se média (37,09), variância (139,10) e assimetria (0,2780) do grupo de controle. Após o balanceamento, houve o ajustamento dessas estatísticas para a covariada em questão, sendo que tanto para o grupo de tratados quanto para o grupo de controle a média (38,04), variância (100,00) e assimetria (0,3443) passaram a ser as mesmas. Quanto aos resultados para as regiões rurais, os resultados foram similares ao encontrado para o Brasil.

+

+ + + + Balanceamento por Entropia Covariadas da Renda do Trabalho per capita - Brasil Rural + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CovariadasAntes do balanceamento por entropia Após o balanceamento por entropia
+ Tratados Controle Tratados Controle
+ MédiaVariânciaAssimetriaMédiaVariânciaAssimetriaMédiaVariânciaAssimetriaMédiaVariânciaAssimetria
Chefe_homem0,86630,1158-2,15300,86810,1145-2,17500,86630,1158-2,15300,86630,1158-2,1530
Chefe_branco0,25360,18931,13300,28080,20200,97560,25360,18931,13300,25360,18931,1330
Ensino_2° grau0,03830,03684,81200,05760,05433,79700,03830,03684,81200,03830,03684,8120
Ensino_ginásio0,12870,11222,21700,17580,14491,70300,12870,11222,21700,12870,11222,2170
Ensino_primário0,59220,2415-0,37510,53040,2491-0,12190,59220,2415-0,37510,59220,2415-0,3751
Ensino_superior0,000020,00002222,800,000030,00003188,100,000020,00002222,800,000020,00002222,80
N. filho_50,58420,57751,11500,59490,59891,10900,58420,57751,11500,58420,57751,1150
N. filho_100,54680,50921,06100,34130,38941,81200,54680,50921,06100,54680,50921,0610
N. filho_150,47890,51421,33100,28540,36222,18900,47890,51421,33100,47890,51421,3310
N. filho_170,11270,10532,680,07540,07443,55400,11270,10532,680,11270,10532,6800
N. filhos_180,27630,39492,78700,22720,35983,28500,27630,39492,78700,27630,39492,7870
Filho_branco0,31400,21540,80160,28190,20240,96960,31400,21540,80160,31400,21540,8016
Cegueira0,00940,009310,1900,01180,01169,05800,00940,009310,190,00940,009310,19
Surdez0,00040,000451,100,00060,000640,060,00040,000451,100,00040,000451,10
Mental0,00030,000359,540,00040,000452,130,00030,000359,540,00030,000359,54
Física0,00090,000933,940,00140,001426,810,00090,000933,940,00090,000933,94
Cart._trab.0,02980,02905,52700,04320,04134,49400,02980,02905,52700,02980,02905,5270
Agro._chefe0,77040,1769-1,28600,75210,1864-1,16800,77040,1769-1,28600,77040,1769-1,2860
Condi._dom.0,83230,1396-1,77900,77540,1742-1,320,83230,1396-1,77900,83230,1396-1,7790
Material_dom.0,77600,1738-1,32400,69460,2121-0,84500,77600,1738-1,32400,77600,1738-1,3240
Tipo_dom.0,99860,0014-26,770,99700,0030-18,100,99860,0014-26,77000,99860,0014-26,77
Saneamento0,03960,03804,72300,05080,04824,09100,03960,03804,72300,03960,03804,7230
Água_canalizada0,20380,16231,47100,18970,15371,58300,20380,16231,47100,20380,16231,4710
Tratam_lixo0,08580,07842,95800,10510,09412,57500,08580,07842,95800,08580,07842,9580
Eletricidade0,86430,1173-2,12800,79540,1628-1,46400,86430,1173-2,12800,86430,1173-2,1280
Idade_chefe38,04100,000,344337,09139,200,400038,04100,000,344338,04100,000,3443
+
+ + +

Fonte: Elaboração própria

+ + +

Nota: O tamanho da amostra após o balanceamento por entropia não se alterou, permanecendo 19.860 tratados e 18.444 controles.

+
+ + +

+

A Tabela 7 mostra o Efeito Médio do Tratamento sobre os Tratados (ATT) para o Brasil e Regiões Rurais. Por meio dela, percebe-se que, em média, as famílias beneficiadas pelo programa no Brasil possuem renda do trabalho per capita inferior às famílias elegíveis não beneficiárias, chegando a uma diferença de R$22,05. Nas regiões, essa diferença é maior na região Sul (-R$19,46), enquanto a região Norte (-R$15,27) é responsável pela menor diferença, seguida do Sudeste (-R$16,73) e Centro-Oeste (-R$16,74).

+

Portanto, pode-se verificar que no Brasil e Regiões os beneficiários do Bolsa Família possuem renda do trabalho inferior per capita quando comparados com aqueles elegíveis que não participam do programa, sendo que, para as regiões, o maior e o menor impacto ocorreu nas Região Sul e Norte, respectivamente.

+

+ + + + Impacto do PBF na renda do trabalho per capita do chefe familiar - Brasil e Regiões - Rural + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RegiõesATTteste t95% Interval, Conf
Brasil-22,05-80,40-22,5898 -21,5146
Norte-16,49-18,86-16,3022 -14,2557
Nordeste-19,82-46,86-17,6156 -16,2627
Sudeste-20,17-26,33-17,7782 -15,6955
Sul-24,07-22,32-20,7731 -18,1594
Centro-Oeste-15,14-5,26-18,7189 -14,7777
+
+ + +

Fonte: Elaborado pelos autores, com base nas estimações.

+ + + +

+
+
+ + 3.3 Resultados para o Modelo de <xref ref-type="bibr" rid="B10">Firpo (2007</xref>) + + 3.3.1 Impacto do Programa Bolsa Família nas horas trabalhadas do chefe familiar +

Os efeitos do Bolsa Família nas horas trabalhadas do chefe familiar para as regiões, na distribuição, são apresentados na Tabela 8. Para os quantis, os resultados apresentam efeitos distintos. Pode-se perceber que no primeiro quantil, em que a quantidade de horas trabalhadas é de 2 horas semanais (para o Nordeste, Norte, Sudeste e Centro-Oeste) e 3 horas semanais (para o Sul), não existe “efeito desincentivo” ao trabalho para os trabalhadores. A não existência desse efeito persiste nos primeiros quantis para a região Nordeste e Norte. Já na região Norte, é possível perceber efeitos negativos mais fortes nos quantis mais elevados e um pequeno impacto positivo entre os quantis 0,1 e 0,25.

+

A região Centro-Oeste tem a maior redução (12 horas) na jornada de trabalho, mais precisamente para os indivíduos que trabalham 80 horas semanais. Para as regiões Sudeste e Sul, destacam-se efeitos negativos entre os quantis 0,1 e 0,25. Ademais, a região Centro-Oeste é a que possui maiores efeitos desincentivo ao trabalho, enquanto a região Norte é responsável pelos menores efeitos.

+

Para aqueles que trabalham 40 horas semanais, tanto para o Brasil quanto para as regiões, não existem efeitos significativos, com exceção da região Centro-Oeste, em que parte dos beneficiários que se encontram nessa faixa chegam a ofertar até 4 horas a menos com relação aos que não são beneficiários. Tais resultados seguem os encontrados por Costa et al. (2014), os quais consideraram para o Brasil urbano e rural.

+

Destacam-se alguns efeitos encontrados: 1) efeitos neutros, não significantes, para os quantis em que são poucas as horas trabalhadas do chefe familiar e para os que trabalham 40 horas semanais nas regiões, com exceção da Centro-Oeste. 2) efeitos negativos para os que trabalham acima de 40 horas semanais em todas as regiões, excetuando-se os quantis com efeito nulo, neste caso, o recebimento do benefício pode implicar na busca da aproximação do montante de horas previsto pela CLT, qual seja, reduzindo o excesso de trabalho para 40 horas. 3) Efeitos positivos entre os quantis 0,1 e 0,25 da região Norte, no qual as famílias beneficiadas encontram incentivos para aumentar a quantidade de horas trabalhadas.

+

+ + + + Impacto do PBF nas horas trabalhadas dos chefes familiares - Brasil e Regiões - Rural + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
QuantisBrasil Nordeste Norte Sudeste Centro-Oeste Sul
+ HEQT%HEQT%HEQT%HEQT%HEQT%HEQT%
0,0120 (0,135)-20 (0,176)-20 (0,284)-20 (0,412)-20 (0,840)-30 (0,479)-
0,19-1*** (0,136)-11,1%80 (0,212)-80 (0,335)-9-2*** (0,502)-22,2%8-2* (1,106)-25,0%14-2*** (0,761)-14,3%
0,25200 (0,105)-200 (0,154)-200 (0,363)0,0%20-4*** (0,873)-20,0%200 (1,307)-25-8*** (0,647)-32,0%
0,536-8*** (0,260)-22,2%30-6*** (0,949)-20,0%300 (0,450)-400 (0,246)-40-4*** (0,971)-10,0%400 (0,242)-
0,75400 (0,043)-400 (0,064)-400 (0,172)-45-1** (0,405)-2,2%44-1 (0,711)-2,3%480 (0,372)-
0,9560-4*** (0,278)-6,7%50-4*** (1,264)-8,0%58-4*** (0,912)-6,9%600 (0,730)-600 (1,038)-65-5** (2,359)-7,7%
0,9977-8*** (0,705)-10,4%720 (0,569)-80-10*** (1,786)-12,5%80-6*** (2,130)-7,5%80-12* (4,642)-15,0%800 (1,838)-
+
+ + +

Nota: (¹) Os valores entre parênteses representam o desvio-padrão.

+ + +

(²)A tabela apresenta somente alguns quantis selecionados.

+
+ +

(³)***Estatisticamente significante a 1%, **Estatisticamente significante a 5%, *Estatisticamente significante a 10%.

+
+ +

Fonte: Elaborado pelos autores, com base nas estimações

+
+ + +

+
+ + 3.3.2 Impacto do Programa Bolsa Família na renda do trabalho per capita +

A Tabela 9 retrata o impacto do Programa Bolsa Família na renda do trabalho per capita. Por meio dela, percebe-se que, à exceção do primeiro quantil da região Nordeste, a renda dos beneficiários do PBF, se comparada aos não beneficiários, é menor ao longo de toda a distribuição para todas as regiões do país.

+

Com relação às regiões Nordeste e Norte, os maiores impactos em termos monetários são observados da mediana pra cima, chegando a receber até R$22,75 (Nordeste) e R$23,33 (Norte) a menos que as famílias elegíveis não beneficiadas. Já nas regiões Sudeste, Centro-Oeste e Sul, a redução na renda é maior no quantil 0,75 (assim como para o Brasil), correspondendo a uma diminuição de R$23,00, R$25,50 e R$25,00, respectivamente.

+

Tratando-se do impacto percentual no quantil, os efeitos negativos são mais encontrados nas regiões Sul e Centro-Oeste, nas quais os chefes domiciliares beneficiados recebem 35,0% (quantil 0,1) e 34,3% (quantil 0,01), respectivamente, a menos que os não beneficiados.

+

+ + + + Impacto do PBF na Renda do trabalho per capita - Brasil e Regiões - Rural + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
QuantisBrasil Nordeste Norte Sudeste Centro-Oeste Sul
+ R$EQT%R$EQT%R$EQT%R$EQT%R$EQT%R$EQT%
0,016,67-1,50*** (0,231) -22,5%5,550,00 (0,325)0,0%8,33-1,09* (0,580)-13,1%12,00-2,50** (1,097)-20,8%12,50-4,29** (1,909)-34,3%12,00-2,50*** (0,938)-20,8%
0,120,00-5,00*** (0,293)-25,0%17,50-2,26*** (0,339)-12,9%25,00-5,56*** (0,633)-22,2%35,71-6,67*** (1,028)-18,7%40,00-13,20*** (2,023)-33,0%33,33-11,67*** (1,212)-35,0%
0,2540,00-14,29*** (0,295)-35,7%33,33-4,63*** (0,435)-13,9%42,86-10,00*** (0,731)-23,3%60,00-16,67*** (0,912)-27,8%66,67-15,00*** (1,760)-22,5%59,20-16,67*** (1,042)-28,2%
0,567,00-18,75*** (0,376)-28,0%60,00-11,67*** (0,562)-19,4%70,38-15,83*** (0,805)-22,5%87,50-20,00*** (0,519)-22,9%100,00-15,00*** (1,295)-15,0%85,72-25,00*** (0,755)-29,2%
0,75100,00-22,22*** (0,629)-22,2%90,00-16,67*** (0,375)-18,5%100,00-14,50*** (0,628)-14,5%107,15-23,00*** (0,303)-21,5%116,67-25,50*** (0,572)-21,9%106,25-25,00*** (0,423)-23,5%
0,95127,50-20,83*** (0,262)-16,3%125,00-22,75*** (0,202)-18,2%127,50-23,33*** (0,746)-18,3%127,50-5,83*** (0,172)-4,6%132,00-5,83*** (0,396)-4,4%130,00-8,33*** (0,537)-6,4%
0,99134,50-12,5*** (0,043)-9,3%133,33-13,08*** (0,432)-9,8%135,71-14,29*** (0,631)-10,5%138,33-12,50*** (0,064)-9,0%140,00-12,50*** (0,232)-8,9%140,00-12,50*** (0,154)-8,9%
+
+ + +

Nota: (¹) Os valores entre parênteses representam o desvio-padrão.

+ + +

(²)A tabela apresenta somente alguns quantis selecionados.

+
+ + +

+

(³)***Estatisticamente significante a 1%; **Estatisticamente significante a 5%; *Estatisticamente significante a 10%.

+

Fonte: Elaborado pelos autores, com base nas estimações

+

Logo, embora haja uma menor renda oriunda do trabalho dos beneficiários se comparada a dos não beneficiários, não se pode afirmar que essa diferença seja atribuída exclusivamente ao efeito desincentivo ao trabalho, visto que foram observados distintos efeitos na distribuição. Ademais, a redução de horas trabalhadas no caso de altos quantis pode não ser somente causada pelo efeito desincentivo, mas também por um aumento no poder de barganha do trabalhador em abrir mão de jornadas excessivas de trabalho para ter uma compensação de renda por meio do PBF.

+
+
+
+ + 4 Considerações finais +

Este trabalhou procurou avaliar possíveis efeitos do Programa Bolsa Família nas horas trabalhadas do chefe familiar e na renda do trabalho per capita dos indivíduos que se situam em áreas rurais, contribuindo com a literatura em vista dos poucos estudos existentes que buscam avaliar o impacto do programa no mercado de trabalho destas áreas.

+

A análise foi feita utilizando dados do Censo Demográfico de 2010, sendo utilizado três metodologias: CEM (2009), Entropia (2011) e EQT (2007). O primeiro e segundo métodos buscam deixar o suporte comum entre o grupo de tratados e controle homogêneo, além disso, a Entropia também encontra efeito médio de tratamento sobre os tratados. A principal diferença entre esses métodos reside no fato de que a Entropia analisa o efeito médio nas variáveis, enquanto o EQT avalia o efeito ao longo da distribuição.

+

Considerando os efeitos médios, foi possível observar em todas as regiões e no Brasil como um todo resultados negativos sobre as horas trabalhadas e sobre a renda do trabalho dos beneficiários do programa comparados às famílias que são elegíveis, mas não são beneficiadas. Assim, constatou-se um efeito desincentivo para o Brasil e Regiões, sendo este efeito de maior impacto na região Centro Oeste, enquanto o menor impacto foi registrado na região Nordeste. Ademais, o Nordeste é a região com a maior quantidade de beneficiários do programa no Brasil, no entanto, esta região é a que oferta menos horas trabalhadas em média no país, enquanto a região Sul é a que oferta mais, logo, para os beneficiários que se encontram na região Nordeste, uma maior redução das horas trabalhadas poderia implicar em uma perda monetária mais significativa em comparação com beneficiários da região Sul.

+

Quanto aos efeitos na distribuição, foram verificados três tipos de efeitos nas horas trabalhadas do chefe familiar: 1) efeitos neutros nos quantis em que as horas trabalhadas equivalem a no máximo 3 horas para todas as regiões, bem como nos quantis em que as horas trabalhadas são de 40 horas, com exceção da região Centro-Oeste e em outros quantis pontuais. 2) Efeitos negativos, especialmente, onde as horas trabalhadas são superiores a 40 horas, talvez explicada pelo aumento do poder de barganha do trabalhador de abrir mão de jornadas excessivas de trabalho. 3) Efeitos positivos entre os quantis 0,1 e 0,25 da região Norte. Ressalta-se ainda que os maiores e menores efeitos desincentivo ao trabalho foram observados na região Centro-Oeste e Norte, respectivamente. Para a renda do trabalho, os efeitos na distribuição foram negativos, exceto para o primeiro quantil da região Nordeste, ou seja, os beneficiários possuem menor renda do trabalho do que os não beneficiários.

+

Os resultados não necessariamente implicam que essa menor renda do trabalho per capita dos beneficiários é consequência da redução de horas trabalhadas do chefe familiar, visto que os efeitos negativos nas horas trabalhadas foram em poucos quantis, enquanto na renda foi ao longo de todos os quantis analisados. Diante disso, devem existir outros fatores que tenham impacto no mercado de trabalho que não foram identificados nos resultados aqui obtidos, como, por exemplo, os postos de trabalho ocupados pelos indivíduos e o diferente dinamismo econômico de cada região rural do país.

+
+ + + + Referências + + AROCA, P.; BRIDA, J. G.; VOLO, S. Tourism statistics: correcting data inadequacy using coarsened exact matching. Working Paper. School of Economics and Management at the Free University of Bozen, 2014. + + + + AROCA + P. + + + BRIDA + J. G. + + + VOLO + S + + + Tourism statistics: correcting data inadequacy using coarsened exact matching + Working Paper + School of Economics and Management at the Free University of Bozen + 2014 + + + + AVERBUG, A. A Economia Brasileira nos anos 90: abertura e integração comercial na década de 90. Rio de Janeiro: BNDES, 1999. + + + + AVERBUG + A + + + A Economia Brasileira nos anos 90: abertura e integração comercial na década de 90 + Rio de Janeiro + BNDES + 1999 + + + + BASSET, Gilbert; KOENKER, R. Regression quantiles. Econometrica, v. 46, n. 1, p. 33-50, 1978 + + + + BASSET + Gilbert + + + KOENKER + R + + + Regression quantiles + Econometrica + 46 + 1 + 33 + 50 + 1978 + + + + BLACKWELL, M.; IACUS, S.; KING, G.; PORRO, G. CEM: Coarsened exact matching in Stata. The Stata Journal. v. 9, n. 4, p. 524-546, 2009. + + + + BLACKWELL + M. + + + IACUS + S. + + + KING + G. + + + PORRO + G + + + CEM: Coarsened exact matching in Stata + The Stata Journal + 9 + 4 + 524 + 546 + 2009 + + + + CARVALHO, R.; MARINHO, E. L. L. Transformações Estruturais, Variações na Eficiência Técnica e Produtividade Total dos Fatores no Setor Agrícola dos Países Sul-Americanos - 1970 a 2000. ENCONTRO NACIONAL DE ECONOMIA, 31., 2003. Anais... Porto Seguro, ANPEC, 2003. + + + + CARVALHO + R. + + + MARINHO + E. L. L + + + Transformações Estruturais, Variações na Eficiência Técnica e Produtividade Total dos Fatores no Setor Agrícola dos Países Sul-Americanos - 1970 a 2000 + ENCONTRO NACIONAL DE ECONOMIA, 31 + 2003 + Anais... + Porto Seguro + ANPEC + 2003 + + + + CAVALCANTI, D. M. Avaliação dos Impactos do Programa Bolsa Família na Renda, Educação e no Mercado de Trabalho das Famílias Pobres do Brasil. Dissertação. (Mestrado). Universidade Federal do Rio Grande do Norte, Programa de Pós-Graduação em Economia, Centro de Ciências Sociais Aplicadas. 2013. + + + + CAVALCANTI + D. M + + + Avaliação dos Impactos do Programa Bolsa Família na Renda, Educação e no Mercado de Trabalho das Famílias Pobres do Brasil + Dissertação. (Mestrado) + Universidade Federal do Rio Grande do Norte, Programa de Pós-Graduação em Economia, Centro de Ciências Sociais Aplicadas + 2013 + + + + COSTA, E. M.; CAVALCANTI, D. M.; SILVA, J. L. M. da; SAMPAIO, R. M. B. Impactos Regionais do Programa Bolsa Família: uma análise sobre o Mercado de Trabalho das Famílias Pobres. ANPEC: XLII ENCONTRO NACIONAL DE ECONOMIA, 2014 . Disponível em: < Disponível em: http://www.anpec.org.br/encontro/2014/submissao/files_I/i13-dc0aad69d0a6580ef400e1ea2c1accc7.pdf + > Acesso em: 20 abr. 2015. 2014 + + + + COSTA + E. M. + + + CAVALCANTI + D. M. + + + SILVA + J. L. M. da + + + SAMPAIO + R. M. B + + + Impactos Regionais do Programa Bolsa Família: uma análise sobre o Mercado de Trabalho das Famílias Pobres + XLIIENCONTRO NACIONAL DE ECONOMIA + 2014 + Disponível em: http://www.anpec.org.br/encontro/2014/submissao/files_I/i13-dc0aad69d0a6580ef400e1ea2c1accc7.pdf + + 20 abr. 2015 + 2014 + + + + FERREIRA, M. de O. et al.Especialização produtiva e mudança estrutural da agropecuária cearense. Teoria e Evidência Econômica, Passo Fundo, v. 14, n. 26, p. 91-111, maio 2006. + + + + FERREIRA + M. de O. + + + + Especialização produtiva e mudança estrutural da agropecuária cearense + Teoria e Evidência Econômica + Passo Fundo + 14 + 26 + 91 + 111 + 2006 + + + + FERRO, A. R.; NICOLLELA, A. C. The impact of conditional cash transfers programs on household working decision in Brazil. São Paulo, 2007. Disponível em: <Disponível em: http://www.iza.org/conference_files/worldb2007/ferro_a3468.pdf + >. Acesso em: 9 março 2015. + + + + FERRO + A. R. + + + NICOLLELA + A. C + + + The impact of conditional cash transfers programs on household working decision in Brazil + São Paulo + 2007 + Disponível em: http://www.iza.org/conference_files/worldb2007/ferro_a3468.pdf + + 9 março 2015 + + + + FIRPO, Sérgio. Efficient Semiparametric Estimation of Quantile Treatment Effects. Econométrica, v. 75, n. 1, 2007. + + + + FIRPO + Sérgio + + + Efficient Semiparametric Estimation of Quantile Treatment Effects + Econométrica + 75 + 1 + 2007 + + + + GOODMAN, D.; SORJ, B.; WILKISON, J. Agroindústria, políticas públicas e estruturas rurais: análise recentes sobre a agricultura brasileira. Revista de Economia Política, v. 5 n.4, p.31-35, 1985. + + + + GOODMAN + D. + + + SORJ + B. + + + WILKISON + J + + + Agroindústria, políticas públicas e estruturas rurais: análise recentes sobre a agricultura brasileira + Revista de Economia Política + 5 + 4 + 31 + 35 + 1985 + + + + HAINMUELLER J. Entropy Balancing for Causal Effects: A Multivariate Reweighting Method to Produce Balanced Samples in Observational Studies. Political Analysis, v. 20 n. 1, p. 25-46, 2012. + + + + HAINMUELLER + J + + + Entropy Balancing for Causal Effects: A Multivariate Reweighting Method to Produce Balanced Samples in Observational Studies + Political Analysis + 20 + 1 + 25 + 46 + 2012 + + + + HAINMUELLER J.; XU, Y. Ebalance: A Stata Package for Entropy Balancing. Journal of Statistical Software. v. 54, n.7. 2013 + + + + HAINMUELLER + J. + + + XU + Y + + + Ebalance: A Stata Package for Entropy Balancing + Journal of Statistical Software + 54 + 7 + 2013 + + + + HIRANO, K.; IMBENS, G.; RIDDER, G. Efficient Estimation of Average Treatment Effects Using the Estimated Propensity Score. Econometrica , v. 71 n. 4, p. 1161-1189, 2003. + + + + HIRANO + K. + + + IMBENS + G. + + + RIDDER + G + + + Efficient Estimation of Average Treatment Effects Using the Estimated Propensity Score + Econometrica + 71 + 4 + 1161 + 1189 + 2003 + + + + HO, DE; IMAI, K.; KING, G.; STUART, E. A. Matching as Nonparametric Preprocessing for Reducing Model Dependence in Parametric Causal Inference. Political Analysis , v. 15 n. 3, p. 199, 2007. + + + + HO + DE + + + IMAI + K. + + + KING + G. + + + STUART + E. A + + + Matching as Nonparametric Preprocessing for Reducing Model Dependence in Parametric Causal Inference + Political Analysis + 15 + 3 + 199 + 199 + 2007 + + + + IACUS, S. M.; KING, G; PORRO, G. Matching for causal inference without balance checking. 2009. Disponível em: <Disponível em: http://gking.harvard.edu/files/cem.pdf + >. Acesso em: 27 Maio 2016. + + + + IACUS + S. M. + + + KING + G + + + PORRO + G + + + Matching for causal inference without balance checking + 2009 + Disponível em: http://gking.harvard.edu/files/cem.pdf + + 27 Maio 2016 + + + + IACUS, S; KING, G; PORRO, G. Causal Inference without Balance Checking: Coarsened Exact Matching. Political Analysis , 2011. + + + + IACUS + S + + + KING + G + + + PORRO + G + + + Causal Inference without Balance Checking: Coarsened Exact Matching + Political Analysis + 2011 + + + + IBGE - Instituto Brasileiro de Geografia e Estatística. Banco de Dados Agregados. Sistema IBGE de Recuperação Automática - SIDRA. Disponível em:Disponível em:http://www.ibge.gov.br + Acesso em: 20 abr. 2015. + + IBGE + Disponível em:http://www.ibge.gov.br + + 20 abr. 2015 + + + + IBGE - Instituto Brasileiro de Geografia e Estatística. Censo Demográfico de 2010. Rio de Janeiro. Disponível em: http://www.ibge.gov.br. Vários acessos. + + IBGE + http://www.ibge.gov.br + + + + IBGE - Instituto Brasileiro de Geografia e Estatística. Pesquisa Nacional por Amostra de Domicílios de 2013. Rio de Janeiro. Disponível em: http://www.ibge.gov.br. Vários acessos. + + IBGE + http://www.ibge.gov.br + + + + IMBENS, G. W. Nonparametric Estimation of Average Treatment Effects under Exogeneity: A Review. Review of Economics and Statistics, v. 86 n. 1, p. 4-29, 2004. + + + + IMBENS + G. W + + + Nonparametric Estimation of Average Treatment Effects under Exogeneity: A Review + Review of Economics and Statistics + 86 + 1 + 4 + 29 + 2004 + + + + NASCIMENTO, C. A. et al. A Qualidade do emprego rural fluminense nos anos recentes (2002 e 2006). Congresso da Sociedade Brasileira de Economia e Sociologia RuraL, 46, 2008, Rio Branco . Anais... Rio Branco, 2008. Disponível em: <Disponível em: http://www.sober.org.br + > Acesso em: 05 mai. 2015. + + + + NASCIMENTO + C. A. + + + + A Qualidade do emprego rural fluminense nos anos recentes (2002 e 2006) + Congresso da Sociedade Brasileira de Economia e Sociologia RuraL, 46 + 2008 + Rio Branco + Anais... + Rio Branco + 2008 + Disponível em: http://www.sober.org.br + + 05 mai. 2015 + + + + RUBIN, D. B. Matched Sampling for Causal Effects. Cambridge: Cambridge University Press. 2006. + + + + RUBIN + D. B + + + Matched Sampling for Causal Effects + Cambridge + Cambridge University Press + 2006 + + + + SANTOS, G. C. et al.Mercado de trabalho e rendimento no meio rural brasileiro. Economia Aplicada, Ribeirão Preto, v. 14, n. 3, p. 355-379, set. 2010. + + + + SANTOS + G. C. + + + + Mercado de trabalho e rendimento no meio rural brasileiro + Economia Aplicada + Ribeirão Preto + 14 + 3 + 355 + 379 + 2010 + + + + SCHURER, S. et al.The Medical Care Costs of Mood Disorders: A Coarsened Exact Matching Approach, IZA Discussion Papers, 2015. + + + + SCHURER + S. + + + + The Medical Care Costs of Mood Disorders: A Coarsened Exact Matching Approach + IZA Discussion Papers + 2015 + + + + SEKHON, J. S. Opiates for the Matches: Matching Methods for Causal Inference. Annual Review of Political Science, v. 12, p. 487-508, 2009. + + + + SEKHON + J. S + + + Opiates for the Matches: Matching Methods for Causal Inference + Annual Review of Political Science + 12 + 487 + 508 + 2009 + + + + TAVARES, P. A. Efeito do Programa Bolsa Família sobre a oferta de trabalho das mães. XIII Seminário sobre Economia Mineira - Economia, História, Demografia e Políticas Públicas. Diamantina, MG, 2008. + + + + TAVARES + P. A + + + Efeito do Programa Bolsa Família sobre a oferta de trabalho das mães + XIIISeminário sobre Economia Mineira - Economia, História, Demografia e Políticas Públicas + Diamantina, MG + 2008 + + + + TEIXEIRA, C. G. Análise do Impacto do Programa Bolsa Família na oferta de trabalho dos homens e das mulheres. PNUD/IPC, 2008. Disponível em:<Disponível em:http://www.ipc-undp.org/publications/mds/27P.pdf + >. Acesso em: 20 abr. 2015. + + + + TEIXEIRA + C. G + + + Análise do Impacto do Programa Bolsa Família na oferta de trabalho dos homens e das mulheres + PNUD/IPC + 2008 + Disponível em:http://www.ipc-undp.org/publications/mds/27P.pdf + + 20 abr. 2015 + + + + TEIXEIRA, J. C. Modernização da agricultura no Brasil: impactos econômicos, sociais e ambientais. Revista Eletrônica da Associação dos Geógrafos Brasileiros - Seção Três Lagoas, v. 2, n. 2, 2005. + + + + TEIXEIRA + J. C + + + Modernização da agricultura no Brasil: impactos econômicos, sociais e ambientais + Revista Eletrônica da Associação dos Geógrafos Brasileiros + Seção Três Lagoas + 2 + 2 + 2005 + + + + + + +

Instituído pela Medida Provisória nº 132, de 20 de outubro 2003. Oficializado pela Lei nº 10.836, de 09 de janeiro de 2004, e Decreto nº 5.209, de 17 de setembro de 2004.

+
+ + +

Visto que foi o último censo divulgado.

+
+ + +

Tais resultados podem ser requisitados aos autores por email.

+
+ + +

O desequilíbrio global é dado pela estatística L1, sendo determinado na diferença entre o histograma L1 multidimensional de todas as covariáveis de pré-tratamento do grupo tratado e do grupo de controle. Quanto mais próximo for L1=0, mais balanceados estarão os dois grupos, quanto mais próximo for L1=1, mais separados são os tratados e controle.

+
+ + +

Tais resultados podem ser requisitados aos autores por email.

+
+ + +

Tais resultados podem ser requisitados aos autores por email.

+
+
+
+ \ No newline at end of file diff --git a/xml/math/Tutorial_2006_4bafe3.xml b/xml/math/Tutorial_2006_4bafe3.xml new file mode 100644 index 0000000..cce4ea7 --- /dev/null +++ b/xml/math/Tutorial_2006_4bafe3.xml @@ -0,0 +1,1071 @@ + + + + + + Objects in Motion + In this tutorial, we will look at a number of ways to transform objects, rendering them in + different locations and orientations in the world. And we will also solve the secret of why + we overcomplicated everything with those matrices. +
+ Spaces + Throughout this series of tutorials, we have discussed a number of different spaces. + We have seen OpenGL-defined spaces like normalized device coordinate (NDC) space, + clip-space, and window space. And we have seen user-defined spaces like camera space. + But we have yet to formally discuss about what a space actually is. + A space is a shorthand term for a coordinate + system. For the purposes of this conversation, a coordinate system or + space consists of the following: + + + The dimensionality of the space. 2D, 3D, 4D, etc. + + + A series of vectors in those dimensions that define the axes of the space. The + directions do not have to be orthogonal (at right-angles) to one another, but + there must be one axis per dimension. Each axis vector in the space has a name, + like X, Y, Z, etc. These are called the basis vectors of + a space. + + + A location in the space that defines the central origin + point. The origin is the point from which all other points in the space are + derived. + + + An area within this space in which points are valid. Outside of this range, + positions are not valid. The range can be infinite depending on the + space. + + + A position or vertex in a space is defined as the sum of the basis vectors, where each + basis vector is multiplied by a scalar value called a coordinate. Geometrically, this + looks like the following: +
+ Two 2D Coordinate Systems + + + + + +
+ These are two different coordinate systems. The same coordinate, in this case (2, 2) + (each basis vector is added twice) can have two very different positions, from the point + of view of a neutral observer. What is interesting to note is that (2, 2) is the same + value in their own coordinate system. This means that a coordinate itself is not enough + information to know what it means; one must also know what coordinate system it is in + before you can know anything about it. + The numerical version of the coordinate system equation is as follows: + + Coordinate System + + + The geometric version is all well and good when dealing with the geometric basis + vectors and origin point. The origin point is just a position, and the basis vectors are + simply drawn. But what does it mean to give actual numbers to these concepts in the + numerical version? A position, like the origin point, is itself a coordinate. Which + means that it must be defined relative to some coordinate system. The same goes for the + basis vectors. + Ultimately, this means that we cannot look numerically at a single coordinate system. + Since the coordinate values themselves are meaningless without a coordinate system, a + coordinate system can only be numerically expressed in relation to another coordinate + system. + Technically, the geometric version of coordinate systems works the same way. The + length of the basis vectors in the geometric diagrams are relative to our own + self-imposed sense of length and space. Essentially, everything is relative to + something, and we will explore this in the near future. +
+ Transformation + In the more recent tutorials, the ones dealing with perspective projections, we + have been taking positions in one coordinate system (space) and putting them in + another coordinate system. Specifically, we had objects in camera space that we + moved into clip space. The process of taking a coordinate in one space and + specifying it as a coordinate in another space is called + transformation. The coordinate's actual meaning has not + changed; all that has changed is the coordinate system that this coordinate is + relative to. + We have seen a number of coordinate system transformations. OpenGL implements the + transformation from clip-space to NDC space and the transformation from NDC to + window space. Our shaders implement the transformation from camera space to + clip-space, and this was done using a matrix. Perspective projection (and + orthographic, for that matter) are simply a special kind of transformation. + This tutorial will cover a large number of different kinds of transform + operations and how to implement them in OpenGL. +
+
+ Model Space + Before we begin, we must define a new kind of space: model + space. This is a user-defined space, but unlike camera space, model + space does not have a single definition. It is instead a catch-all term for the + space that a particular object begins in. Coordinates in buffer objects, passed to + the vertex shaders as vertex attributes are de facto + in model space. + There are an infinite variety of model spaces. Each object one intends to render + can, and often does, have its own model space, even if the difference between these + spaces is only in the origin point. Model spaces for an object are generally defined + for the convenience of the modeller or the programmer who intends to use that + model. + The transformation operation being discussed in this tutorial is the transform + from model space to camera space. Our shaders already know how to handle + camera-space data; all they need is a way to transform from model space to camera + space. +
+
+
+ + Translation + The simplest space transformation operation is translation. Indeed, we have not only + seen this transform before, it has been used in all of the tutorials with a perspective + projection. Recall this line from the vertex shaders: + vec4 cameraPos = position + vec4(offset.x, offset.y, 0.0, 0.0); + This is a translation transformation: it is used to position + the origin point of the initial space relative to the destination space. Since all of + the coordinates in a space are relative to the origin point of that space, all a + translation needs to do is add a vector to all of the coordinates in that space. The + vector added to these values is the location of where the user wants the origin point + relative to the destination coordinate system. +
+ Coordinate System Translation in 2D + + + + + +
+ Here is a more concrete example. Let us say that an object which in its model space is + near its origin. This means that, if we want to see that object in front of the camera, + we must position the origin of the model in front of the camera. If the extent of the + model is only [-1, 1] in model space, we can ensure that the object is visible by adding + this vector to all of the model space coordinates: (0, 0, -3). This puts the origin of + the model at that position in camera space. + Translation is ultimately just that simple. So let's make it needlessly complex. And + the best tool for doing that: matrices. Oh, we could just use a 3D uniform vector to + pass an offset to do the transformation. But matrices have hidden benefits we will + explore very soon. + All of our position vectors are 4D vectors, with a final W coordinate that is always + 1.0. In Tutorial 04, we took advantage of this with + our perspective transformation matrix. The equation for the Z coordinate needed an + additive term, so we put that term in the W column of the transformation matrix. Matrix + multiplication causes the value in the W column to be multiplied by the W coordinate of + the vector (which is 1) and added to the sum of the other terms. + But how do we keep the matrix from doing something to the other terms? We only want + this matrix to apply an offset to the position. We do not want to have it modify the + position in some other way. + This is done by modifying an identity matrix. An identity + matrix is a matrix that, when performing matrix multiplication, will return the matrix + (or vector) it was multiplied with. It is sort of like the number 1 with regular + multiplication: 1*X = X. The 4x4 identity matrix looks like this: + + Identity Matrix + + + To modify the identity matrix into one that is suitable for translation, we simply put + the offset into the W column of the identity matrix. + + Translation Matrix + + + The tutorial project cleverly titled Translation + performs translation operations. + This tutorial renders 3 of the same object, all in different positions. One of the + objects is positioned in the center of the screen, and the other two's positions orbit + it at various speeds. + Because of the prevalence of matrix math, this is the first tutorial that uses the GLM + math library. So let's take a look at the shader program initialization code to see it + in action. + + Translation Shader Initialization + void InitializeProgram() +{ + std::vector<GLuint> shaderList; + + shaderList.push_back(Framework::LoadShader(GL_VERTEX_SHADER, + "PosColorLocalTransform.vert")); + shaderList.push_back(Framework::LoadShader(GL_FRAGMENT_SHADER, + "ColorPassthrough.frag")); + + theProgram = Framework::CreateProgram(shaderList); + + positionAttrib = glGetAttribLocation(theProgram, "position"); + colorAttrib = glGetAttribLocation(theProgram, "color"); + + modelToCameraMatrixUnif = glGetUniformLocation(theProgram, + "modelToCameraMatrix"); + cameraToClipMatrixUnif = glGetUniformLocation(theProgram, + "cameraToClipMatrix"); + + float fzNear = 1.0f; float fzFar = 45.0f; + + cameraToClipMatrix[0].x = fFrustumScale; + cameraToClipMatrix[1].y = fFrustumScale; + cameraToClipMatrix[2].z = (fzFar + fzNear) / (fzNear - fzFar); + cameraToClipMatrix[2].w = -1.0f; + cameraToClipMatrix[3].z = (2 * fzFar * fzNear) / (fzNear - fzFar); + + glUseProgram(theProgram); + glUniformMatrix4fv(cameraToClipMatrixUnif, 1, GL_FALSE, + glm::value_ptr(cameraToClipMatrix)); + glUseProgram(0); +} + + GLM takes a unique approach for a vector/matrix math library. It attempts to emulate + GLSL's approach to vector operations where possible. It uses C++ operator overloading to + effectively emulate GLSL. In many cases, GLM-based expressions would compile in + GLSL. + The matrix cameraToClipMatrix is defined as a + glm::mat4, which has the same properties as a GLSL mat4. + Array indexing of a mat4, whether GLM or GLSL, returns the zero-based + column of the matrix as a vec4. + The glm::value_ptr function is used to get a direct pointer to + the matrix data, in column-major order. This is useful for uploading data to OpenGL, as + shown with the call to glUniformMatrix4fv. + With the exception of getting a second uniform location (for our model transformation + matrix), this code functions exactly as it did in previous tutorials. + There is one important note: fFrustumScale is not 1.0 anymore. + Until now, the relative sizes of objects were not particularly meaningful. Now that we + are starting to deal with more complex objects that have a particular scale, picking a + proper field of view for the perspective projection is very important. + The new fFrustumScale is computed with this code: + + Frustum Scale Computation + float CalcFrustumScale(float fFovDeg) +{ + const float degToRad = 3.14159f * 2.0f / 360.0f; + float fFovRad = fFovDeg * degToRad; + return 1.0f / tan(fFovRad / 2.0f); +} + +const float fFrustumScale = CalcFrustumScale(45.0f); + + The function CalcFrustumScale computes the frustum scale based on + a field-of-view angle in degrees. The field of view in this case is the angle between + the forward direction and the direction of the farmost-extent of the view. + This project, and many of the others in this tutorial, uses a fairly complex bit of + code to manage the transform matrices for the various object instances. There is an + Instance object for each actual object; it has a function + pointer that is used to compute the object's offset position. The + Instance object then takes that position and computes a + transformation matrix, based on the current elapsed time, with this function: + + Translation Matrix Generation + glm::mat4 ConstructMatrix(float fElapsedTime) +{ + glm::mat4 theMat(1.0f); + + theMat[3] = glm::vec4(CalcOffset(fElapsedTime), 1.0f); + + return theMat; +} + + The glm::mat4 constructor that takes only a single value constructs what + is known as a diagonal matrix. That is a matrix with all zeros except for along the + diagonal from the upper-left to the lower-right. The values along that diagonal will be + the value passed to the constructor. An identity matrix is just a diagonal matrix with 1 + as the value along the diagonal. + This function simply replaces the W column of that identity matrix with the offset + value. + This all produces the following: +
+ Translation Project + + + + + +
+
+
+ + Scale + Another kind of transformation is scaling. In terms of our + previous definition of a coordinate system, this means that our basis vectors are + getting shorter or longer. +
+ Coordinate System Scaling in 2D + + + + + +
+ Scaling can be uniform, which means each basis vector is scaled by the same value. A + non-uniform scale means that each basis can get a different scale or none at all. + Uniform scales are used to allow objects in model space to have different units from + the units used in camera space. For example, a modeller may have generated the model in + inches, but the world uses centimeters. This will require applying a uniform scale to + all of these models to compensate for this. This scale should be 2.54, which is the + conversion factor from inches to centimeters. + Note that scaling always happens relative to the origin of the space being + scaled. + Recall how we defined the way coordinate systems generate a position, based on the + basis vectors and origin point: + + + + If you are increasing or decreasing the length of the basis vectors, this is the same + as multiplying those basis vectors by the new length. So we can re-express this equation + as follows: + + + + Since scalar-vector multiplication is both associative and commutative, we can + multiply the scales directly into the coordinate values to achieve the same effect. So a + scaled space can be reexpressed as simply multiplying the input coordinate + values. + This is easy enough to do in GLSL, if you pass a vector uniform containing the scale + values. But that's just not complicated enough. Obviously, we need to get matrices + involved, but how? + This gets a bit technical, in terms of how a matrix multiplication works. But look + back at the identity matrix: + + + + This matrix selects each coordinate in turn from the vector it is being multiplied + into. Each row is multiplied with the column of the vector; all of the zeros remove the + components of the vector that we do not want. The 1 value of each row multiplies into + the component we do want, thus selecting it. This produces the identity result: the + vector we started with. + We can see that, if the ones were some other value, we would get a scaled version of + the original vector, depending on which ones were changed. Thus, a scaling + transformation matrix looks like this: + + Scaling Transformation Matrix + + + You may start to see a pattern emerging here, something that begins to suggest why + matrices are very, very useful. I will not spoil it for you yet though. + The tutorial project Scale will display 5 objects + at various scales. The objects are all at the same Z distance from the camera, so the + only size difference between the objects is the scale effects applied to them. The + object in the center is unscaled; each of the other objects has a scale function of some + kind applied to them. +
+ Scale Project + + + + + +
+ Other than the way the tutorial builds its matrices, there is no difference between + this tutorial project and the previous one. The matrix building code works as + follows: + glm::mat4 ConstructMatrix(float fElapsedTime) +{ + glm::vec3 theScale = CalcScale(fElapsedTime); + glm::mat4 theMat(1.0f); + theMat[0].x = theScale.x; + theMat[1].y = theScale.y; + theMat[2].z = theScale.z; + theMat[3] = glm::vec4(offset, 1.0f); + + return theMat; +} + As before, the scale is supplied by a number of scale functions, depending on which + instance is being rendered. The scale is stored in the columns of the identity matrix. + Then the translation portion of the matrix is filled in. + The offset variable is also a member of the + Instance object. Unlike the last tutorial, the offset is a + fixed value. We will discuss the ramifications of applying multiple transforms later; + suffice it to say, this currently works. + Scaling is only slightly more complicated than translation. + + Perspective and Scaling + The way we construct a scale transformation matrix may seem familiar to you. Back + in Tutorial 4, the perspective transformation involved a frustum scale value. This + was used to make up for the fact that our projection defined a specific location for + the plane of projection and camera eye point. Using this frustum scale, we could + give the appearance of having a larger or smaller viewing size. Indeed, we later + used this to define the aspect ratio as well as the field of view, using the + function defined earlier in this tutorial. + This frustum scale was ultimately nothing more than a scale factor applied the X + and Y positions. When we constructed the perspective matrix, we used the frustum + scale as a uniform scaling in the X and Y dimensions. The aspect ratio compensation + code was nothing more than applying a nonuniform scale. + +
+ Inversion and Winding Order + Scales can be theoretically negative, or even 0. A scale of 0 causes the basis + vector in that direction to become 0 entirely. A basis vector with no length means + that a dimension has effectively been lost. The resulting transform squashes + everything in that direction down to the origin. A 3D space becomes a 2D space (or + 1D or 0D, depending on how many axes were scaled). + A negative scale changes the direction of an axis. This causes vertices + transformed with this scale to flip across the origin in that axis's direction. This + is called an inversion. This can have certain unintended + consequences. In particular, it can change the winding order of vertices. + Back in Tutorial 4, we introduced the + ability to cull triangles based on the order in which the vertices appeared in + window space. Depending on which axis you negate, relative to camera space, an + inversion can flip the expected winding order of vertices. Thus, triangles that + were, in model space, forward-facing now in camera space are backwards-facing. And + vice-versa. + Negative scaling can have other problems as well. This is not to say that + inversions cannot be used, but they should be used with care. +
+
+
+ + Rotation + A rotation transformation is the result of the orientation of + the initial space being different from the orientation of the destination space. The + basis vectors of the space do not change orientation relative to one another, but + relative to the destination coordinate system, they are pointed in different directions + than they were in their own coordinate system. + A rotation looks like this: +
+ Coordinate Rotation in 2D + + + + + +
+ Rotations are usually considered the most complex of the basic transformations, + primarily because of the math involved in computing the transformation matrix. + Generally, rotations are looked at as an operation, such as rotating around a particular + basis vector or some such. The prior part of the tutorial laid down some of the + groundwork that will make this much simpler. + First, let's look back at our equation for determining what the position of a + coordinate is relative to certain coordinate space: + + + + Does not this look a bit familiar? No? Maybe this look at vector-matrix multiplication + will jog your memory: + + + + Still nothing? Perhaps an alternate look would help: + + Vectorized Matrix Multiplication + + + Does it look familiar now? + What this tells us is that the columns of our transformation matrices are, and have + always been, nothing more than the axes of a coordinate system. + Except for the fourth column; because the input position has a 1 in the W, it acts as an + offset. + Transformation from one space to another ultimately means this: taking the basis + vectors and origin point from the original coordinate system and re-expressing them + relative to the destination coordinate system. The transformation matrix from one space + to another contains the basis vectors and origin of the original coordinate system, but + the values of those basis vectors and origin are relative to the + destination coordinate system. + Earlier, we said that numerical coordinates of a space must be expressed relative to + another space. A matrix is a numerical representation of a coordinate system, and its + values are expressed in the destination coordinate system. Therefore, a transformation + matrix takes values in one coordinate system and transforms them into another. It does + this by taking the basis vectors and origin of the input coordinate system and + represents them relative to the output space. To put it another way, the transformation + from space A to space B is what space A looks like from an observer in space B. + A rotation matrix is just a transform that expresses the basis vectors of the input + space in a different orientation. The length of the basis vectors will be the same, and + the origin will not change. Also, the angle between the basis vectors will not change. + All that changes is the relative direction of all of the basis vectors. + Therefore, a rotation matrix is not really a rotation matrix; it is an + orientation matrix. It defines the orientation of one space + relative to another space. Remember this, and you will avoid many pitfalls when you + start dealing with more complex transformations. + For any two spaces, the orientation transformation between them can be expressed as + rotating the source space by some angle around a particular axis (specified in the + initial space). This is true for any change of orientation. + A common rotation question is to therefore compute a rotation around an arbitrary + axis. Or to put it more correctly, to determine the orientation of a space if it is + rotated around an arbitrary axis. The axis of rotation is expressed in terms of the + initial space. In 2D, there is only one axis that can be rotated around and still remain + within that 2D plane: the Z-axis. + In 3D, there are many possible axes of rotation. It does not have to be one of the + initial space's basis axes; it can be any arbitrary direction. Of course, the problem is + made much simpler if one rotates only around the primary axes. + Deriving these matrix equations is beyond the scope of this tutorial; so instead, we + will simply provide them. To perform rotations along the primary axes, use the following + matrices: + + Axial Rotation Matrices + + + When using the standard C/C++ library sin and + cos functions, the angles must be in radians. + As useful as these are, the more generic equation for rotation by an angle about an + arbitrary axis is as follows. + + Angle/Axis Rotation Matrix + + + All of these matrices are such that, from the point of view of an observer looking + down the axis of rotation (the positive direction of the axis is pointed into the eye of + the observer), the object rotates counter-clockwise with positive angles. + The Rotations tutorial shows off each of these + rotation matrix functions. Similar to how the others work, there are multiple instances + rendered based on functions. +
+ Rotation Project + + + + + +
+ The function that builds the transformation matrix looks like this: + + Rotation Transformation Building + glm::mat4 ConstructMatrix(float fElapsedTime) +{ + const glm::mat3 &rotMatrix = CalcRotation(fElapsedTime); + glm::mat4 theMat(rotMatrix); + theMat[3] = glm::vec4(offset, 1.0f); + + return theMat; +} + + The constructor of glm::mat4 that takes a glm::mat3 generates a 4x4 matrix with the + 3x3 matrix in the top-left corner, and all other positions 0 except the bottom-left + corner, which is set to 1. As with much of GLM, this works in GLSL as well. +
+
+ + Fun with Matrices + In all of the previous examples except for the translation one, we always combined the + transformation with a translation operation. So the scale transform was not a pure scale + transform; it was a scale and translate transformation matrix. The translation was there + primarily so that we could see everything properly. + But these are not the only combinations of transformations that can be performed. + Indeed, any combination of transformation operations is possible; whether they are + meaningful and useful depends on what you are doing. + Successive transformations can be seen as doing successive multiplication operations. + For example, if S is a pure scale matrix, T is a pure translation matrix, and R is a + pure rotation matrix, then the shader can compute the result of a transformation as + follows: + vec4 temp; +temp = T * position; +temp = R * temp; +temp = S * temp; +gl_Position = cameraToClipMatrix * temp; + In mathematical terms, this would be the following series of matrix operations: + Final = C*S*R*T*position + , where C is the camera-to-clip space transformation matrix. + This is functional, but not particularly flexible; the series of transforms is baked + into the shader. It is also not particularly fast, what with having to do four + vector/matrix multiplications for every vertex. + Matrix math gives us an optimization. Matrix math is not commutative: + S*R + is not the same as + R*S + . However, it is associative: + (S*R)*T + is the same as + S*(R*T) + . The usual grouping for vertex transformation is this: + Final = C*(S*(R*(T*position))) + . But this can easily be regrouped as: + Final = (((C*S)*R)*T)*position + . + This would in fact be slower for the shader to compute, since full matrix-to-matrix + multiplication is much slower than matrix-to-vector multiplication. But the combined + matrix + (((C*S)*R)*T) + is fixed for all of a given object's vertices. + This can be computed on the CPU, and all we have to do is upload a single matrix to + OpenGL. And since we're already uploading a matrix to OpenGL for each object we render, + this changes nothing about the overall performance characteristics of the rendering (for + the graphics hardware). + This is one of the main reasons matrices are used. You can build + an incredibly complex transformation sequence with dozens of component transformations. + And yet, all it takes for the GPU to use this to transform positions is a single + vector/matrix multiplication. +
+ Order of Transforms + As previously stated, matrix multiplication is not commutative. This means that + the combined transform + S*T + is not the same as + T*S + . Let us explore this further. This is what these two composite + transform matrices look like: + + Order of Transformation + + + The transform + S*T + actually scales the translation part of the resulting matrix. This + means that the vertices will not just get farther from each other, but farther + from the origin of the destination space. It is the + difference between these two transforms: +
+ Transform Order Diagram + + + + + +
+ If you think about the order of operations, this makes sense. Even though one can + think of the combined transform + S*T + as a single transform, it is ultimately a composite operation. The + transformation T happens first; the object is translated into a new position. + What you must understand is that something special happens between S and T. + Namely, that S is now being applied to positions that are not from model space (the + space the original vertices were in), but are in post translation + space. This is an intermediate coordinate system defined by T. + Remember: a matrix, even a translation matrix, defines a full-fledged coordinate + system. + So S now acts on the T-space position of the vertices. T-space has an origin, + which in T-space is (0, 0, 0). However, this origin back in model space is the + translation part of the matrix T. A scaling transformation matrix performs scaling + based on the origin point in the space of the vertices being scaled. So the scaling + matrix S will scale the points away from the origin point in T-space. Since what you + (probably) actually wanted was to scale the points away from the origin point in + model space, S needs to come first. + Orientation (rotation) matrices have the same issue. The orientation is always + local to the origin in the current space of the positions. So a rotation matrix must + happen before the translation matrix. Scales generally should happen before + orientation; if they happen afterwards, then the scale will be relative to the + new axis orientation, not the model-space one. This is fine + if it is a uniform scale, but a non-uniform scale will be problematic. + There are reasons to put a translation matrix first. If the model-space origin is + not the point that you wish to rotate or scale around, then you will need to perform + a translation first, so that the vertices are in the space you want to rotate from, + then apply a scale or rotation. Doing this multiple times can allow you to scale and + rotate about two completely different points. +
+
+ Hierarchical Models + In more complex scenes, it is often desirable to specify the transform of one + model relative to the model space transform of another model. This is useful if you + want one object (object B) to pick up another object (object A). The object that + gets picked up needs to follow the transform of the object that picked it up. So it + is often easiest to specify the transform for object B relative to object A. + A conceptually single model that is composed of multiple transforms for multiple + rendered objects is called a hierarchical model. In such a + hierarchy, the final transform for any of the component pieces is a sequence of all + of the transforms of its parent transform, plus its own model space transform. + Models in this transform have a parent-child relationship to other objects. + For the purposes of this discussion, each complete transform for a model in the + hierarchy will be called a node. Each node is defined by a + specific series of transformations, which when combined yield the complete + transformation matrix for that node. Usually, each node has a translation, rotation, + and scale, though the specific transform can be entirely arbitrary. What matters is + that the full transformation matrix is relative to the space of its parent, not + camera space. + So if you have a node who's translation is (3, 0, 4), then it will be 3 X-units + and 4 Z-units from the origin of its parent transform. The node itself does not know + or care what the parent transform actually is; it simply stores a transform relative + to that. + Technically, a node does not have to have a mesh. It is sometimes useful in a + hierarchical model to have nodes that exist solely to position other, visible nodes. + Or to act as key points for other purposes, such as identifying the position of the + gun's muzzle to render a muzzle flash. + The Hierarchy tutorial renders a hierarchical + model of an arm. This tutorial is interactive; the relative angles of the nodes can + be changed with keyboard commands. The angles are bound within certain values, so + the model will stop bending once these values are exceeded. These commands are as + follows: + + Hierarchy Tutorial Key Commands + + + + + + + Node Angle + Increase/Left + Decrease/Right + + + + + Base Spin + A + D + + + Arm Raise + W + S + + + Elbow Raise + R + F + + + Wrist Raise + T + G + + + Wrist Spin + Z + C + + + Finger Open/Close + Q + E + + + +
+
+ Hierarchy Project + + + + + +
+ The structure of the tutorial is very interesting and shows off a number of + important data structures for doing this kind of rendering. + The class Hierarchy stores the information for our + hierarchy of nodes. It stores the relative positions for each node, as well as angle + information and size information for the size of each rectangle. The rendering code + in display simply does the usual setup work and calls + Hierarchy::Draw(), where the real work happens. + The Draw function looks like this: + + Hierarchy::Draw + void Draw() +{ + MatrixStack modelToCameraStack; + + glUseProgram(theProgram); + glBindVertexArray(vao); + + modelToCameraStack.Translate(posBase); + modelToCameraStack.RotateY(angBase); + + //Draw left base. + { + modelToCameraStack.Push(); + modelToCameraStack.Translate(posBaseLeft); + modelToCameraStack.Scale(glm::vec3(1.0f, 1.0f, scaleBaseZ)); + glUniformMatrix4fv(modelToCameraMatrixUnif, 1, GL_FALSE, + glm::value_ptr(modelToCameraStack.Top())); + glDrawElements(GL_TRIANGLES, ARRAY_COUNT(indexData), + GL_UNSIGNED_SHORT, 0); + modelToCameraStack.Pop(); + } + + //Draw right base. + { + modelToCameraStack.Push(); + modelToCameraStack.Translate(posBaseRight); + modelToCameraStack.Scale(glm::vec3(1.0f, 1.0f, scaleBaseZ)); + glUniformMatrix4fv(modelToCameraMatrixUnif, 1, GL_FALSE, + glm::value_ptr(modelToCameraStack.Top())); + glDrawElements(GL_TRIANGLES, ARRAY_COUNT(indexData), + GL_UNSIGNED_SHORT, 0); + modelToCameraStack.Pop(); + } + + //Draw main arm. + DrawUpperArm(modelToCameraStack); + + glBindVertexArray(0); + glUseProgram(0); +} + + The program and VAO binding code should look familiar, but most of the code should + be fairly foreign. + The MatrixStack object created in the very first line is a + class that is also a part of this project. It implements the concept of a + matrix stack. The matrix stack is a method for dealing + with transformations in hierarchical models. + A stack is a particular data structure concept. Stacks store a controlled sequence + of objects. But unlike arrays, linked lists, or other general data structures, there + are only 3 operations available to the user of a stack: push, pop, and peek. Push + places a value on the top of the stack. Pop removes the value on the top of the + stack, making the previous top the current top. And peek simply returns the current + value at the top of the stack. + A matrix stack is, for the most part, a stack where the values are 4x4 + transformation matrices. Matrix stacks do have a few differences from regular + stacks. C++ has an object, std::stack, that implements the + stack concept. MatrixStack is a wrapper around that object, + providing additional matrix stack functionality. + A matrix stack has a current matrix value. An initially constructed matrix stack + has an identity matrix. There are a number of functions on the matrix stack that + multiply the current matrix by a particular transformation matrix; the result + becomes the new current matrix. For example, the + MatrixStack::RotateX function multiplies the current + matrix by a rotation around the X axis by the given angle. + The MatrixStack::Push function takes the current matrix and + pushes it onto the stack. The MatrixStack::Pop function makes + the current matrix whatever the top of the stack is, and removes the top from the + stack. The effect of these is to allow you to save a matrix, modify the current + matrix, and then restore the old one after you have finished using the modified one. + And you can store an arbitrary number of matrices, all in a specific order. This is + invaluable when dealing with a hierarchical model, as it allows you to iterate over + each element in the model from root to the leaf nodes, preserving older transforms + and recovering them as needed. + In the Draw code, the translation is applied to the stack + first, followed by an X rotation based on the current angle. Note that the order of + operations is backwards from what we said previously. That's + because the matrix stack looks at transforms backwards. When we said earlier that + the rotation should be applied before the translation, that was with respect to the + position. That is, the equation should be + T*R*v + , where v is the position. What we meant was that R should be + applied to v before T. This means that R comes to the right of T. + Rather than applying matrices to vertices, we are applying matrices to each other. + The matrix stack functions all perform right-multiplication; the new matrix being + multiplied by the current is on the right side. The matrix stack starts with the + identity matrix. To have it store T*R, you must first apply the T transform, which + makes the current matrix the current matrix is I*T. Then you apply the R transform, + making the current matrix I*T*R. + Right-multiplication is necessary, as the whole point of using the matrix stack is + so that we can start at the root of a hierarchical model and save each node's + transform to the stack as we go from parent to child. That simply would not be + possible if matrix stacks left-multiplied, since we would have to apply the child + transforms before the parent ones. + The next thing that happens is that the matrix is preserved by pushing it on the + stack. After this, a translation and scale are applied to the matrix stack. The + stack's current matrix is uploaded to the program, and a model is rendered. Then the + matrix stack is popped, restoring the original transform. What is the purpose of + this code? + What we see here is a difference between the transforms that need to be propagated + to child nodes, and the transforms necessary to properly position the model(s) for + rendering this particular node. It is often useful to have source mesh data where + the model space of the mesh is not the same space that our node transform + requires. + In our case, we do this because we know that all of our pieces are 3D rectangles. + A 3D rectangle is really just a cube with scales and translations applied to them. + The scale makes the cube into the proper size, and the translation positions the + origin point for our model space. + Rather than have this extra transform, we could have created 9 or so actual + rectangle meshes, one for each rendered rectangle. However, this would have required + more buffer object room and more vertex attribute changes when these were simply + unnecessary. The vertex shader runs no slower this way; it's still just multiplying + by matrices. And the minor CPU computation time is exactly that: minor. + This concept is very useful, even though it is not commonly talked about to the + point where it gets a special name. As we have seen, it allows easy model reuse, but + it has other properties as well. For example, it can be good for data compression. + There are ways to store values on the range [0, 1] or [-1, 1] in 16 or 8 bits, + rather than 32-bit floating point values. If you can apply a simple + scale+translation transform to go from this [-1, 1] space to the original space of + the model, then you can cut your data in half (or less) with virtually no impact on + visual quality. + Each section of the code where it uses an extra transform happens between a + MatrixStack::Push and + MatrixStack::Pop. This preserves the node's matrix, so that it + may be used for rendering with other nodes. + At the bottom of the base drawing function is a call to draw the upper arm. That + function looks similar to this function: apply the model space matrix to the stack, + push, apply a matrix, render, pop, call functions for child parts. All of the + functions, to one degree or another, look like this. Indeed, they all looks similar + enough that you could probably abstract this down into a very generalized form. And + indeed, this is frequently done by scene graphs and the like. The major difference + between the child functions and the root one is that this function has a push/pop + wrapper around the entire thing. Though since the root creates a MatrixStack to + begin with, this could be considered the equivalent. + + Matrix Stack Conventions + There are two possible conventions for matrix stack behavior. The caller could + be responsible for pushing and popping the matrix, or the callee (the function + being called) could be responsible for this. These are called caller-save and + callee-save. + In caller-save, what it is saying is that a function that takes a matrix stack + should feel free to do whatever they want to the current matrix, as well as + push/pop as much as they want. However, the callee must not + pop more than they push, though this is a general requirement with any function + taking a matrix stack. After all, a stack does not report how many elements it + has, so you cannot know whether someone pushed anything at all. + In callee-save, what the convention is saying is that a function must be + responsible for any changes it wants to make to the matrix stack. If it wants to + change the matrix stack, then it must push first and pop after using those + changes. + Callee-save is probably a better convention to use. With caller-save, a + function that takes a matrix stack must be assumed to modify it (if it takes the + object as a non-const reference), so it will have to do a push/pop. Whereas with + callee-save, you only push/pop as you explicitly need: at the site where you are + modifying the matrix stack. It groups the code together better. + +
+
+
+ + In Review + In this tutorial, you have learned the following: + + + Coordinate systems (spaces) are defined by 3 basis axes and a position. + + + The transformation from one 3D space to another can be defined by a 4x4 + matrix, which is constructed from the 3 basis axes and the position. + + + Model space is the coordinate system that a particular model occupies, + relative to camera space. Other models can have model spaces that depend on the + model space of other models. + + + Scale, translation, and rotation transformations have specific matrix + forms. + + + Transformations can be composed via matrix multiplication. All transformations + for a model can be folded into a single matrix, which a vertex shader can + execute at a fixed rate. Therefore, complex transforms are no slower to execute + (for the graphics chip) than simple ones. + + + The order that successive transforms are applied in matters. Matrix + multiplication is not commutative, and neither is object transformation. + + + Successive transformations can be used to build hierarchies of objects, each + dependent on the accumulated transformations of lower ones. This is done using a + matrix stack. + + +
+ Further Study + Try doing these things with the given programs. + + + In the Translation tutorial, we had two objects that rotated around a + specific point. This was achieved by computing the offset for the rotated + position on the CPU, not through the use of a rotation transformation. + Change this code to use rotation transformations instead. Make sure that the + orientation of the objects do not change as they are being rotated around; + this will require applying more than one rotation transformation. + + + Reverse the order that the two rotations on the wrist are applied in the + Hierarchy tutorial. Note how this affects the ability to adjust the + wrist. + + + Reimplement the Hierarchy tutorial, instead using a more generic data + structure. Have each node be a struct/class that can be attached as a child + to another node. Each node has one parent, but multiple children. The scene + will simply be the root node: the node that has no parent. The individual + angle values should be stored in the node object. The node should have a + render function that will render this node, given the matrix stack. It would + render itself, then recursively render its children. The node would also + have a way to define the size (in world-space) and origin point of the + rectangle to be drawn. + + + Given the generalized Hierarchy code, remove the matrix stack. Use matrix + objects created on the C++ stack instead. The node render function would + take a const& to a matrix rather than a matrix stack reference. + + +
+
+
+ + Glossary + + + space, coordinate system + + This defines what the coordinates used to refer to positions actually + mean. Coordinate systems have a dimensionality (the number of coordinates), + a basis vector for each of the dimensions, and an origin position. A + coordinate system of 3 dimensions therefore is defined by 3 vectors and a + position. The X, Y and Z coordinates in that coordinate system refer to the + value you get when you multiply the X, Y, Z values into the X, Y, and Z + axes, then add the origin position to those values. + + + + basis vector + + One of the vectors that define a coordinate system. The basis vectors of a + coordinate system do not have to be orthogonal or of unit length. + + + + transformation + + The process of moving objects defined in one space to be defined in + another space. + + + + model space + + The space that a particular model is expected to be in. Vertex data stored + in buffer objects is expected to be in model space. + + + + translation transform + + A transform between two spaces, where the origin of the spaces are not in + the same location. This causes objects to shift as they are transformed + between the two spaces. + + + + identity matrix + + The matrix I such that the following is true: + MI = M + , for any matrix M. Identity matrices only exist for square + matrices (a matrix with the same number of columns and rows). An identity + matrix consists of a matrix with ones along the diagonal from the top-left + to the lower-right, and zeros everywhere else. + + + + scale transform + + A transform between two spaces where the axis vectors of the source space + are longer or shorter than the corresponding axis vectors in the destination + space. This causes objects to stretch or shrink along the axes as they are + transformed between the two spaces. + + + + scale inversion + + Performing a scale by a negative value. This is perfectly allowed, though + it can change the winding order of triangles, depending on the axis being + scaled. + + + + orthogonal + + Two vectors are orthogonal if they are perpendicular to each other. Three + vectors are othogonal if each vector is perpendicular to the other + two. + + + + rotation transform, orientation transform + + A transform between two spaces, where the axis vectors of the two spaces + are not pointed in the same direction, but the angle between the axis + vectors stay the same. This cause a reorientation of objects as they are + transformed from the initial space to the destination space. + + + + hierarchical model + + Models can be conceptually composed of multiple independent pieces in a + hierarchy. The space of each component of that hierarchy is stored relative + to its parent in the hierarchy. + + + + node + + A single model space transform within a hierarchy of model transforms. The + node's transform is stored relative to the transform of the node beneath it, + called the parent. Nodes can have a single parent node and multiple child + nodes; the child nodes' transforms are relative to this node's space. + + + +
+
diff --git a/xml/math/elife_41046_v2_622635.xml b/xml/math/elife_41046_v2_622635.xml new file mode 100644 index 0000000..e84319e --- /dev/null +++ b/xml/math/elife_41046_v2_622635.xml @@ -0,0 +1,4 @@ +
elifeeLifeeLife2050-084XeLife Sciences Publications, Ltd4104610.7554/eLife.41046Research AdvanceCell BiologyComputational and Systems BiologySaccharomyces cerevisiae goes through distinct metabolic phases during its replicative lifespanLeupoldSimeonhttps://orcid.org/0000-0002-7186-70611HubmannGeorg1LitsiosAthanasioshttp://orcid.org/0000-0003-3588-49881MeinemaAnne Chttps://orcid.org/0000-0002-0002-34861§TakhaveevVakilhttp://orcid.org/0000-0002-3474-52411PapagiannakisAlexandroshttp://orcid.org/0000-0002-6363-804X1#NiebelBastian1JanssensGeorges2SiegelDavid3HeinemannMatthiashttp://orcid.org/0000-0002-5512-9077m.heinemann@rug.nl1Molecular Systems Biology, Groningen Biomolecular Sciences and Biotechnology InstituteUniversity of GroningenGroningenNetherlandsEuropean Research Institute for the Biology of AgeingUniversity of Groningen, University Medical Centre GroningenGroningenNetherlandsAnalytical Biochemistry, Groningen Research Institute of PharmacyUniversity of GroningenGroningenNetherlandsWeisKarstenReviewing EditorETH ZurichSwitzerlandBarkaiNaamaSenior EditorWeizmann Institute of ScienceIsrael

Laboratory of Molecular Cell Biology, Department of Biology, Institute of Botany and Microbiology, Center for Microbiology, KU Leuven, VIB, Heverlee, Belgium

Institute of Biochemistry, ETH Zurich, Zürich, Switzerland

Microbial Sciences Institute, Yale University, West Haven, United States

Laboratory Genetic Metabolic Diseases, Amsterdam Gastroenterology and Metabolism, Amsterdam UMC, University of Amsterdam, Amsterdam, Netherlands

These authors contributed equally to this work

0904201920198e410462908201809042019© 2019, Leupold et al2019Leupold et alhttp://creativecommons.org/licenses/by/4.0/This article is distributed under the terms of the Creative Commons Attribution License, which permits unrestricted use and redistribution provided that the original author and source are credited.10.7554/eLife.41046.001

A comprehensive description of the phenotypic changes during cellular aging is key towards unraveling its causal forces. Previously, we mapped age-related changes in the proteome and transcriptome (Janssens et al., 2015). Here, employing the same experimental procedure and model-based inference, we generate a comprehensive account of metabolic changes during the replicative life of Saccharomyces cerevisiae. With age, we found decreasing metabolite levels, decreasing growth and substrate uptake rates accompanied by a switch from aerobic fermentation to respiration, with glycerol and acetate production. The identified metabolic fluxes revealed an increase in redox cofactor turnover, likely to combat increased production of reactive oxygen species. The metabolic changes are possibly a result of the age-associated decrease in surface area per cell volume. With metabolism being an important factor of the cellular phenotype, this work complements our recent mapping of the transcriptomic and proteomic changes towards a holistic description of the cellular phenotype during aging.

replicative agingmetabolomemetabolic fluxesmetabolic modellingResearch organismS. cerevisiaehttp://dx.doi.org/10.13039/501100003246Nederlandse Organisatie voor Wetenschappelijk OnderzoekHeinemannMatthiashttp://dx.doi.org/10.13039/501100000780European Commission642738TakhaveevVakilHeinemannMatthiasThe funders had no role in study design, data collection and interpretation, or the decision to submit the work for publication.Author impact statementWith replicative age, S. cerevisiae shifts from a fermentative towards an unusual respiratory metabolism, accompanied by a decrease in growth and glucose uptake rate.
Introduction

Cellular aging is a complex multifactorial process affected by an intertwined network of effectors such as protein translation, protein quality control, mitochondrial dysfunction and metabolism (Barzilai et al., 2012; Kennedy et al., 1994; Lagouge and Larsson, 2013; Webb and Brunet, 2014). Disentangling cause and effect is a major challenge in aging research (McCormick and Kennedy, 2012). A key requisite towards unraveling the causal forces of cellular aging is a comprehensive account of the concomitant phenotypic changes. In the replicatively aging budding yeast Saccharomyces cerevisiae, a common model for mitotic aging (Eisenberg et al., 2007), unfortunately, the application of cell ensemble-based omics methods has been difficult due to the rapid outgrowth of aging mother cells by the newly formed daughter cells. Through a novel cultivation technique, allowing us to generate large amounts of aged cells, we could recently perform proteome and transcriptome profiling throughout the whole lifespan of S. cerevisiae. There, on the basis of an identified gradually increasing uncoupling between protein and transcript levels of biogenesis-related genes, we conjectured that this uncoupling is one of the causal forces of aging (Janssens et al., 2015). Furthermore, we found changes in expression of enzymes and, consistent with an earlier report (Lin et al., 2001), in metabolic genes, suggesting an altered metabolism with increasing replicative age. Here, exploiting our novel cultivation technique (recently also adopted by others; Hendrickson et al., 2018), metabolomics and model-based inference methods (Niebel et al., 2019), we identified a metabolic shift during the replicative lifespan of S. cerevisiae. With this work, we complement our recent proteome and transcriptome profiling data with the corresponding metabolome and fluxome, and generate a description of the functional phenotypic changes accompanied with cellular aging which ultimately lead to senescence and cell cycle arrest.

ResultsColumn-based cultivation to enrich aged mother cells

To generate large quantities of aged cells, required for the metabolic profiling, we used our earlier developed column-based cultivation technique. Here, biotinylated cells attached to streptavidin-conjugated iron beads are immobilized inside a column positioned in the center of a ring magnet. A continuous nutrient flow through the column removes emerging daughter cells, while largely retaining mother cells (Janssens et al., 2015). Several columns operated in parallel, allowed harvesting cells at different time points, corresponding to cell age. In order to be able to infer data for aged cells from the harvested samples (which still contained a fraction of daughter cells), we generated at each harvesting time point three samples differently enriched with aged mother cells; (1) from the column effluent, (2) from the column after an additional washing step, and (3) from the washing solution (in the following referred to as mix 1, 2 and 3) (Figure 1). The exact sample compositions (i.e. the fraction of mother, daughter and dead cells) were determined by flow cytometry using a combined dye-staining with propidium iodide and avidin–FITC. We then determined the cell population-averaged intracellular metabolite concentrations and, to assess physiological parameters, measured the change in extracellular metabolites concentrations due to cell growth over a period of 3 hr. To infer the aged mother cells’ metabolite levels, physiological parameters and intracellular metabolic fluxes from the mixed-sample measurements, we employed different mathematical model-based methods (Figure 1).

10.7554/eLife.41046.002Overview of the experimental and model-based analyses to determine the metabolite levels, physiological parameters and intracellular metabolic fluxes of replicatively aging budding yeast.

Samples were harvested at various time points (corresponding to different cell ages) from a column-based cultivation system (Janssens et al., 2015), designed to enrich aged mother cells. The fractional abundance of mother, daughter and dead cells in each sample was determined by flow cytometry and a combined dye-staining with propidium iodide and avidin–FITC. Aliquots were used to determine the intracellular metabolite concentrations, i, by LC-MS/MS and the cell count, ncell(t), by flow cytometry, extracellular metabolites (i.e. substrates and products), cS(t) and cP(t), by HPLC and the integral of oxygen and carbon transfer rates, OTR and CTR (i.e. total consumed oxygen and produced carbon dioxide) by a Respiration Activity Monitoring System (RAMOS), in the mixed population samples. Next, the age-dependent intracellular metabolite concentrations (ci) were inferred from the acquired population-average data using non-negative least square regression (NNLS) and the physiological parameters (growth (µ) and metabolite exchange rates (q)) of mother (mo) and daughter (da) cells) from an ordinary differential equation (ODE) model. The inferred physiological parameters and intracellular metabolite levels of aged mother cells were then analyzed using a combined stoichiometric-thermodynamic metabolic model and regression analysis to obtain the intracellular metabolic flux distribution.

Intracellular metabolite concentrations decrease with cell age

The intracellular concentrations of 18 metabolites, mainly located in central carbon metabolism, were quantified by LC-MS/MS in the differently mixed samples (i.e. mix 1, 2 and 3), taken at various time points (after 10, 20, 44 and 68 hr). As these concentration measurements resembled the average concentration of metabolites originating from mother and daughter cells, we used non-negative linear regression to infer the metabolite concentration in each individual population (i.e. aged mother and young daughter cells), using the determined fractional abundances of each population and the age-dependent cell volumes, which we determined with microfluidics and microscopy (Figure 2—figure supplement 1). To confirm the validity of the regression approach, where in general a good fitting was achieved (R2 = 0.89) (Figure 2—figure supplement 2), we compared the concentrations for daughter cells, inferred from the mixed population samples, with metabolite concentrations independently determined from a culture of young streptavidin-labeled cells. Here, we found an excellent agreement between mathematically inferred and directly determined concentrations (R2 = 0.99) (Figure 2—figure supplement 3).

Focusing on the intracellular metabolite dynamics in aging mother cells, we found that the concentrations of all quantified metabolites already at a relatively young age start to decrease on average to about half of their initial values (Figure 2a and Figure 2—figure supplement 4). Previously, also other phenotypic changes have been observed at a young age (Janssens and Veenhoff, 2016). Remarkably, despite the drop in ATP levels, the adenylate energy charge was maintained between 0.8 and 0.95 (Figure 2—figure supplement 5), which corresponds to values of exponentially growing cultures (Ditzelmüller et al., 1983). The drop in metabolic concentrations suggests that metabolic activities are globally decreased in aged cells and, as many metabolites have also regulatory function (Huberts et al., 2012; Litsios et al., 2018), the observed concentration changes are expected to lead to metabolic rearrangements.

10.7554/eLife.41046.003Changes in metabolite concentrations and physiological parameters during cellular aging.

(a) The intracellular metabolite concentrations of 18 metabolites at various cell ages were inferred from LC-MS/MS measurements, cell volume measurements and the fractional abundances of each cell population using non-linear least square regression. Grey dashed lines depict the change of intracellular metabolite concentrations relative to concentrations determined from streptavidin-labeled cells (i.e. young cells at an age of 0 hr). The change in ATP concentration is highlighted in red, and FBP (fructose-1,6-bisphosphate) in blue. Figure 2—figure supplement 4 shows the data for each metabolite in absolute units. Figure 2—source data 1 contains the data. (b) The growth (µ), metabolite uptake and production rates at various cell ages were obtained by measuring the evolution of cell count and extracellular metabolites (including produced carbon dioxide and consumed oxygen) and fitting the acquired data to an ordinary differential equation model. A positive value indicates metabolite production and a negative uptake. To assess the validity of the inference approach physiological rates were independently determined from unlabeled and streptavidin-labeled cell cultures (time point 0 hr), consisting of predominantly young cells. The shading reflects the inverse of the relative uncertainty of the estimation (i.e. values which are depicted with a higher transparency are more uncertain). Figure 2—source data 2 contains the data.

10.7554/eLife.41046.016Intracellular metabolite concentrations inferred for daughter and aging mother cells.

10.7554/eLife.41046.017Growth rates and yields inferred for daughter and aging mother cells.

10.7554/eLife.41046.004The cellular volume gradually increases with cellular age.

Individual cells of Saccharomyces cerevisiae were tracked in a microfluidics device (Huberts et al., 2013; Lee et al., 2012) and bright field images were recorded throughout their whole lifespan. The cellular volume was subsequently determined from the acquired microscopic data using the ImageJ plugin BudJ.

10.7554/eLife.41046.005Inference of intracellular metabolite concentrations.

The intracellular concentration of 18 metabolites in daughter and aging mother cells was inferred from data obtained in various mixed population samples using non-negative least square regression where we obtained an excellent fit.

10.7554/eLife.41046.006Comparison of inferred intracellular metabolite concentrations with independently determined concentrations of young cells.

To confirm the validity of inference method for intracellular metabolite concentrations, we determined the metabolite concentration of young streptavidin-labeled cells and compared them to the inferred metabolite concentrations of daughter cells, which, by definition, should have the same phenotype. Here, we found a good consensus, confirming our approach.

10.7554/eLife.41046.007Inference of intracellular concentrations of 18 metabolites with cell age.

We found a drastic decrease of metabolite concentrations with cell age (starting from young daughter cells (da)) of all 18 metabolites: adenosindiphosphat (ADP), adenosinmonophosphat (AMP), aspartic acid (Asp), adenosintriphosphat (ATP), citric acid (Cit), dihyroxy acetone phosphate (DHAP), fructose 1,6-bisphosphate (FBP), fructose-6-phosphate (F6P), glucose-1-phosphate (G1P), glucose-6-phosphate (G6P), glutamic acid (Glu), malic acid (Mal), phenylalanine (Phe), phosphoenolpyruvic acid (PEP), ribose-5-phosphate (R5P), ribulose-5-phosphate (Ru5P), sedoheptulose-7-phosphate (S7P) and succinic acid (Succ). The standard errors were determined by leave-one-out cross-validation, where we one-by-one removed data points from the set and repeated the estimation procedure.

10.7554/eLife.41046.008The energy charge remains constant with cell age.

Despite the vast decrease of the inferred concentrations of all three adenosin nucleotides with cell age, the energy charge was maintained between 0.8 and 0.95, which corresponds to values of exponentially growing cultures (Ditzelmüller et al., 1983).

10.7554/eLife.41046.009Inference of physiological parameters from dynamic changes in extracellular metabolites.

At each time point (after 10, 20, 44 and 68 hr), we measured the evolution of cell count (which was converted to dry weight (i.e. biomass)) and extracellular concentrations of acetate, ethanol, glycerol, pyruvate and glucose over a period of three hours in the harvested sample mix 1. The dry mass specific fractional abundance of each cell population was determined before and after that period. We used a second set of aliquots to measure the evolution of produced carbon dioxide and consumed oxygen using a Respiration Activity Monitoring System (RAMOS) (Hansen et al., 2012). To infer the population-specific physiological rates from the mixed-population samples, we fitted the acquired dynamic data to an ordinary differential equation model, describing the changes of the biomass and extracellular metabolite concentrations in the samples, due to mother and daughter cell growth and their respective metabolism.

10.7554/eLife.41046.010Inference of physiological parameters from dynamic changes in extracellular metabolites.

At each time point (after 10, 20, 44 and 68 hr), we measured the evolution of cell count (which was converted to dry weight (i.e. biomass)) and extracellular concentrations of acetate, ethanol, glycerol, pyruvate and glucose over a period of three hours in the harvested sample mix 2. The dry mass specific fractional abundance of each cell population was determined before and after that period. We used a second set of aliquots to measure the evolution of produced carbon dioxide and consumed oxygen using a Respiration Activity Monitoring System (RAMOS) (Hansen et al., 2012). To infer the population-specific physiological rates from the mixed-population samples, we fitted the acquired dynamic data to an ordinary differential equation model, describing the changes of the biomass and extracellular metabolite concentrations in the samples, due to mother and daughter cell growth and their respective metabolism.

10.7554/eLife.41046.011Inference of physiological parameters from dynamic changes in extracellular metabolites.

At each time point (after 10, 20, 44 and 68 hr), we measured the evolution of cell count (which was converted to dry weight (i.e. biomass)) and extracellular concentrations of acetate, ethanol, glycerol, pyruvate and glucose over a period of three hours in the harvested sample mix 3. The dry mass specific fractional abundance of each cell population was determined before and after that period. We used a second set of aliquots to measure the evolution of produced carbon dioxide and consumed oxygen using a Respiration Activity Monitoring System (RAMOS) (Hansen et al., 2012). To infer the population-specific physiological rates from the mixed-population samples, we fitted the acquired dynamic data to an ordinary differential equation model, describing the changes of the biomass and extracellular metabolite concentrations in the samples, due to mother and daughter cell growth and their respective metabolism.

10.7554/eLife.41046.012FBP (fructose-1,6-bisphosphate) concentration as function of sugar uptake rate.

Fructose-1,6-bisphosphate is a glycolytic flux-signaling metabolite and its concentration strictly correlates with the carbon flow through the glycolysis or the sugar uptake rate (Huberts et al., 2012). The independently inferred rate of glycolysis and FBP concentration in aging cells follows this correlation, providing evidence for the validity of the two independently generated data sets, that is physiological rates and metabolite levels. Black dots (Christen and Sauer, 2011), grey dots (de Assis Souza, 2016) and red dots inferred for aging cells.

10.7554/eLife.41046.013The decreasing growth rate was confirmed using single cell analysis.

The decreasing growth rate inferred with cell age was confirmed using microfluidics and microscopy. Cells from an exponentially growing batch culture were loaded onto a microfluidics device and monitored for >70 hr. The doubling time (time from bud emergence to next bud emergence) was measured for each cell in bright-field images, and the budding rate for each doubling event (ln(2) td−1) was calculated. Budding rates within 6 hr windows were averaged. Note, that the growth rate in Figure 2b was inferred from the increase of biomass in the culture while here the growth rate is determined from the budding rate of individual cells. Because of the prolonged G1 phase of newborn cells and the asymmetric division, both values are not identical, however, show both a decreasing trend.

10.7554/eLife.41046.014The yeast proteome progressively transforms form a fermentation- to a respiration-associated state during aging.

Proteomes of yeast (YSBN6 strain on 2% glucose) obtained at 12 consecutive replicative ages (gradient gray circles) were compared to proteomes of fermenting (KOY WT on 1% glucose) and respiring (KOY TM6 on 1% glucose; Elbing et al., 2004) cells derived from 12 and 13 replicate batch cultures, respectively (blue and red circles). We focused on 396 metabolic proteins present in all proteome data sets and, within each proteome, normalized their abundances by the total one. Next, we centered the 25 proteomes of fermenting and respiring cells together on the origin and performed a principal component analysis (PCA) using the module Sklearn (v0.19.1) in Python (v3.4.3). Next, we centered the proteomes of ageing cells and projected them on two principal components PC1 and PC2 that explain most of the variance among the proteomes of fermenting and respiring cells. PC1 can be interpreted as the fermentation-respiration dimension, that is, the dimension summarizing almost all the differences between the fermentation- and respiration-associated states of the yeast metabolic proteome. Here, we found that the yeast proteome during aging progressively transforms form a fermentation- to a respiration-associated state, similarly as inferred from our physiological analysis (Figures 2b and 3).

10.7554/eLife.41046.015Replicative lifespan is increased in the presence of ethanol.

The replicative lifespan of S. cerevisiae is assessed in a microfluidic dissection platform in 0.5% glucose with and without 0.1% ethanol. The curves represent the survival estimates obtained by the Kaplan-Meier procedure considering the numbers of buds produced by the indicated amount of cells (including the cells that were washed out by the medium flow prior death, that is right censoring of the data; these cells are denoted as “washed”). The shaded area demarks the 95 % confidence intervals. The survival estimates were summarized using the median values and their 95 % confidence intervals (CI). Note that the mean survival with its standard error are 22.32 ± 0.76 in the absence of ethanol and 26.44 ± 1.67 in the presence of ethanol. However, as the right censoring of the data biases the calculation of the mean survival, the median is more robust. The survival curves are compared in the log-rank test whose p-value is given.

Cells switch from a fermentative to a respiratory metabolism with age

To assess changes on the level of metabolic fluxes, we next determined the physiological rates, that is growth, metabolite uptake and excretion rates of aging cells. At each time point (after 10, 20, 44 and 68 hr), we measured the evolution of cell count and extracellular concentrations of glucose, pyruvate, acetate, glycerol and ethanol over a period of three hours in each harvested sample (i.e. mix 1, 2 and 3). The fractional abundance of each cell population was determined before and after that period. We used a second set of aliquots to measure the evolution of produced carbon dioxide and consumed oxygen using a Respiration Activity Monitoring System (RAMOS) (Hansen et al., 2012). To infer the population-specific physiological rates from the mixed-population samples, we fitted the acquired dynamic data to an ordinary differential equation model, describing the changes of the biomass and extracellular metabolite concentrations in the samples, due to mother and daughter cell growth and their respective metabolism (Figure 2—figure supplements 68). To assess the validity of the inference approach, we compared the physiological rates inferred for daughter cells to physiological rates independently determined from unlabeled as well as from streptavidin-labeled cell cultures, both consisting of predominantly young cells. Here, we found a good agreement between the rates mathematically inferred for daughter cells and the rates directly obtained from these cultures containing young cells (Figure 2b).

In aging cells, we found that the specific glucose uptake rate (GUR) decreased drastically towards the end of their lifespan to almost 10% of the value of young cells (Figure 2b), which is in line with the simultaneously decreasing concentration of fructose-1,6-bisphosphate (Figure 2—figure supplement 9) and its function as a glycolytic flux-signaling metabolite (Huberts et al., 2012). This decrease in GUR was accompanied by a reduction of growth rate, which we qualitatively confirmed with single-cell measurements (Figure 2—figure supplement 10). Furthermore, while at a young age, cells showed a fermentative metabolic phenotype indicated by ethanol production and a low oxygen uptake rate (although oxygen was sufficiently available in the setup; Janssens et al., 2015), with increasing age cells shifted towards a respiratory phenotype as indicated by an increase in oxygen uptake and reduced ethanol excretion (Figure 2b). Using principle component analysis, we found a similar shift on the level of protein expression data (Figure 2—figure supplement 11). However, unlike a normal respiratory metabolism, where no byproducts would be excreted, up to half of the carbon influx was directed to glycerol and acetate excretion. Acetate metabolism has been linked to apoptosis (Giannattasio et al., 2013) and the production of glycerol indicates a stress response (Albertyn et al., 1994). This stress response might be crucial for survival at a high replicative age as a gpd1Δ (rate limiting step in the synthesis of glycerol) mutant shows a significant reduced lifespan (Kaeberlein et al., 2002). At the end of their lifespan (starting from time point 44 hr), cells started to co-consume ethanol, produced by surrounding daughter cells, for which we obtained independent evidence from microfluidics experiments (Figure 2—figure supplement 12). The identified stress responsive metabolism and decreased glucose uptake rate are consistent with signatures related to starvation and oxidative stress, as foundin our earlier proteome and transcriptome analysis (Janssens et al., 2015).

Metabolic changes are accompanied by drastic intracellular flux rearrangements

To infer the normalized intracellular flux distributions (i.e. metabolic rates normalized by GUR) from the acquired physiological data, we used a recently developed computational method (Niebel et al., 2019). This method rests on a thermodynamic and stoichiometric model of cellular metabolism (as a function of metabolite concentration and metabolic flux) and was shown to yield predictions in good agreement with 13C based metabolic flux analysis, while not relying on labelling data (Niebel et al., 2019). The model consists of a mass balanced metabolic reaction network, including glycolysis, gluconeogenesis, tricarboxylic acid cycle, amino acid-, nucleotide-, sterol-synthesis and two reactions accounting for the NAD(P)H demand required for scavenging of reactive oxygen species (ROS). The reaction directionalities are constrained by the associated changes in Gibbs energy, and the Gibbs energy dissipated by the sum of all metabolic processes is balanced with the Gibbs energy exchanged with the environment through exchange processes (i.e. the production and consumption of extracellular metabolites). Using this model and regression analysis, we analysed the inferred metabolite concentrations (Figure 2a) and physiological rates (Figure 2b) (Figure 3—figure supplement 1). Subsequently, we assessed the solution space of the regression solution by minimizing the ‘absolute sum of fluxes’ (Holzhütter, 2004) to obtain the normalized intracellular flux distributions during aging.

The inferred intracellular metabolic rearrangements with age echo our findings from the extracellular physiology. Up until an age of 20 hr the intracellular physiology depicted a fermentative phenotype with a low normalized flux into the pentose phosphate pathway and a low normalized flux in an incomplete tricarboxylic acid cycle as the majority of carbon was leaving glycolysis through the pyruvate decarboxylase towards ethanol. After 20 hr, cells began to gradually shift towards a respiratory phenotype, where an increasing proportion of the incoming carbon flux was directed into the pentose phosphate pathway and half of the carbon flux leaving the upper glycolysis going each towards glycerol excretion and through the lower glycolysis in the tricarboxylic acid cycle, while part of the carbon loss was compensated by the uptake of ethanol and pyruvate (Figure 3).

10.7554/eLife.41046.018Rearrangement of normalized fluxes during replicative aging.

The normalized flux distributions (i.e. metabolic rates normalized by GUR) were obtained by minimizing the ‘absolute sum of fluxes’ within the solution space of the regression analysis of the inferred intracellular metabolite concentrations and physiological rates. The thickness of the arrows corresponds to the absolute value of the fluxes, normalized to the glucose uptake rate. The grey dots show the intracellular metabolite concentrations inferred for cells of the respective age where the diameter corresponds to the natural logarithm of the respective concentration. Note, that this figure does not show the complete model stoichiometry of the metabolic network. The numeric values of the respective normalized fluxes can be found in Figure 3—source data 1.

10.7554/eLife.41046.020Reaction stoichiometry of employed metabolic network model, metabolite annotation and inferred predicted intracellular metabolic fluxes normalized to the glucose uptake rates, for aging mother cells.

10.7554/eLife.41046.019Results of the regression analysis using the combined thermodynamic and stoichiometric metabolic model.

The inferred extracellular metabolic rates (normalized by the respective glucose uptake rate) and intracellular metabolite concentrations of mother cell at an age of 0, 10, 20, 44 and 68 hr were analyzed using regression analysis and a combined thermodynamic and stoichiometric metabolic network model. Fitted values from this regression analysis versus inferred values; (a) extracellular rates and (b) intracellular metabolite concentrations.

This switch in metabolic operation was accompanied by an increased redox nucleotide turnover (Figure 4). Up until an age of 20 hr, the majority of NADH was generated in glycolysis and regenerated through the alcohol dehydrogenase. After the switch to respiration, the tricarboxylic acid cycle became the major source of NADH, which in turn was regenerated in the respiratory chain. During the first 20 hr, NADPH turnover was low but after the switch towards respiration NADPH was produced in the pentose phosphate pathway and through the aldehyde dehydrogenase. The increase in redox nucleotide turnover can be attributed to increased demands to combat emerging reactive oxygen species (ROS) (Figure 4). Despite these dramatic changes in cofactor turnover, cells managed to maintain a constant NAD(P)H levels, as observed in age-spanning time-lapse analysis in single cells (Figure 4—figure supplement 1).

10.7554/eLife.41046.021The metabolic rearrangements with age are accompanied by shifts in redox cofactor turnover.

The redox cofactor production and consumption rates (normalized by the respective glucose uptake rate) were obtained by minimizing the absolute sum of fluxes within the solution space of the regression analysis of the inferred intracellular metabolite concentrations and physiological rates. Reactions with a maximal turnover of <0.5 mol molglc−1 were combined and depicted as various. A positive turnover means that the cofactor is produced and a negative turnover that the cofactor is consumed. Note, that we did not enforce the emergence of ROS, however, the model could fit the experimental data the best by using cofactors for ROS scavenging.

10.7554/eLife.41046.022The intracellular NAD(P)H concentration remains constant with cell age.

Individual cells of Saccharomyces cerevisiae were tracked in a microfluidics device and fluorescence images were recorded throughout their whole lifespan. The NAD(P)H concentration was inferred from the acquired autofluorescence (Papagiannakis et al., 2017). Assuming that this measurement mostly reflects the NADH concentration, and assuming that there is a Sirtuin inhibiting effect of NADH, then this effect would be constant through age.

Discussion

Here, employing again the same experimental setup and procedures, we complement our earlier generated transcriptome and proteome account during the replicative aging of the budding yeast Saccharomyces cerevisiae (Janssens et al., 2015), with the metabolic phenotype, inferred from cell ensemble measurements. Next to globally decreased metabolite levels, we found that cells shift with age from a fermentative towards a respiratory phenotype accompanied by a decrease in growth and glucose uptake rate. The increase in cellular volume (and the accompanying decrease in surface area per cell volume) with age (cf. Figure 2—figure supplement 1) could be in part responsible for the observed decrease in the volumetric (i.e. dry weight specific) substrate influx, next to possibly altered hexose transporter expression with age (Kamei et al., 2014). Such decreased substrate influx will lead to decreased glycolytic fluxes, which trigger a switch towards a respiratory metabolism (Huberts et al., 2012). Increased respiratory activity (Figures 2b and 3) could then lead to an increased generation of reactive oxygen species (Drakulic et al., 2005) necessitating an increase in redox cofactor turnover (Figure 4) for ROS scavenging. This cascade of metabolic changes, likely in part induced by the non-homeostatic volume increases and the concomitant collapse in substrate uptake rate, might not only cause detrimental effects due to for example ROS production, but the reduced metabolic rates might also be responsible for the entry into senescence, as it was recently shown that sufficiently high enough metabolic rates are necessary for cells to pass cell cycle start (Papagiannakis et al., 2017).

Materials and methodsMethod 1 | strain and cultivation conditions

The haploid prototrophic Saccharomyces cerevisiae strain, YSBN6 (MATa, FY3 ho::HphMX4) (Canelas et al., 2010), which is derived from S288c, was used in this study. All cultivations were performed using yeast nitrogen base (YNB) without amino acids (ForMedium, Norfolk, UK) supplemented with 2% glucose at 30°C and 300 rpm, unless indicated differently.

Column-based cultivation of yeast cells and sampling

To generate large quantities of aged yeast cells, necessary to perform bulk measurements, we used a method, in which cells were immobilized on iron beads and trapped inside a column (Janssens et al., 2015). Briefly, cells were labelled with biotin and linked to streptavidin-coated iron beads. This iron bead bound cell culture was then grown in a column, equipped with an iron grid, in which the beads (and the cells attached to them) were trapped by a magnet. A continuous medium flow through the column washed out most emerging daughter cells and kept the mother cells in a constant, nutrient-rich environment. With the used flow rate of 170 mL h−1, the glucose concentration stayed almost constant (only dropped from 21.7 to 20.1 g L−1) and the concentration of major byproducts (pyruvate, succinate, glycerol, acetate and ethanol) never exceeded 1 g L−1. Furthermore, the dissolved oxygen saturation never dropped below 75%. The precise instrumental as well as experimental setup for the column-based cultivation and harvest can be found in Janssens et al. (2015).

As samples harvested from the column still resembled a mixture of mother, daughter and dead cells and any subsequent sorting step, aiming at an absolutely pure mother cell fraction would have inherently led to a distortion of the metabolic phenotype, we opted for an approach also followed in our previous study (Janssens et al., 2015), to computationally infer the phenotype of each subpopulation. Specifically, we generated at each aging time point three samples with different proportions of mothers, daughter and dead cells (i.e. (1) from the column effluent, (2) from the column after an additional washing step, (3) from the washing solution (in the following referred to as mix 1, 2 and 3)). After harvesting and before the respective analysis (and for the physiological characterization additionally at the end of the growth experiment), the cell count specific fractional abundance of each subpopulation in each sample was determined by flow cytometry and a combined dye-staining with propidium iodide and avidin – FITC. Later the metabolite concentrations and the cellular physiologies of each individual cell population (i.e. mother, daughter and dead cells) were mathematically inferred from data originating from the mixed samples and the determined fractional abundance.

Method 2 | inference of intracellular metabolite concentrationsRegeneration

To allow the cells to recover from any possible stress during the sampling procedure, all samples were transferred in an Erlenmeyer flask containing 10 mL medium, adjusted to a cell density of 2 × 107 cells mL−1 and incubated for 20 min at 30°C and 300 rpm prior analysis.

Sample preparation

A sample of 3 × 107 cells was taken from the Erlenmeyer flask and immediately quenched in 10 mL −40°C methanol. The cells were separated from the organic solvent by centrifugation (5 min, 21’000 g, 4°C), washed with 2 mL −40°C methanol, separated again by centrifugation and stored at −80°C. For the following analysis, the cell pellet was re-suspended in 900 µL −40°C extraction buffer (methanol, acetonitrile and water, 4:4:2 v/v/v supplemented with 0.1 M formic acid) and an internal standard of 13C-labeled metabolites was added to the extraction. This standard was obtained and quantified from exponentially growing cell cultures prior to the experiment (Wahl et al., 2014). The extraction solution was agitated for 10 min at room temperature and thereafter centrifuged at maximum speed. The supernatant was transferred to a new vial and the cell pellet re-suspended in 900 µL −40°C extraction buffer and the extraction procedure was repeated a second time. The supernatants from both steps were combined and centrifuged for 45 min at 4°C and 21’000 g to remove any remaining non soluble parts. Thereafter, the supernatant was vacuum-dried at 45°C for approximately 1.5 hr and prior to the further analysis dissolved in 200 µL water.

Measurement of intracellular metabolites

The extracted metabolite samples were analyzed using a UHPLC-MS/MS system. The chromatographic separation was performed on a Dionex Ultimate 3000 RS UHPLC (Dionex, Germering, Germany) equipped with a Waters Acquity UPLC HSS T3 ion pair column with precolumn (dimensions: 150 × 2.1 mm, particle size: 3 μm; Waters, Milford, MA, USA). The injection volume was 10 μL and the samples were permanently cooled at 4°C. A binary solvent gradient was employed (0 min: 100% A; 5 min: 100% A 10 min: 98% A; 11 min: 91% A; 16 min: 91% A; 18 min: 75% A, 22 min: 75% A; 22 min: 0% A; 26 min: 0% A; 26 min: 100% A; 30 min: 100% A) at a flow rate of 0.35 mL min−1 where solvent A was composed of 5% methanol in water v/v supplemented with 10 mM tributylamine, 15 mM acetic acid and 1 mM 3,5-heptanedione and isopropanole as solvent B. The detection was done using multiple reaction monitoring (MRM) on a MDS Sciex API365 tandem mass spectrometer, upgraded to EP10+ (Ionics, Bolton, Ontario, Canada) and equipped with a Turbo-Ionspray source (MDS Sciex, Nieuwerkerk aan den Ijssel, Netherlands) with the following source parameter: NEB (nebulizing gas, N2): 12 a.u., CUR (curtain gas, N2): 12 a.u., CAD (collision activated dissociation gas): 4 a.u., IS (ion spray voltage): −4,500 V, TEM (temperature): 500°C.

Mathematical inference of intracellular metabolite concentrations of mother and daughter cells using non-negative least squares regression

The concentrations of intracellular metabolites were determined from samples harvested after 10, 20, 44, and 68 hr. The samples were measured in six replicates and the average of this replicates was used for the mathematical inference. To validate the interference approach we independently determined the intracellular metabolite concentrations of biotin labeled cells before loading them onto the column.

The general idea of the in the following described mathematical inference rests on the concept that a system of linear equations can be solved if the number of independent equations is greater or equal than the number of unknowns. This was implemented by generating at each time point three samples (i.e. mix 1, 2 and 3, cf. Methods 1). The measured concentration in each of these three samples is constituted as the sum of the two unknown concentrations in mother and daughter cells, weighted by their respective known fractional abundance.

Specifically, the in each sample (with ncell cells) measured amount of metabolite, nmeas, contains metabolites originating from mother (mo) and daughter (da) cells. As dead cells were considered to be lysed and their metabolite content accordingly leaked into the medium, we assumed that their contribution to the total metabolite pool can be neglected. With taking the respective volumes of mother and daughter cells (Method 5 and Figure 2—figure supplement 1), and the fractional abundance of each population into account, the amount of substance of each metabolite in each cell is given by,ni,j,kmeasnj,kcell=αj,kVkmoci,kmo+βj,kVdacida,

 where nmeasi,j,k is the measured amount of substance (unit mol) of the metabolite i in the sample j (i.e. mix 1, 2 or 3) at the aging time point k (i.e. 10, 20, 44 or 68 hr), ncellj,k the total amount of cells in the respective sample, αj,k and βj,k the cell count specific fractional abundance of mother and daughter cells, Vmok and Vda the cell volume (unit L cell−1) of mother and daughter cells and cmoi,k and cdai the unknown metabolite concentration (unit M) in mother and daughter cells. Note that cdai and Vda are not indexed over the aging time points k, as we assumed that the daughter cell phenotype does not change over time (i.e. daughter cells produced by young mothers are identical with daughter cells produced by old mothers). To infer the intracellular metabolite concentrations cmo and cda from the measurements, nmeas, we formulated a non-negative least square regression problem of the form,minxAcn22, c0,

 where the matrix A contains all fractional volumes αj,k Vmok and βj,k Vda in every sample j at every aging time point k, the vector c the unknown concentrations cmoi,k and cdai of the metabolite i in mother and daughter cells at every aging time point k and the vector n all metabolite measurements, nmeasi,j,k, normalized by the total amount of cells in the sample, ncellj,k, in every sample j at every aging time point k.

The regression problem in Equation 2 was implemented in MATLAB (Release R2013, MathWorks, Inc, Massachusetts, USA) and the unknown metabolite concentrations, c, in mother and daughter cells were identified using the function ‘lsqnonneg’. The uncertainty of the estimation was then determined by leave-one-out cross-validation, where we one-by-one removed data points from the set and repeated the estimation procedure (Figure 2—figure supplement 4).

Method 3 | inference of growth, metabolite uptake and production rates

The physiological parameters (i.e. growth, metabolite uptake and production rates) were determined from two independent experimental campaigns. In campaign I, samples were harvested after 20, 44 and 68 hr and in campaign II after 10, 20, 44, and 68 hr where the samples from campaign II were split and analyzed in duplicates. The three data sets of both campaigns were combined for the inference. Additionally, we determined the physiologies of biotin labeled cells (referred to as ‘0 hr’) and unlabeled cells (referred to as ‘unlabeled’).

Batch cultivation conditions in minimal medium

The three samples obtained from the cultivation column (i.e. mix 1, 2 and 3) as well as the two reference samples (i.e. 0 hr and unlabeled) were transferred each in a 250 mL Erlenmeyer flask (or RAMOS flasks) containing 25 mL medium, adjusted to a cell density of 2 × 107 cell mL−1, and incubated at 300 rpm and 30°C.

Determination of cell dry weight from cell count

The cell count was measured every 20 min between 1 and 3 hr after inoculation using a BD Accuri C6 flow cytometer (Becton, Dickinson and Company, Franklin Lakes, NJ). The samples were diluted with PBS at pH seven to <106 cell mL−1 and 20 µL sample were counted at 'medium' flow. The FSC-H thresholds was set to 80’000 in order to cut off most of the electronic noise. To correct the measured dry weight for the mass of iron beads in the sample, the iron beads were gated separately and counted as well. The data were analyzed using the Accuri CFlow Plus software.

As the cell volume and thus the cell specific dry weight (i.e. the weight of one cell) of mother cells changes with age, towards converting the measured cell counts to dry weight (biomass), we first determined the cell specific dry weight of mother/dead, mmo/de, and daughter cells, mda. After 3 hr, at the end of each batch cultivation, 20 mL of culture were filtered through a pre-weighed nitrocellulose filter with a pore size of 0.2 µm. The filter was washed once with distilled water, dried at 80°C for two days and afterwards weighed again. The total weight of iron beads attached to mother cells (here we assumed that one mother cell is attached to one iron bead; Janssens et al., 2015) and free beads, which was determined from the counted number of iron beads in the sample and the weight of one individual bead, was subtracted from the total dry weight of each sample. The bead weight had been determined to be 8.49 × 10−13 g per bead by filtration and weighting of a known amount of beads. Next, the cell specific dry weight of mother/dead and daughter cells was inferred from the measured population-average dry weight in the samples, mmeas, by following an in principle similar approach as done for the intracellular metabolite concentrations. Specifically, we assumed that dead cells (i.e. died mother cells) and mother cells have the same dry mass and that the dry mass of newly formed daughter cells does not change over the aging time points. Taking the fractional abundances of each cell population into account, the measured cell specific dry mass in each sample is given as,mj,kmeasnj,kcell=(αj,k+γj,k)mkmo/de+βj,kmda,

 where mmeasj,k is the measured population-average dry mass (unit g) after 3 hr cultivation in the sample j at the aging time point k, ncellj,k the total amount of cells in the respective sample, αj,k the cell count specific fraction of mother cells, γj,k the cell count specific fraction of dead cells, mmo/dek the unknown cell specific dry mass (unit g) of mother or dead cells, βj,k the cell count specific fraction of daughter cells and mda the unknown cell specific dry mass (unit g) of daughter cells. Next, we formulated a least square regression problem of the form,minxAmn22,

 where the matrix A contains all fractional abundances αj,k + γj,k and βj,k in every sample j at every aging time point k, the vector m the unknown cell specific dry weights mmo/dek and mda at every aging time point k and the vector n all measured cell dry weights, mmeasj,k, normalized by the total amount of cells in the sample, ncellj,k, in every sample j at every aging time point k. The regression problem in Equation 4 was implemented in R (Release 3.2.0) and the unknown cell specific dry weights, m, of mother/dead and daughter cells were identified using the function ‘lm’.

The inferred cell specific dry weights of mother/dead and daughter cells were then used to convert the measured cell counts to dry weight. At the beginning of each cultivation (t = 0) the total dry weight, Xtt=0, is constituted of mother/dead and daughter cells, taking their fractional abundance into account, while in the following all new emerging cells are daughter cells. The total dry weight at every time t, Xt, is then given as,Xt,j,k=(αt=0,j,k+γt=0,j,k)nt=0,j,kmkmo/de+βt=0,j,knt=0,j,kmdaXt=0,j,k+(nt,j,knt=0,j,k)mda,

 where Xt,j,k is the dry weight of the mixed population sample j of the aging time point k at time t, αt=0,j,k + γt=0,j,k and βt=0,j,k the cell count specific fractional abundances of mother/dead and daughter cells at the beginning of the cultivation, nt=0,j,k the cell count at the beginning of the cultivation and nt,j,k the cell count at the time t. Note that k refers to the cell age (i.e. aging time point) and t refers to the cultivation time at each aging time point (between 0 and 3 hr).

Additionally, the inferred cell specific dry weights of mother/dead and daughter cells were used to convert the cell count specific fractional abundances, αj,k, βj,k, and γj,k, in the dry mass specific fractional abundances of mother, daughter and dead cells, αdwj,k, βdwj,k, and γdwj,k, in every sample j at every aging time point k:αj,kdw=αj,kmkmo/de(αj,k+γj,k)mkmo/de+βj,kmda,βj,kdw=βj,kmkmo/de(αj,k+γj,k)mkmo/de+βj,kmda,γj,kdw=γj,kmkmo/de(αj,k+γj,k)mkmo/de+βj,kmda,

Determination of glucose and extracellular metabolite concentration

0.3 mL samples were taken every 20 min from 1 to 3 hr after inoculation. To separate the cells from the medium, the samples were centrifuged at maximum speed for 3 min, the supernatant transferred onto a filter column (SpinX, pore size 0.22 µm), again centrifuged at maximum spend and the flow through was further analyzed. The glucose, pyruvate, glycerol, acetate and ethanol concentration was detected using an Agilent 1290 LC HPLC system equipped with a Hi-Plex H column and 5 mM H2SO4 as eluent at a constant flow rate of 0.6 mL min−1. The injection volume was 10 µL and the column temperature was kept constant at 60°C. Glucose, glycerol, ethanol and acetate were detected by refractive index and pyruvate by UV (constant wave length of 210 nm) and the respective concentrations were determined using an external standard with known concentrations. The data were analyzed using the Agilent Open Lab CDS software.

Determination of total consumed oxygen and produced carbon dioxide

The oxygen transfer rate (OTR) and carbon dioxide transfer rate (CTR) were determined from exhaust gas analysis using a respiration activity monitoring system (RAMOS) (Hansen et al., 2012). The RAMOS measurement flask, containing 25 mL medium, was inoculated with 2 × 107 cell mL−1 and the cultivation conditions were identical to the batch cultures used to determine the other physiological parameters. One RAMOS measurement cycle encompassed a 10 min measuring phase and a 20 min rinsing phase. The total consumption of oxygen and the production of carbon dioxide in a time interval were calculated from the mean of two consecutive OTR and CTR measurement cycles multiplied by the time.

Inference of growth, metabolite uptake and production rates of mother and daughter cells

To infer the physiological parameter of mother (mo), daughter (da) and dead (de) cells from the mixed population measurements, we formulated an ordinary differential equation model describing the dynamic change of biomass and extracellular metabolites during the 3 hr cultivation in each sample. To this end, we assumed that the physiology of daughter cells stays constant over all aging time points and that within the 3 hr cultivation the physiology of the mother cells stays constant. Finally, due to the short experiment time the evaporation of water and metabolites was neglected.

The total biomass in the sample is constituted of mother, dead and daughter cells and thus the differential mass balance can be formulated as,0=ddtαj,kdw+ddtβj,kdw+ddtγj,kdw.

Due to the short experiment time (3 hr) compared to their life span (>50 hr), we assumed that the amount of initial mother and dead cells stays constant (i.e. no new mother cells emerge and no mother cells die during the experiment). Thus,ddtXj,kmo=ddt(αj,kdwXj,k)=0,andddtXj,kde=ddt(γj,kdwXj,k)=0,

 where Xj,k is the total biomass and Xmoj,k and Xdej,k the biomass of mother and dead cells in sample j at the aging time point k.

From Equation 9, 10 and 11, and follows that the change in total biomass is only due to the change in daughter cell biomass, Xdaj,k, which in turn can be either due to the emergence of new daughter cells originating from mother cells (i.e. budding of mother cells) or originating from daughter cells (i.e. budding of daughter cells). Thus, the change of the total biomass is given as,ddtXj,k=ddtXj,kda=ddt(βj,kdwXj,k)=μkmoαj,kdwXj,k+μdaβj,kdwXj,k,

 where µmok is the growth rate (unit h−1) of mother cells and µda is the growth rate (unit h−1) of daughter cells.

Reformulating the partial derivatives in Equations 10 and 11 and adding Equation 12 yields the change in dry mass specific fractional abundance of mother and dead cells as,ddtαj,kdw=αj,kdwXj,kddtXj,k=αj,kdw(αj,kdwμkmo+βj,kdwμda),andddtγj,kdw=γj,kdwXj,kddtXj,k=γj,kdw(αj,kdwμkmo+βj,kdwμda),and plugging Equations 13 and 14 and in the differential biomass balance (Equation 9) yields the change in fractional abundance of daughter cells due to budding of mother and daughter cells as,ddtβj,kdw=(αj,kdw+γj,kdw)(αj,kdwμkmo+βj,kdwμda).

Next, the change in glucose concentration in the medium can be due to the uptake by mother and daughter cells as in,ddtcglc,j,k=Xj,k(αj,kdwμkmoYXS,kmoqS,kmo+βj,kdwμdaYXSdaqSda),

 where cglc,j,k is the measured glucose concentration (unit g L−1) in sample j at the aging time point k, qSmok and qSda the specific uptake rates of mother and daughter cells and YXSmok and YXSda the biomass yields (unit g gGLU−1) of mother and daughter cells.

In a similar way, the mass balance for oxygen, carbon dioxide and other fermentation products can be formulated:ddtcO2,j,k=Xj,k(αj,kdwYO2S,kmoμkmoYXS,kmoqO2,kmo+βj,kdwYO2SdaμdaYXSdaqO2da),ddtcP,j,k=Xj,k(αj,kdwYPS,kmoμkmoYXS,kmoqP,kmo+βj,kdwYPSdaμdaYXSdaqPda),

 where qO2mok, qO2da, qPmok and qPda are the biomass specific oxygen uptake and product (including carbon dioxide) excretion rates (unit g gDW−1 h−1) of mother and daughter cells at the aging time point k and YO2Smok, YO2Sda, YPSmok and YPSda the respective oxygen and product yields (unit g gGLU−1) of mother and daughter cells.

To increase robustness in the estimation, we stated that the mother and daughter cell physiology needs to fulfill the carbon balance within a certain range.0.5qPCqSC1.5,

 where qCS and qCP are the specific carbon uptake and excretion rates (unit C-mol gDW−1 h−1) of mother and daughter cells.

All three datasets were combined into one parameter estimation problem subject to the Equations 12–19. All parameters (including initial conditions) as well as the associated uncertainties were estimated using Maximum Likelihood estimation implemented in the software gPROMS ModelBuilder (Release 4.0, PSE software systems) with the MINLP solver SRQPD where a constant variance (error model) was assumed for all measurements.

Method 4 | inference of intracellular metabolic fluxesComputational model of cellular metabolism

To determine the intracellular fluxes at different cell ages from the inferred metabolite concentrations and physiologies, we made use of a recently published computational inference method (Niebel et al., 2019). This method rests on a combined thermodynamic and stoichiometric network model of cellular operation, M(v,lnc)≤0 (Equation 20), consisting of a mass balanced metabolic reaction network, in which the reaction directionalities are constraint by the associated changes in Gibbs energy – as a function of the metabolite concentrations c – through the 2nd law of thermodynamics. Additionally, the Gibbs energy, which is dissipated through metabolic operation (i.e. the sum of all metabolic processes, MET) is balanced with the Gibbs energy exchanged with the environment through exchange processes (i.e. the production and consumption of metabolites, EXG),{M(v,lnc)0}={jMETSijvj=viEXGiΔrG(lncj)vj0jMETjMETΔrG(lncj)vj=iEXGΔfG(lnci)vi},

 where Sij is the stoichiometric coefficient of the ith reactant (i.e. metabolite) in reaction j, vj the rate of the reaction j (i.e. the flux through this reaction), ΔrG’(ln cj) the Gibbs free energy of reaction of the metabolic process j and ΔfG’(ln ci) the Gibbs free energy of formation of the reactant i.

The published, and here used, model for Saccharomyces cerevisiae encompasses the metabolic processes of glycolysis, gluconeogenesis, tricarboxylic acid cycle, amino acid-, nucleotide-, sterol-synthesis and considers the processes’ location in the cytosol, mitochondria and extracellular space. To account for cofactor turnover due to the combatting of reactive oxygen species, which is known to occur at high replicative ages (Ayer et al., 2014), the model was extended by reactions describing the oxidation of NADH and NADPH through glutathione in the cytoplasm as well as the glutathione exchange (i.e. a sink and a source). This exchange does not represent any direct metabolic process but needed to be included since the glutathione metabolism is not part of this model.             nadh[c] + gthox[c] => nad[c] + (2) gthrd[c] +             nadh[c] + gthox[c] => nad[c] + (2) gthrd[c] +                               gthox[c] <=> +                               gthrd[c] <=>

A more detailed description of this model and its implementation can be found in Niebel et al. (2019).

Regression analysis

Using this model and the inferred age-dependent metabolite concentrations and physiologies, we formulated a regression problem minimizing the weighted residual sum of squares, RSS(y) (Equation 21). As data we used (i) the inferred yields, Y~i(k) (iPY… physiological yield), (ii) the inferred metabolite concentrations c~i(k) (iMC1iMC2… metabolite concentration set 1 or 2 (see below)), both of daughter and aged mother cells at a replicate age of 0, 10, 20, 44 and 68 hr and (iii) standard Gibbs energies of reaction, ΔrG~jo. The later were determined (including uncertainty) using the component contribution method (Noor et al., 2013) and as this was not possible for all standard Gibbs energies, to prevent overfitting, the regression was regularized by the Lasso method (Hastie et al., 2011).

To ensure the same thermodynamic reference state (i.e. the same standard Gibbs energies of reactions) in all experimental conditions, we bundled all datasets in on regression problem and indexed the model (Equation 20) over the experimental conditions k.RSS¯(y)=1#nYk,iPY(vi(k)vglcD_EX(k)Y~i(k)Y~i(k),SE)2+1#nc[k,iMC1(elnci[c](k)c~i(k)c~i(k),SE)2+k,iMC2(0.9elnci[c](k)+0.1elnci[m](k)c~i(k)c~i(k),SE)],+1#nCCMjCC(ΔrGjoΔrG~joΔrG~jo,SE)2+0.05#nunk|ΔrGjo|where #nY and #nc are the number of inferred yields and metabolite concentrations, #nCCM the number of standard Gibbs energies of reaction, which could be estimated by the component contribution method and #nunk the number of reactions where no standard Gibbs energy of reaction could be calculated. The residuals were weighted by the respective prediction uncertainty, indicated by the superscript SE. Metabolites can occur in the cytoplasm and/or in the mitochondrial space (MC1… metabolites occurring in one compartment and MC2… metabolites occurring in two compartments). Thus, we stated that the sum of the metabolite concentrations in the respective compartments, weighted by the fractional compartmental volume (0.9 for the cytoplasm and 0.1 for the mitochondrial space), had to be equal to the inferred (cell-averaging) concentration. Last, to facilitate the convergence of the optimization and for an easy conversion of reaction rates to yields, the glucose uptake rate, vglc-D_EX, was constraint to a value of 1 mmol gDW-1 h-1.

The regression analysis was implemented in the mathematical programming system GAMS (GAMS Development Corporation; General Algebraic Modeling System (GAMS) Release 24.2.2. Washington, DC, USA).

Evaluation of the solution space

To obtain a picture of the intracellular flux distribution, we formulated the solution space, Ωreg (Equation 22), of the optimal regression solution, indicated by an *,Ωreg={(v(k),lnc(k),ΔrGo)|M(k)(v(k),lnc(k),ΔrGo)(vi(k)vglcD_EX(k)=Yi(k) iPY)(lnci(k)=lnci(k) iMC1)(0.9elnci[c](k)+0.1elnci[m](k)=0.9elnci[c](k)+0.1elnci[m](k) iMC2)(ΔrGo=ΔrGo)}.

Within this solution space we then minimized the ‘absolute sum of fluxes’,min{j|vj|:(v,lnc)Ωreg}.

The optimization problem in Equation 23 was implemented in the mathematical programming system GAMS (GAMS Development Corporation; General Algebraic Modeling System (GAMS) Release 24.2.2. Washington, DC, USA).

Method 5 | determination of NAD(P)H concentration, budding rate, cell size and replicative lifespan using single cell analysisMicroscopy

For microscopy experiments, cells from exponentially growing batch cultures were used to load a microfluidic device (Huberts et al., 2013; Lee et al., 2012). Individual cells were monitored using an inverted fluorescence microscope (Eclipse Ti-E; Nikon) housed in an custom-made microscope incubator (Life Imaging Services GmbH) that retained at a constant temperature of 30°C. During the experiment, cells were continuously fed with fresh medium. An LED-based excitation system (pE2; CoolLED) was used for illumination, and images were recorded using an Andor 897 Ultra EX2 EM-CCD camera. NAD(P)H autofluorescence (excitation at 365 nm using a 357/44 nm filter and a 409 nm beam-splitter, 200 ms exposure time, 15 % light intensity, 435/40 nm emission, EM gain 1) was recorded every 60 min to minimize phototoxic effects, and brightfield images every 10 min to reliably track individual cells and determine their division times. A CSI S Fluor 40x Oil (NA = 1.3; Nikon) objective was used for NAD(P)H. Automated hardware (PFS, Nikon) was used for correction of axial focus fluctuations during imaging.

Image and data analysis

Cell segmentation for estimation of cell volume and fluorescence intensity took place in a semi-automated manner using the ImageJ plugin BudJ (Ferrezuelo et al., 2012). For cell volume estimation, brightfield images captured with the 60x objective were used. Fluorescent intensity measurements were corrected for background fluorescence using the Rolling Ball Radius algorithm of ImageJ. For budding rate estimations on the basis of single-cells, the doubling time, td, (time from bud emergence to bud emergence) was measured for each cell in 60x brightfield images, and the budding rate for each doubling event (ln(2) td-1) was calculated.

Replicative lifespan

Cells from an exponentially growing culture (minimal medium; Verduyn et al., 1992) supplemented with 1 % (w/v) glucose were loaded in two identical microfluidic devices located on one cover glass. Minimal media supplemented with 0.5 % (w/v) glucose with and without 0.1 % (v/v) ethanol were constantly supplied into the two microfluidic devices, respectively. The cells in the microfluidic devices were monitored simultaneously by taking bright-field images every 10 minutes for more than 5 days (halogen lamp with a UV-blocking filter, 60x objective). The time points of budding, death and washout loss were recorded for individual cells using a custom macro in ImageJ. The number of budding events and fate (death or washed) of the individual cells in both microfluidic devices were used to assess the replicative age-associated survival via the Kaplan-Meier estimator. The analysis was implemented using the Lifelines (0.9.4) module in Python (2.7.13). The mean survival and its standard error were calculated using the Survival (2.43-3) package in R (3.4.1) integrating the survival curves until 44 buds (the maximal number of buds per cell in two conditions).

Acknowledgements

We thank Silke Vedelaar for support during the metabolite extraction, Pieter Schmal and Alfredo Ramos from Process Systems Enterprise (PSE) for their support on the implementation of the ODE model.

Additional informationCompeting interests

No competing interests declared

Author contributions

Software, Formal analysis, Investigation, Visualization, Methodology, Writing—original draft, Writing—review and editing

Conceptualization, Software, Formal analysis, Investigation, Visualization, Writing—original draft, Writing—review and editing

Formal analysis, Investigation, Visualization

Conceptualization, Investigation

Formal analysis, Investigation, Visualization

Investigation

Methodology

Investigation

Investigation

Conceptualization, Supervision, Funding acquisition, Writing—original draft, Project administration, Writing—review and editing

Additional files10.7554/eLife.41046.023Data availability

All data generated or analysed during this study are included in the manuscript and supporting files.

ReferencesAlbertyn JHohmann SPrior BA1994Characterization of the osmotic-stress response in Saccharomyces cerevisiae: osmotic stress and glucose repression regulate glycerol-3-phosphate dehydrogenase independentlyCurrent Genetics25121810.1007/BF007129608082159Ayer AGourlay CWDawes IW2014Cellular redox homeostasis, reactive oxygen species and replicative ageing in Saccharomyces cerevisiaeFEMS Yeast Research14607210.1111/1567-1364.1211424164795Barzilai NHuffman DMMuzumdar RHBartke A2012The critical role of metabolic pathways in agingDiabetes611315132210.2337/db11-130022618766Canelas ABHarrison NFazio AZhang JPitkänen JPvan den Brink JBakker BMBogner LBouwman JCastrillo JICankorur AChumnanpuen PDaran-Lapujade PDikicioglu Dvan Eunen KEwald JCHeijnen JJKirdar BMattila IMensonides FINiebel APenttilä MPronk JTReuss MSalusjärvi LSauer USherman DSiemann-Herzberg MWesterhoff Hde Winde JPetranovic DOliver SGWorkman CTZamboni NNielsen J2010Integrated multilaboratory systems biology reveals differences in protein metabolism between two reference yeast strainsNature Communications114510.1038/ncomms115021266995Christen SSauer U2011Intracellular characterization of aerobic glucose metabolism in seven yeast species by 13C flux analysis and metabolomicsFEMS Yeast Research1126327210.1111/j.1567-1364.2010.00713.x21205161de Assis Souza R2016Correlations Between Yeast Physiological and Morphological Parameters: Explanation for the Crabtree Effect Could Rely on Cell MorphologyUniversidade Federal de ViçosaDitzelmüller GWöhrer WKubicek CPRöhr M1983Nucleotide pools of growing, synchronized and stressed cultures of Saccharomyces cerevisiaeArchives of Microbiology135636710.1007/BF004194846354131Drakulic TTemple MDGuido RJarolim SBreitenbach MAttfield PVDawes IW2005Involvement of oxidative stress response genes in redox homeostasis, the level of reactive oxygen species, and ageing in Saccharomyces cerevisiaeFEMS Yeast Research51215122810.1016/j.femsyr.2005.06.00116087409Eisenberg TBüttner SKroemer GMadeo F2007The mitochondrial pathway in yeast apoptosisApoptosis121011102310.1007/s10495-007-0758-017453165Elbing KLarsson CBill RMAlbers ESnoep JLBoles EHohmann SGustafsson L2004Role of hexose transport in control of glycolytic flux in Saccharomyces cerevisiaeApplied and Environmental Microbiology705323533010.1128/AEM.70.9.5323-5330.200415345416Ferrezuelo FColomina NPalmisano AGarí EGallego CCsikász-Nagy AAldea M2012The critical size is set at a single-cell level by growth rate to attain homeostasis and adaptationNature Communications3101210.1038/ncomms201522910358Giannattasio SGuaragnella NZdralević MMarra E2013Molecular mechanisms of Saccharomyces cerevisiae stress adaptation and programmed cell death in response to acetic acidFrontiers in Microbiology43310.3389/fmicb.2013.0003323430312Hansen SHariskos ILuchterhand BBüchs J2012Development of a modified Respiration Activity Monitoring System for accurate and highly resolved measurement of respiration activity in shake flask fermentationsJournal of Biological Engineering61110.1186/1754-1611-6-1122901278Hastie TJTibshirani RFriedman J2011The Elements of Statistical Learning: Data Mining, Inference, and PredictionSpringerHendrickson DGSoifer IWranik BJKim GRobles MGibney PAMcIsaac RS2018A new experimental platform facilitates assessment of the transcriptional and chromatin landscapes of aging yeasteLife7e3991110.7554/eLife.3991130334737Holzhütter HG2004The principle of flux minimization and its application to estimate stationary fluxes in metabolic networksEuropean Journal of Biochemistry2712905292210.1111/j.1432-1033.2004.04213.x15233787Huberts DHNiebel BHeinemann M2012A flux-sensing mechanism could regulate the switch between respiration and fermentationFEMS Yeast Research1211812810.1111/j.1567-1364.2011.00767.x22129078Huberts DHSik Lee SGonzáles JJanssens GEVizcarra IAHeinemann M2013Construction and use of a microfluidic dissection platform for long-term imaging of cellular processes in budding yeastNature Protocols81019102710.1038/nprot.2013.06023640166Janssens GEMeinema ACGonzález JWolters JCSchmidt AGuryev VBischoff RWit ECVeenhoff LMHeinemann M2015Protein biogenesis machinery is a driver of replicative aging in yeasteLife4e0852710.7554/eLife.0852726422514Janssens GEVeenhoff LM2016Evidence for the hallmarks of human aging in replicatively aging yeastMicrobial Cell326327410.15698/mic2016.07.51028357364Kaeberlein MAndalis AAFink GRGuarente L2002High osmolarity extends life span in Saccharomyces cerevisiae by a mechanism related to calorie restrictionMolecular and Cellular Biology228056806610.1128/MCB.22.22.8056-8066.200212391171Kamei YTamada YNakayama YFukusaki EMukai Y2014Changes in transcription and metabolism during the early stage of replicative cellular senescence in budding yeastJournal of Biological Chemistry289320813209310.1074/jbc.M114.60052825294875Kennedy BKAustriaco NRGuarente L1994Daughter cells of Saccharomyces cerevisiae from old mothers display a reduced life spanThe Journal of Cell Biology1271985199310.1083/jcb.127.6.19857806576Lagouge MLarsson NG2013The role of mitochondrial DNA mutations and free radicals in disease and ageingJournal of Internal Medicine27352954310.1111/joim.1205523432181Lee SSAvalos Vizcarra IHuberts DHLee LPHeinemann M2012Whole lifespan microscopic observation of budding yeast aging through a microfluidic dissection platformPNAS1094916492010.1073/pnas.111350510922421136Lin SSManchester JKGordon JI2001Enhanced gluconeogenesis and increased energy storage as hallmarks of aging in Saccharomyces cerevisiaeJournal of Biological Chemistry276360003600710.1074/jbc.M10350920011461906Litsios AOrtega ÁDWit ECHeinemann M2018Metabolic-flux dependent regulation of microbial physiologyCurrent Opinion in Microbiology42717810.1016/j.mib.2017.10.02929154077McCormick MAKennedy BK2012Genome-scale studies of aging: challenges and opportunitiesCurrent Genomics1350050710.2174/13892021280325145423633910Niebel BLeupold SHeinemann M2019An upper limit on Gibbs energy dissipation governs cellular metabolismNature Metabolism112513210.1038/s42255-018-0006-7Noor EHaraldsdóttir HSMilo RFleming RM2013Consistent estimation of Gibbs energy using component contributionsPLOS Computational Biology9e100309810.1371/journal.pcbi.100309823874165Papagiannakis ANiebel BWit ECHeinemann M2017Autonomous metabolic oscillations robustly gate the early and late cell cycleMolecular Cell6528529510.1016/j.molcel.2016.11.01827989441Verduyn CPostma EScheffers WAVan Dijken JP1992Effect of benzoic acid on metabolic fluxes in yeasts: a continuous-culture study on the regulation of respiration and alcoholic fermentationYeast850151710.1002/yea.3200807031523884Wahl SASeifar RMten Pierick ARas Cvan Dam JCHeijnen JJvan Gulik WM2014Quantitative metabolomics using ID-MSMethodsMolecular Biology11919110510.1007/978-1-4939-1170-7_6Webb AEBrunet A2014FOXO transcription factors: key regulators of cellular quality controlTrends in Biochemical Sciences3915916910.1016/j.tibs.2014.02.00324630600
10.7554/eLife.41046.026Decision letterWeisKarstenReviewing EditorETH ZurichSwitzerland

In the interests of transparency, eLife includes the editorial decision letter and accompanying author responses. A lightly edited version of the letter sent to the authors after peer review is shown, indicating the most substantive concerns; minor comments are not usually included.

Thank you for submitting your article "Saccharomyces cerevisiae goes through distinct metabolic phases during its replicative lifespan" for consideration by eLife. Your article has been reviewed by two peer reviewers, and the evaluation has been overseen by a Reviewing Editor and Naama Barkai as the Senior Editor. The reviewers have opted to remain anonymous.

The reviewers have discussed the reviews with one another and the Reviewing Editor has drafted this decision to help you prepare a revised submission.

Summary:

In this Research Advance, Leupold and colleagues take advantage of a previous method that their lab has developed to isolate aged yeast cells with the goal to analyze changes that occur in the metabolome during the ageing process. The major finding is that cells undergo a metabolic shift from fermentation to respiration during aging. The reviewers agreed that this is an interesting study that in principle is suitable for eLife. However, additional experiments and edits to the text will be needed before the paper can be considered for publication.

Essential revisions:

1) The paper is largely descriptive, without getting too much into causality. Some simple tests should be performed to either refute or support some of the authors' hypotheses. For example, to address the role of glycerol, what is the replicative lifespan of mutants that are impaired in glycerol synthesis (e.g., gpd1 mutants)?

2) The authors use a series of complicated mathematical models to indirectly infer the metabolite level, physiological parameters and intracellular metabolic fluxes at different ages from the raw data. Given that quite a number of assumptions and approximations have been used in their models, it is hard to fully trust the inferred results without other supporting evidence. Additional controls and further validation will be needed: (a) Unlabeled cells cultured in column with non-fermentable carbon source would serve as a good control for the respiratory state and can be used to reflect the significance of the changes during aging. (b) Use another population-level aging approach, such as Mother-Enrichment Program, to reproduce some of the metabolite data. It will not be necessary to reproduce all the data, but a couple of important metabolites at a few time points would be important.

3) In Figure 2 and Figure 2—figure supplement 2C, all the metabolite levels drop sharply within 0 – 10 hour (the first time point collected from the column). This is surprisingly early in the aging process. In addition, even some of the physiological parameters, such as the growth rate, drop drastically at 10-hour time point (Figure 2B). This is strikingly different from the time trace they obtained using microfluidics, where there is no change in the first 20 hours (Figure 2—figure supplement 5). This discrepancy raises the suspicion that these metabolic changes may be simply a part of the stress response induced by the column-based culturing condition. Additional controls would be needed to confirm that the column-based culturing condition is not stressful, e.g. using stress responsive genes that will not be induced during the first 10 hours of aging in microfluidics. Ideally, one would hope to see single-cell microfluidics experiments to confirm some of the metabolite time traces using fluorescent reporters.

4) The metabolite flux analysis you describe is very hard to follow, mostly because the details of the methodology are in another paper. That paper is listed as 'in press', and could not be found online. This manuscript or a citation to the published article should be provided along with the revised version of your paper and if it is not already published by then, we urge you to post the article on bioRχiv.

[Editors' note: further revisions were requested prior to acceptance, as described below.]

Thank you for submitting your article Saccharomyces cerevisiae goes through distinct metabolic phases during its replicative lifespan" for consideration by eLife. Your article has been reviewed by two peer reviewers, and the evaluation has been overseen by a Reviewing Editor and Naama Barkai as the Senior Editor. The reviewers have opted to remain anonymous.

The reviewers have discussed the reviews with one another and the Reviewing Editor has drafted this decision to help you prepare a revised submission.

Summary:

Both reviewers agree that the manuscript has improved during the revision and that most of the issues have been adequately addressed by the authors. However, there are two remaining issues that need attention before the paper can be published in eLife.

1) The new Figure 2—figure supplement 8 needs further clarification: "293 cells (253 washed).…" what does "washed" mean? Why do the authors only report "median" lifespan here? As most lifespan studies report the "mean" rather than the "median", it is important that the mean lifespans is reported as well. Why are there error bars (shaded area) for lifespan curves? Furthermore, a description of the microfluidic experiments needs to be added in the Materials and methods section.

2) The authors hypothesize that the increase in cellular volume with age is the cause of metabolic changes. The reviewers understand the authors' claim that a larger cell has a lower surface-to-volume ratio (and the effect is not through a simple dilution). But the reviewers questioned whether the changes in the surface-to-volume ratio can be the cause of the metabolic changes since then it should occur before or at least at the same time with the metabolic changes. In Figure 2—figure supplement 1, the volume change is very small in the first 10 hours. Does this small volume change lead to a significant enough change of the surface-to-volume ratio to explain a 50% decrease of glucose uptake that occurs in 10 hours? Further discussions and clarifications will be needed.

10.7554/eLife.41046.027Author response

Essential revisions:

1) The paper is largely descriptive, without getting too much into causality. Some simple tests should be performed to either refute or support some of the authors' hypotheses. For example, to address the role of glycerol, what is the replicative lifespan of mutants that are impaired in glycerol synthesis (e.g., gpd1 mutants)?

Note that this paper (as “Research Advance”) was mainly meant to complement our earlier work, where we had presented proteome and transcriptome data during replicative aging, by metabolic profiling data.

Seeking further support for our findings, as suggested, we have looked in the role of glycerol. We had inferred an increased glycerol production as cells age. A deletion of GPD1 (glycerol 3-phosphate dehydrogenase, which is the rate limiting step in the synthesis of glycerol) should thus likely reduce the replicative lifespan, which is indeed the case (i.e. the lifespan reduces from 28 to around 12 generations, PMID: 12391171 Figure 7A). We now mention this in the manuscript.

Second, we had inferred that aged cells take up ethanol, likely produced by the daughter cells that are simultaneously present in the experiments. Seeking independent evidence for this, we performed microfluidic experiments, where we determined the lifespan of cells grown solely in glucose medium and compared their lifespan with the lifespan of cells grown in glucose medium supplemented with ethanol. Here, we found that the ethanol supplementation increased yeast’s lifespan (from 23 to 28 generations), which could serve as an indication that aged cells might indeed take up ethanol. We added this new data as new Figure 2—figure supplement 8 and refer to these data in the main text.

2) The authors use a series of complicated mathematical models to indirectly infer the metabolite level, physiological parameters and intracellular metabolic fluxes at different ages from the raw data. Given that quite a number of assumptions and approximations have been used in their models, it is hard to fully trust the inferred results without other supporting evidence. Additional controls and further validation will be needed: (a) Unlabeled cells cultured in column with non-fermentable carbon source would serve as a good control for the respiratory state and can be used to reflect the significance of the changes during aging. (b) Use another population-level aging approach, such as Mother-Enrichment Program, to reproduce some of the metabolite data. It will not be necessary to reproduce all the data, but a couple of important metabolites at a few time points would be important.

As requested by the reviewers, for this revision, we have performed further experiments and analyses. Note in this context also the additional evidence presented in response to comment 1.

The reviewer suggested to confirm the shift towards a respiratory state by using non-fermentable carbon sources. Along this line, we compared, using principle component analysis, our previously generated proteome data of aging cells with proteome data of two unlabeled S. cerevisiae strains (one having a fermentative and one a respiratory phenotype). The fermentative proteome was obtained from a culture of S. cerevisiae wildtype and the respiratory proteome from a S. cerevisiae strain that lacks all usual hexose transporters but has only a chimeric version of the hexose transporters Hxt1 and Hxt7. The later strain is otherwise isogenic to the wildtype strain but in high-glucose conditions has a low glucose uptake rate and thus respiratory phenotype (cf. PMID: 15345416). In line with our finding of a shift towards a more respiratory metabolism, this analysis showed that also the proteome of aging cells shifts towards a more respiratory phenotype. We added the results of this new analysis as Figure 2—figure supplement 7.

Second, the reviewer suggested the use of the mother-enrichment program (MEP) to reproduce some of the metabolite data. We evaluated the feasibility of the MEP for generating metabolome data. Therefore, we also consulted with Daniele Novarina from the group of Michael Chang who has worked for several years with the MEP. On the basis of these discussions, we had to conclude that the MEP would not be suitable to generate metabolite data of aged cells. The reasons for this are the following:

1) The MEP suffers from the fact that “escapers” can occur, i.e. mutations, through which daughter cells can divide as well. The escaper rate is in the order of 10-6. For this reason, researchers typically only work with very low cell numbers. However, for the metabolome analyses we need in the order of 107 cells. Thus, when using the MEP with such high numbers of cells, over the course of the aging experiment, the culture would be outgrown by daughter cells.

2) If one aims to generate a high amount of cells (as required for metabolome analyses) with a high replicative age (i.e. 64 h), these cells would relatively fast deplete the glucose in the medium during cultivation (i.e. aging). This would require frequent sub-culturing of the cells which has been shown to introduce stress (PMID 17464066) and could thus introduce artifacts.

Thus, we feel that the MEP program would not be capable to generate the large amounts of aged cells, as required for metabolome analyses, in an artifact-free manner.

As an alternative, we explored single-cell metabolite sensors in combination with microfluidics to assess metabolite levels by alternative means. Previously, we had used an ATP FRET sensor to study ATP dynamics during the yeast’s cell cycle (PMID: 27989441). This sensor’s signal, however, is not only dependent on ATP, but also on pH (PMID: 19720993). It turns out that the intracellular pH drops during aging (PMID: 23172144), exactly in the pH range where the ATP FRET signal is affected. Thus, measurements with this sensor will unfortunately not report the correct ATP values during aging.

Still trying to challenge and validate our results, we did the following: We had earlier found that the concentration of the metabolite fructose-1,6-bisphospate (FBP) strictly correlates with the metabolic flux through the glycolytic pathway (PMID: 22129078). This robust correlation was found to hold also during sudden dynamic flux changes (PMID: 16672504) and across different yeast strains (PMID: 21205161). If the metabolite levels and metabolic fluxes, inferred for the aging cells, were consistent, then we could expect that the inferred FBP levels and glycolytic fluxes should comply with this correlation. Indeed, if we plot the inferred FBA concentrations as a function of glycolytic flux, then these data points exactly fall onto the earlier established correlation. In this context it is important to highlight that the inference of the metabolite concentrations and physiological rates are completely independent from each other. Thus, this observation serves as good indication for the validity of both data sets. We added a new Figure 2—figure supplement 6 showing the results of this analysis.

In summary, we provide the following independent supporting evidence for our inferred findings:

- Metabolite concentrations: The mathematically inferred concentrations for (young) daughter cells match the ones directly determined from a culture of (young) labeled cells.

- Metabolite concentrations/flux: The independently inferred FBP concentrations and glycolytic fluxes of aged cells fall onto an earlier established correlation.

- Physiological rates: The mathematically inferred physiological rates for (young) daughter cells match the ones directly determined from cultures of (young) labeled and unlabeled cells.

- Growth rate: The inferred decrease in growth rate with cell age is qualitatively in line with the decrease in budding rate determined in a microfluidic device.

- Shift towards respiration: The inferred shift from a respiratory towards a fermentative metabolism was shown to also occur on the proteome level.

- Production of glycerol: A deletion of GPD1 reduces yeast’s lifespan.

- Uptake of ethanol: Supplementing ethanol to the medium increases yeast’s lifespan.

3) In Figure 2 and Figure 2—figure supplement 2C, all the metabolite levels drop sharply within 0 – 10 hour (the first time point collected from the column). This is surprisingly early in the aging process. In addition, even some of the physiological parameters, such as the growth rate, drop drastically at 10-hour time point (Figure 2B). This is strikingly different from the time trace they obtained using microfluidics, where there is no change in the first 20 hours (Figure 2—figure supplement 5). This discrepancy raises the suspicion that these metabolic changes may be simply a part of the stress response induced by the column-based culturing condition. Additional controls would be needed to confirm that the column-based culturing condition is not stressful, e.g. using stress responsive genes that will not be induced during the first 10 hours of aging in microfluidics. Ideally, one would hope to see single-cell microfluidics experiments to confirm some of the metabolite time traces using fluorescent reporters.

The reviewer is surprised by the changes that occur already at a relatively young age. Please note that with several other experimental methods early-age changes were also reported. For instance, see the figure from PMID: 28357364, a paper in which age-related changes during budding yeast replicative aging were reviewed. Here, many phenotypic changes occur already very early in life (in the figure the 90-100% population viability corresponds to roughly the first 10 h of yeast’s replicative lifespan). Thus, it is not so unexpected to see changes at early time points. We now mention this in the main text.

The reviewer also raised the question whether the cells would be stressed. In our previous eLife paper, we indeed obtained indication that the biotin-labeling of cells introduces stress. However, the proteome and transcriptome data had indicated that this stress is gone 5-8 hours after loading the cells onto the column (note, the earliest time point we report here is 10 h). Further, as we had shown in our previous paper by means of a comparison of lifespan curves, the cells on the column age normally (cf. Figure 1B in previous paper). Last, our earlier generated proteome data from the column-based experiments were consistent with protein expression patterns acquired with other methods to generate aged-cells. Thus, we do not expect that stress, introduced by the experimental procedure, is generating artifacts in our data.

Second, the reviewer pointed to the discrepancy between the ‘growth rates’ of aged cells determined from the column-based experiments and the ones from the microfluidics experiment. Please note that the “growth rate” of cells from the column was determined on the basis of the increase in measured cell dry mass, while in the microfluidics we assessed the time between the appearances of two buds (daughter cells). Although both ‘growth measures’ decrease with time, these two measures are not the same because of yeast’s asymmetric division (with bud cells having smaller volume than mother cells). Thus, the budding rate cannot be directly converted into the cell-dry-weight-determined growth rate. We now make this clearer in the revised version of the manuscript.

Lastly, the reviewer commented on the drop of metabolite levels within the first 10 h. Triggered by this comment, we reevaluated our deconvolution analysis. Earlier, we had assumed a volume for daughter cells of 25 fL (which corresponds to the volume of daughter cells at the time they detach from their mother). However, an analysis of the acquired flow cytometric forward scatter data and a comparison between daughter and aged cells (of known volume) showed that at the time when the metabolomics samples were taken the daughter cell volume rather corresponds to 40 fL (i.e. the initial volume of mother cells). Thus, we re-did the linear regression using a volume of 40 fL for daughter cells. The inferred metabolite concentrations for daughters are (now even more) similar to concentrations obtained from a batch culture of labeled cells before they were loaded on the column (Figure 2—figure supplement 2B). Note that in an effort to increase consistency between Figure 2A and B and Figure 3, we now use the concentrations determined from the aforementioned batch culture of labeled cells as time point 0. We have updated the figures (Figure 2A and Figure 2—figure supplement 2) respectively.

4) The metabolite flux analysis you describe is very hard to follow, mostly because the details of the methodology are in another paper. That paper is listed as 'in press', and could not be found online. This manuscript or a citation to the published article should be provided along with the revised version of your paper and if it is not already published by then, we urge you to post the article on bioRxv.

The manuscript is now published in Nature Metabolism (https://doi.org/10.1038/s42255-018-0006-7). We included its full bibliography. This will further help the reader to better grasp the methods that we applied here.

[Editors' note: further revisions were requested prior to acceptance, as described below.]

Summary:

Both reviewers agree that the manuscript has improved during the revision and that most of the issues have been adequately addressed by the authors. However, there are two remaining issues that need attention before the paper can be published in eLife.

1) The new Figure 2—figure supplement 8 needs further clarification: "293 cells (253 washed).…" what does "washed" mean? Why do the authors only report "median" lifespan here? As most lifespan studies report the "mean" rather than the "median", it is important that the mean lifespans is reported as well. Why are there error bars (shaded area) for lifespan curves? Furthermore, a description of the microfluidic experiments needs to be added in the Materials and methods section.

In the caption of the Figure 2—figure supplement 8 (now Figure 2—figure supplement 12), we clarified what the word “washed” used in the figure means. It means the number of cells washed out from the microfluidic device during the experiment. Further, in the previous version of the manuscript, we had reported only the median lifespans. As requested by the reviewers, in this revision we now also report the mean lifespans and added these numbers to the caption. In essence, the conclusion remains unaltered. In the caption, we now also explain the meaning of the shaded areas accompanying the survival curves. In the Materials and methods section, we created a separate paragraph explaining the replicative lifespan experiment and the analysis.

2) The authors hypothesize that the increase in cellular volume with age is the cause of metabolic changes. The reviewers understand the authors' claim that a larger cell has a lower surface-to-volume ratio (and the effect is not through a simple dilution). But the reviewers questioned whether the changes in the surface-to-volume ratio can be the cause of the metabolic changes since then it should occur before or at least at the same time with the metabolic changes. In Figure 2—figure supplement 1, the volume change is very small in the first 10 hours. Does this small volume change lead to a significant enough change of the surface-to-volume ratio to explain a 50% decrease of glucose uptake that occurs in 10 hours? Further discussions and clarifications will be needed.

While the surface-to-volume ratio changes with increased cell size, the cell size increase is indeed too small to fully account for the decrease in glucose uptake rate. Thus, additional factors are required to explain the observation of the decreased glucose uptake rate. We thus changed the respective sentence in the Discussion. It now reads:

“The increase We hypothesize that the increase in cellular volume (and the accompanying decrease in surface area per cell volume) with age (cf. Figure 2—figure supplement 1) could be in part is responsible for the observed decrease in the volumetric (i.e. dry weight specific) substrate influx, next to possibly altered transporter expression with age (Kamei et al., 2014)”.

We thank the reviewers for pointing this out.

\ No newline at end of file diff --git a/xml/math/equation_004_a5d8f4.xml b/xml/math/equation_004_a5d8f4.xml new file mode 100644 index 0000000..33b2ba9 --- /dev/null +++ b/xml/math/equation_004_a5d8f4.xml @@ -0,0 +1,39 @@ + +
+ MathML Equations + + Quadratic formula + + + x + = + + + + b + ± + + + b + 2 + + + 4 + + a + + c + + + + 2 + + a + + + + + +
diff --git a/xml/math/equation_005_a1808c.xml b/xml/math/equation_005_a1808c.xml new file mode 100644 index 0000000..d9176cc --- /dev/null +++ b/xml/math/equation_005_a1808c.xml @@ -0,0 +1,14 @@ + +
+ + TeX Equations + + +Note that this requires setting the tex-math \(x^2\) parameter. + + + Quadratic formula + $$x = \frac {-b \pm \sqrt{b^2 -4ac}} {2a}$$ + + +
diff --git a/xml/math/example_04c981.xml b/xml/math/example_04c981.xml new file mode 100644 index 0000000..8cb9351 --- /dev/null +++ b/xml/math/example_04c981.xml @@ -0,0 +1,46 @@ + +
+ Area enclosed by a circle + + + + + + + + 1 + + + + + + 0 + + + + + + + + + + + + + + + + 0 + + + + + + 1 + + + + + + +
diff --git a/xml/math/f_5dcc94.xml b/xml/math/f_5dcc94.xml new file mode 100644 index 0000000..335638f --- /dev/null +++ b/xml/math/f_5dcc94.xml @@ -0,0 +1,219 @@ + + +
+ + + mr + + Materials Research + Mat. Res. + + 1516-1439 + 1980-5373 + + ABM, ABC, ABPol + + + + nnBRGz6Rc3nYKcyrLsDCLRt + S1516-14392022000100285 + 00285 + 10.1590/1980-5373-MR-2021-0526 + + + Articles + + + + Structure, Characteristics and Corrosion Behaviour of Gold Nanocoating Thin Film for Biomedical Applications + + + + 0000-0002-8406-0566 + + Wadullah + Haitham M. + + + a + + * + + + + Ali + Mohammed Hadi + + + b + + + + + Abdulrazzaq + Tariq Khalid + + + a + + + + + Northern Technical University + Engineering Technical College + + Mosul + + Iraq + Northern Technical University, Engineering Technical College, Mosul, Iraq. + + + + Middle Technical University + AL-Suwaira Technical Institute + + Baghdad + + Iraq + Middle Technical University, AL-Suwaira Technical Institute, Baghdad, Iraq. + + + + e-mail: haitham@ntu.edu.iq + + + 07 + 03 + 2022 + + + 2022 + + 25 + e20210526 + + + 10 + 10 + 2021 + + + 11 + 02 + 2022 + + + 13 + 02 + 2022 + + + + + This is an Open Access article distributed under the terms of the Creative Commons Attribution License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited. + + + +

Nanocoatings thin films are layers deposited to improve required properties and corrosion resistance as a major objective for materials that are used for various biomedical applications such as biosensors. In this study, Gold (Au) thin films with 50 nm and 100 nm have been synthesized on Ni-Cr-Mo alloys by magnetron sputtering deposition technique. X-Ray diffraction (XRD), Atomic Force Microscopy (AFM), and Energy-dispersive X-Ray spectroscopy /Scanning Electron Microscopy (EDS/SEM ) have been used to distinguish the surfaces morphology. The results showed that there is no defects or micro-cracks with a uniform and homogenous film. It has spherical nanoparticles diameter morphology with 200-400 nm shaped to fine aggregation. The roughness average (Ra) decreased from 3.91 nm for 50 nm films to 3.70 nm for 100nm films with FCC crystal structure (111) for gold thin films. In vivo, after 50 nm and 100 nm nanocoated thin film by gold, a significant improvement in the localized corrosion resistance has been obtained in artificial saliva corrosive media at 37 °C compared with the uncoated surface.

+
+ + Keywords: + Corrosion resistance + sputtering deposition process + gold thin films + Ni-Cr-Mo biomaterial alloy + + + + + + + +
+
+ + +

+ - + 1 + +

+

+ + + + + D + = + + γ + + + + + β + 2 + + + + + + β + + s + t + d + + 2 + + + + c + o + s + θ + + + + + + + +

+

+ + + x + = + + + + - + b + + ± + + + + b + 2 + + - + + 4 + + a + + c + + + + + + 2 + + a + + + +

+
diff --git a/xml/math/journal_pcbi_1005589_type_manuscript_58c02e.xml b/xml/math/journal_pcbi_1005589_type_manuscript_58c02e.xml new file mode 100644 index 0000000..9b03046 --- /dev/null +++ b/xml/math/journal_pcbi_1005589_type_manuscript_58c02e.xml @@ -0,0 +1,818 @@ + + +
+ + +PLoS Comput Biol +plos +ploscomp + +PLOS Computational Biology + +1553-734X +1553-7358 + +Public Library of Science +San Francisco, CA USA + + + +10.1371/journal.pcbi.1005589 +PCOMPBIOL-D-16-01721 + + +Research Article + +Biology and life sciencesComputational biologyGenome analysisGenome-wide association studiesBiology and life sciencesGeneticsGenomicsGenome analysisGenome-wide association studiesBiology and life sciencesGeneticsHuman geneticsGenome-wide association studiesResearch and analysis methodsMathematical and statistical techniquesStatistical methodsForecastingPhysical sciencesMathematicsStatistics (mathematics)Statistical methodsForecastingBiology and life sciencesGeneticsGenetics of diseaseBiology and life sciencesComputational biologyGenome analysisGenome annotationBiology and life sciencesGeneticsGenomicsGenome analysisGenome annotationMedicine and health sciencesOncologyCancers and neoplasmsBreast tumorsBreast cancerBiology and life sciencesGeneticsGenomicsFunctional genomicsMedicine and health sciencesRheumatologyArthritisRheumatoid arthritisMedicine and health sciencesClinical medicineClinical immunologyAutoimmune diseasesRheumatoid arthritisBiology and life sciencesImmunologyClinical immunologyAutoimmune diseasesRheumatoid arthritisMedicine and health sciencesImmunologyClinical immunologyAutoimmune diseasesRheumatoid arthritisMedicine and health sciencesEndocrinologyEndocrine disordersDiabetes mellitusMedicine and health sciencesMetabolic disordersDiabetes mellitus + +Leveraging functional annotations in genetic risk prediction for human complex diseases +Leverage annotations in risk prediction + + + +http://orcid.org/0000-0002-0988-1030 + +Hu +Yiming + +1 + + +http://orcid.org/0000-0002-4514-0969 + +Lu +Qiongshi + +1 + + + +Powles +Ryan + +2 + + + +Yao +Xinwei + +3 + + + +Yang +Can + +4 + + + +Fang +Fang + +1 + + + +Xu +Xinran + +1 + + + +Zhao +Hongyu + +1 +2 +5 +6 +* + + + Department of Biostatistics, Yale School of Public Health, New Haven, CT, United States of America + Program of Computational Biology and Bioinformatics, Yale University, New Haven, CT, United States of America + Yale College, New Haven, CT, United States of America + Department of Mathematics, Hong Kong Baptist University, Kowloon, Hong Kong + Department of Genetics, Yale University School of Medicine, New Haven, CT, United States of America + Clinical Epidemiology Research Center (CERC), Veterans Affairs (VA) Cooperative Studies Program, VA Connecticut Healthcare System, West Haven, CT, United States of America + + + +Rigoutsos +Isidore + +Editor + + + +Thomas Jefferson University, UNITED STATES + + +

The authors have declared that no competing interests exist.

+
+ +

+

Conceptualization: YH QL HZ.

+

Data curation: CY.

+

Formal analysis: YH QL HZ.

+

Methodology: YH QL HZ.

+

Software: YH RP XY.

+

Validation: YH QL FF XX CY.

+

Writing – original draft: YH QL HZ.

+

+
+* E-mail: hongyu.zhao@yale.edu +
+ +8 +6 +2017 + + +6 +2017 + +13 +6 +e1005589 + + +21 +10 +2016 + + +19 +5 +2017 + + + +2017 +Hu et al + +This is an open access article distributed under the terms of the Creative Commons Attribution License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original author and source are credited. + + + + +

Genetic risk prediction is an important goal in human genetics research and precision medicine. Accurate prediction models will have great impacts on both disease prevention and early treatment strategies. Despite the identification of thousands of disease-associated genetic variants through genome wide association studies (GWAS), genetic risk prediction accuracy remains moderate for most diseases, which is largely due to the challenges in both identifying all the functionally relevant variants and accurately estimating their effect sizes in the presence of linkage disequilibrium. In this paper, we introduce AnnoPred, a principled framework that leverages diverse types of genomic and epigenomic functional annotations in genetic risk prediction for complex diseases. AnnoPred is trained using GWAS summary statistics in a Bayesian framework in which we explicitly model various functional annotations and allow for linkage disequilibrium estimated from reference genotype data. Compared with state-of-the-art risk prediction methods, AnnoPred achieves consistently improved prediction accuracy in both extensive simulations and real data.

+
+ +Author summary +

Genetic risk prediction plays a significant role in precision medicine. Accurate prediction models could have great impact on disease prevention and early treatment strategies. For example, mutations in BRCA1 and BRCA2 have been used to evaluate women’s breast cancer risk and as a guideline for early screening. However, genetic risk prediction models also present important challenges, including extreme high-dimensionality, limited access to and efficient computational methods for individual-level genotype data. To make use of rich GWAS summary statistics, we propose a novel method to address these challenges by integrating genomic functional annotations, which have been successfully applied in GWAS to generate biological insights. We demonstrate the improvement in accuracy in both extensive simulation studies and real data analysis of breast cancer, Crohn’s disease, celiac disease, rheumatoid arthritis and type-II diabetes.

+
+ + + + +http://dx.doi.org/10.13039/100000002 +National Institutes of Health + + +R01 GM59507 + + + +Cooperative Studies Program of the Department of Veterans Affair + + + + +Yale World Scholars Program + + +This study was supported in part by the National Institutes of Health (https://www.nih.gov/) grants R01 GM59507, the VA Cooperative Studies Program of the Department of Veterans Affairs, Office of Research and Development (http://www.research.va.gov/programs/csp/), and the Yale World Scholars Program (http://bbs.yale.edu/training/initiatives/csc.aspx) sponsored by the China Scholarship Council. The funders had no role in study design, data collection and analysis, decision to publish, or preparation of the manuscript. + + + + + + + + +PLOS Publication Stage +vor-update-to-uncorrected-proof + + +Publication Update +2017-06-22 + + +Data Availability +All the GWAS summary statistics are available online and can be accessed through: http://www.ibdgenetics.org, http://gameon.dfci.harvard.edu, http://www.broadinstitute.org/ftp/pub/rheumatoid_arthritis/Stahl_etal_2010NG/, http://diagram-consortium.org/downloads.html and https://www.immunobase.org/downloads/protected_data/GWAS_Data/. Individual level genotype data are available from dbGaP (accession numbers: phs000147, phs000383, phs000237 and phs000274) and WTCCC on EGA https://www.ebi.ac.uk/ega/ (accession numbers: EGAD00000000001, EGAD00000000002, EGAD00000000007 and EGAD00001000401). + + +
+
+ + +

This is a PLOS Computational Biology Methods paper.

+
+ +Introduction +

Achieving accurate disease risk prediction using genetic information is a major goal in human genetics research and precision medicine. Accurate prediction models will have great impacts on disease prevention and early treatment strategies [1]. Advancements in high-throughput genotyping technologies and imputation techniques have greatly accelerated discoveries in genome-wide association studies (GWAS) [2]. Various approaches that utilize genome-wide data in genetic risk prediction have been proposed, including machine-learning models trained on individual-level genotype and phenotype data [38], and polygenic risk scores (PRS) estimated using GWAS summary statistics [9, 10]. Despite the potential information loss in summary data, PRS-based approaches have been widely adopted in practice since the summary statistics for large-scale association studies are often easily accessible [11, 12] while individual-level data are more difficult to acquire, deposit, and process. However, prediction accuracies for most complex diseases remain moderate, which is largely due to the challenges in both identifying all the functionally relevant variants and accurately estimating their effect sizes in the presence of linkage disequilibrium (LD) [13].

+

Explicit modeling and incorporation of external information, e.g. pleiotropy [7, 8] and LD [10], has been shown to effectively improve risk prediction accuracy. Recent advancements in integrative genomic functional annotation, coupled with the rich collection of summary statistics from GWAS, have enabled increase of statistical power in several different settings [1416]. To our knowledge, the impact of functional annotations on performance of genetic risk prediction has not been systematically studied. Here, we introduce AnnoPred (available at https://github.com/yiminghu/AnnoPred), a principled framework that integrates GWAS summary statistics with various types of annotation data to improve risk prediction accuracy. We compare AnnoPred with state-of-the-art PRS-based approaches and demonstrate its consistent improvement in risk prediction performance using both simulations and real data of multiple complex diseases.

+

AnnoPred risk prediction framework has three main stages (Methods). First, we estimate GWAS signal enrichment in 61 different annotation categories, including functional genome predicted by GenoCanyon scores [17], GenoSkyline tissue-specific functionality scores of 7 tissue types [14], and 53 baseline annotations for diverse genomic features [18] for each trait analyzed. Second, we propose an empirical prior of SNP effect size based on annotation assignment and signal enrichment. In general, SNPs located in annotation categories that are highly enriched for GWAS signals receive a higher effect size prior. Finally, the empirical prior is adopted in a Bayesian framework in which marginal summary statistics and LD matrix estimated from a reference panel are jointly modeled to infer the posterior effect size of each SNP. AnnoPred PRS is defined by + + + + +PRS=j=1MXjEA(βj|β^,D^) + + + +where Xj and βj are the standardized genotype and effect size of the jth SNP, respectively, β^ is the marginal estimate of β, D^ is the sample LD matrix, and EA(βj|β^,D^) denotes the posterior expectation of effect sizes under an empirical prior based on annotation assignment for all SNPs when adjusting for LD matrix estimated from a reference panel (Methods).

+
+ +Results +

We first performed simulations to demonstrate AnnoPred’s ability to improve risk prediction accuracy. We compared AnnoPred with four popular PRS approaches (Methods), including PRS based on genome-wide significant SNPs (PRSsig), PRS based on all SNPs in the dataset (PRSall), PRS based on tuned cutoffs for p-values and LD pruning (PRSP+T), and recently proposed LDpred [10]. Mean correlations between simulated and predicted traits were calculated from 100 replicates under different simulation settings (Methods). AnnoPred showed the best prediction performance in all settings when the causal SNPs are highly enriched in annotated regions (Table 1, S2 Table and S2 Fig). In general, performance of PRSsig, PRSP+T, LDpred, and AnnoPred all improved under a sparser genetic model and higher trait heritability. PRSall showed comparable performance between sparse and polygenic models but its prediction accuracy was consistently worse than other methods. Sample size in the training set was also crucial for risk prediction accuracy. Increasing sample size could lead to continuous improvement in prediction accuracy under different settings (Fig 1).

+ +10.1371/journal.pcbi.1005589.g001 + + +Evaluating the effect of sample size on prediction accuracy in simulation. +

Traits were simulated using SNPs of chromosome 1, chromosome 1 and 2, chromosome 1 to 4 and the whole genome while keeping the same proportion of causal variants and heritability to mimic the situation of increasing sample size. In the figure, logNr = logNMMs, where N is the number of individuals, M is the total number of variants and Ms is the number of variants used in simulation. In total four settings were simulated for each effective sample size: h2 = 0.25, p = 0.001; h2 = 0.25, p = 0.01; h2 = 0.5, p = 0.001; h2 = 0.5, p = 0.01, where p represents the proportion of causal variants. Each dot represent the mean COR of 50 replicates in one simulation setting and error bar represents the standard error.

+ + +
+ +10.1371/journal.pcbi.1005589.t001 + Mean correlation between simulated and predicted traits calculated from 100 replicates under different simulation settings.

The highest mean correlations are highlighted in boldface. Standard deviations are shown in parentheses. Traits were simulated from WTCCC genotype data, which contain 15,918 individuals genotyped for 393,273 SNPs. In each setting, we used 70% of the data to calculate the training summary statistics and randomly divided the rest 30% into two parts for parameter tuning.

+ + + ++++++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Training samplesHeritability#CausalPRSsigPRSallPRSP+TLDpredAnnoPred
Half (~5K)0.253000.149(.028)0.08(.021)0.25(.028)0.279(.025)0.286(.024)
3000NA*0.082(.016)0.073(.020)0.087(.019)0.096(.020)
0.53000.304(.04)0.16(.022)0.48(.026)0.502(.033)0.512(.026)
3000NA*0.157(.019)0.157(.024)0.195(.021)0.209(.019)
Full (~10K)0.253000.217(.031)0.11(.02)0.332(.023)0.35(.033)0.358(.022)
3000NA*0.11(.014)0.107(.018)0.136(.017)0.145(.017)
0.53000.373(.036)0.213(.023)0.548(.024)0.557(.047)0.566(.034)
30000.078(.023)0.21(.019)0.243(.021)0.309(.021)0.324(.019)
+
+ +

* NA means no SNP achieves genome-wide significance level (5e-8).

+
+
+

To illustrate the improved risk prediction performance in real data, we applied AnnoPred to five human complex diseases—Crohn’s disease (CD), breast cancer (BC), rheumatoid arthritis (RA), type-II diabetes (T2D), and celiac disease (CEL). We first estimated GWAS signal enrichment in different annotation categories (Methods). Enrichment pattern varies greatly across diseases (Fig 2A; S1 Table), reflecting the genetic basis of these complex phenotypes. Functional genome predicted by GenoCanyon was consistently and significantly enriched for all five diseases. Blood was strongly enriched for three immune diseases, namely CD (P = 8.9×10−12), CEL (P = 7.0×10−15), and RA (P = 9.9×10−6), while gastrointestinal (GI) tract was enriched in CD (P = 2.6×10−5) and CEL (P = 1.4×10−4), both of which have a known GI component. For BC, epithelium (P = 7.4×10−4), GI (P = 5.9×10−3), and muscle (P = 6.1×10−3) were significantly enriched. A few studies have shown that breast cancer could arise from epithelial cells [19, 20]. The connections between breast cancer and muscle as well as GI tract have also been previously suggested [21, 22]. In addition, studies have suggested that GI can be used as diagnostic and treatment target for type-II diabetes, Crohn’s disease, and celiac disease [2325]. Furthermore, the connection between immune system and Crohn’s disease, celiac disease and rheumatoid arthritis have been extensively studied in literature [2628]. Next, we evaluated the effectiveness of proposed empirical effect size prior in three diseases (i.e. CD, CEL, and RA) with well-powered testing cohorts (N>2,000). Interestingly, despite the highly variable enrichment results in training datasets, integrative effect size prior could effectively identify SNPs with large effect sizes and consistent effect directions in independent validation cohorts (Fig 2B and 2C).

+ +10.1371/journal.pcbi.1005589.g002 + + +Evaluating effectiveness of annotations and empirical effect size prior. +

(A) GWAS signal enrichment across GenoCanyon and tissue-specific GenoSkyline annotations. The horizontal lines mark p-value cutoffs of 0.05 and Bonferroni corrected significance level. (B) Comparing signal strength of SNPs with high priors and low priors in independent validation cohorts. SNPs with higher priors have significantly stronger associations across three independent and well-powered testing datasets (N>2,000). P-values were calculated using one-sided Kolmogorov-Smirnov test. (C) Comparing consistency of SNPs’ effect direction between training and testing datasets. Each bar quantifies the proportion of SNPs with consistent effect directions. P-values were calculated using one-sided two-sample binomial test.

+ + +
+

Correlations between the calculated PRS and disease status (COR) for different approaches are summarized in Table 2. AnnoPred showed consistently improved prediction accuracy compared with all other methods across five diseases. Notably, PRSsig and PRSall showed suboptimal performance in these datasets, reaffirming the importance of modeling LD and other external information. A likelihood ratio test was used to test for the difference in the prediction accuracy between models comparing the likelihood of a logistic regression fitting PRS of one method to that of a logistic regression fitting PRS of two methods jointly (S11 Table). From the test, AnnoPred with 61 annotations performed significantly better than LDpred (p = 1.2E-22 for CD, p = 0.045 for BC, p = 4.2E-7 for RA, p = 3.3E-4 for T2D and p = 1.3E-3 for CEL). Reversing the order of test (that is, comparing the likelihood of model using annotations with model using and not using annotations jointly) results in non-significant p-values for most tests (S11 Table), which further demonstrates that PRS incorporating functional annotations mostly encompasses the information of PRS without annotations. To test different methods’ ability to stratify individuals with high risk, we compared the proportion of cases among testing samples with high PRS. AnnoPred outperformed all other methods in CD, CEL, RA, and T2D (S1 Fig). Next, we tested AnnoPred’s performance using only the 53 baseline annotations and observed a substantial drop in prediction accuracy for all diseases (S3 Table). AnnoPred with GenoCanyon and GenoSkyline annotations only (nine annotation tracks in total) yields better performance than the 53 baseline annotations (S10 Table). For CD and T2D, by using these 9 categories AnnoPred even achieved higher accuracy than the model with all 61 annotation tracks added. These results highlight the importance of annotation quality in genetic risk prediction, and also demonstrate GenoCanyon and GenoSkyline’s ability to accurately identify functionality in the human genome. Since different diseases have various enrichment patterns, we also run AnnoPred with significantly enriched annotations (enrichment test p value less than 0.05) for each disease (S10 Table). In general, using only the significantly enriched annotations indeed improved the performance in most diseases.

+ +10.1371/journal.pcbi.1005589.t002 + CORs of different methods.

The highest CORs are highlighted in boldface.

+ + + ++++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Disease/TraitPRSsigPRSallPRSP+TLDpredAnnoPred
Crohn's Disease0.270.2290.320.3250.343
Breast Cancer0.0840.0550.120.1220.137
Rheumatoid Arthritis0.2040.1140.2480.2820.287
Type-II Diabetes0.1650.1560.2040.2020.22
Celiac Disease0.110.1360.180.1970.213
+
+
+

Tissue specificity plays an important role in genetic risk prediction. Integrating more functional annotations with higher tissue and cell type specificity may further increase risk prediction accuracy, especially when the tissue type that is biologically relevant to the disease is not well characterized by the seven available tissue tracks in our current analyses. To explore how these factors will affect the AnnoPred model, we performed a few follow-up analyses. We have recently expanded our GenoSkyline annotations to more than 100 tissue and cell types from the Roadmap Epigenomics Project [29]. We investigated the performance of AnnoPred after integrating 66 annotation tracks representing a spectrum of adult tissue and cell types. As shown in S10 Table, incorporating more annotations into the model does not always further improve risk prediction accuracy compared with AnnoPred with fewer annotations in the model. This may be due to the overlap between functional regions (e.g. functional annotations for slightly different brain regions) when incorporating too many annotation tracks into the model, which will cause numerically unstable heritability estimates. This is because annotation-stratified LD score regression, the method we used to empirically estimate the informative prior for SNPs’ effect sizes, is a multiple linear regression model that regresses SNP-level summary statistics against annotation-stratified LD scores. When two functional annotation tracks are similar, the corresponding LD scores will also be correlated by definition. It is well understood that if multi-collinearity (i.e. correlation among covariates) in multiple regression leads to numerically unstable estimates for regression coefficients [30] (the heritability parameters in our case).

+

In order to study the effect of highly associated SNPs (e.g. SNPs in MHC regions for immune traits), we repeated the analysis on CD, RA, BC and T2D after removing the SNPs in MHC region (chr6: 28,477,797–33,448,354 bp). Re-analysis of CEL was unnecessary since the training summary statistics of CEL does not contain any SNP in the MHC region. After removing SNPs in MHC regions, the prediction accuracies for RA drops dramatically for all methods and AnnoPred remained to be the method with the best performance (S9 Table). For the rest diseases, results varied little from the original analysis. Besides COR, we also included AUCs for all the analysis performed (S2, S6, S9 and S10 Tables), all of which showed consistent patterns.

+

Due to distinct allele frequencies and LD structures across populations, risk prediction accuracy usually drops when the training and testing samples are from different populations. In order to investigate the robustness of AnnoPred against population heterogeneity, we applied AnnoPred to three non-European cohorts for breast cancer and type-II diabetes while training the model using summary statistics from European-based studies. The CORs and AUCs are summarized in S6 and S7 Tables. As expected, we observed a drop in prediction accuracy for all methods. However, AnnoPred still performed the best in all three trans-ethnic validation datasets.

+
+ +Discussion +

Our work demonstrates that functional annotations can effectively improve performance of genetic risk prediction. AnnoPred jointly analyzes diverse types of annotation data and GWAS summary statistics to upweight SNPs with a higher likelihood of functionality, which lead to consistently better prediction accuracy for multiple complex diseases. Our method is not without limitation. First, despite the consistent improvement compared with existing PRS-based methods, accuracies for most diseases remain moderate. In order to effectively stratify risk groups for clinical usage, our model remains to be further calibrated using large cohorts with measured environmental and clinical risk factors [1]. Second, accurate estimation of GWAS signal enrichment and SNP effect sizes requires a large sample size for the training dataset. This could potentially be improved by new estimators for annotation-stratified heritability [19]. A few Bayesian models combining GWAS summary statistics with functional annotations have been proposed for the purpose of fine-mapping functional variants [16, 20, 21]. Whether these models could be adapted to benefit risk prediction accuracy remains to be investigated in the future. Importantly, the rich collection of publicly available integrative annotation data, in conjunction with the increasing accessibility of GWAS summary statistics, makes AnnoPred a customizable and powerful tool. As GWAS sample size continues to grow, AnnoPred has the potential to achieve even better prediction accuracy and become widely adopted as a summary of genetic contribution in clinical applications of risk prediction.

+
+ +Methods + +Annotation data +

GenoCanyon is a statistical framework to predict functional regions in the human genome through integrative analysis of ENCODE epigenomic data and multiple conservation metrics [17]. Later we have further extended the model and developed GenoSkyline, which aimed to predict tissue-specific functionality [14]. In the AnnoPred model, we incorporated GenoCanyon general functionality scores, GenoSkyline tissue-specific functionality scores for seven tissue types (brain, gastrointestinal tract, lung, heart, blood, muscle, and epithelium), and 53 LDSC baseline annotations that covered a variety of genomic features [18] (S1 Table). We smoothed GenoCanyon scores by a 10Kb window, a strategy previously shown to improve robustness of functionality prediction [22]. The smoothed GenoCanyon annotation and raw GenoSkyline annotations of seven tissue types were dichotomized based on a cutoff of 0.5. The regions with GenoCanyon or GenoSkyline scores greater than the cutoff were interpreted as non-tissue-specific or tissue-specific functional regions in the human genome. Such dichotomization has been previously shown to be robust against the cutoff choice [14]. Notably, the AnnoPred framework allows users to specify their own choice of annotations.

+
+ +Heritability partition +

We assume throughout the paper that both the phenotype YN×1 and the genotypes XN×M are standardized with mean zero and variance one. We assume a linear model + + + + +YN×1=XN×MβM×1+εN×1 + + + +X, β and ε are mutually independent. We also assume that β is a random effect and effects of different SNPs are independent. A key idea in the AnnoPred framework is to utilize functional annotation information to accurately estimate SNPs’ effect sizes. In order to achieve that, we first partition trait heritability by annotations using LD score regression [18]. Since genotypes are standardized, per-SNP heritability is defined as the variance of βi for the ith SNP, and is used to quantify SNP effect sizes. More specifically, assume there are K + 1 pre-defined annotation categories, denoted as S0, S1, …, SK with S0 representing the entire genome. Under an additive assumption for heritability in overlapped annotations, we have βiN(0,j:iSjτj), where τ0, τ1, …, τK, quantify the contribution to per-SNP heritability from each annotation category. Denote the estimated marginal effect size of the ith SNP as β^i=XiTYN, then we have the following approximation + + + + +E(Nβ^i2)(N1)kτkl(i,k)+1 + + + +where l(i, k) is the annotation-stratified LD score and N denotes the total sample size. Regression coefficients τk are estimated through weighted least squares. The estimated heritability of the ith SNP is then Var^(βi)=j:iSjτ^j.

+
+ +Empirical prior of effect size +

Based on per-SNP heritability estimates, we propose two different priors for SNP effect sizes to add flexibility against different genetic architecture. For the first prior, we assume that SNP effect size follows a spike-and-slab distribution + + + + +βip0N(0,σ^i2p0)+(1p0)δ0 + + + +where p0 is the proportion of causal SNPs in the dataset, and δ0 is a Dirac function representing a point mass at zero. The empirical variance of each SNP, i.e. σ^i2, is determined by the annotation categories it falls in. More specifically, we assume σ^i2=c(j:iSjτ^j), where c is a constant calculated from the following equation + + + + +iσ^i2=H^2. + + +

+

We do not directly use j:iSjτ^j as the empirical variance prior because it is estimated in the context where all SNPs in the 1000 Genomes Project database are included in the model [18]. Such per-SNP heritability estimates cannot be extrapolated to the risk prediction context where many fewer SNPs are analyzed [23]. Therefore, we rescale the heritability estimates to better quantify each SNP’s contribution toward chip heritability. Following [24], we use a summary statistics-based heritability estimator that approximates the Haseman-Elston estimator: + + + + +H^2=(χ¯21)Nl + + + +where χ¯2 and l¯ denote the mean Nβ^i2 and mean non-stratified LD score, respectively.

+

In the first prior, we assumed the same proportion of causal SNPs but different effect sizes across annotation categories. We now describe the second prior that assumes different proportions of causal SNPs but the same effect size across annotation categories. To be specific, we assume the causal effect size to be Var(βcausal) = V, the total number of SNPs to be M0, and the overall proportion of causal SNPs to be p0. The total heritability H02 can then be written as H02=p0M0V. For the ith SNP, use Ti=(j:iSjSj)(k:iSkSkc) to denote the collection of SNPs that share the same annotation assignment with the ith SNP, and let MTi=|Ti|, i.e. the number of SNPs in the set. Then, the total heritability of SNPs in Ti is HTi2=pTiMTiV, with pTi denoting the proportion of causal SNPs in Ti. Following these notations, we have + + + + +βipTiN(0,V)+(1pTi)δ0 + + + +where V=H0p0N0 and pTi=p0M0HTi2MTiH02. We use H^2 to estimate H02, and the following formula to estimate HTi2.

+ + + + +H^Ti2=kTij:kSjτ^jk=1M0j:kSjτ^jH^2 + + + +

Finally, p0 is treated as a tuning parameter for both prior functions in our analysis.

+
+ +Calculation of posterior effect sizes +

By Bayes’ rule, the posterior distribution of β is: + + + + +f(β|β^,D^)f(β^|β,D^)f(β) + + + +where D^=1NXTX is the sample correlation matrix and β^=1NXTY is the marginal effect size estimates. Given β and D^, β^ follows a multivariate normal distribution asymptotically with the following mean and variance + + + + +E(β^|β,D^)=1N[E(XTXβ|β,D^)+E(XTε|β,D^)]=D^β + + + + + + + +Var(β^|β,D^)=Var(1NXTε|β,D^)=1N(1hg2)D^. + + +

+

However, D^ is usually non-invertible and has very high dimensions. We thus study the posterior distribution of a small chunk of β^ instead. Let β^b be the estimated marginal effect size of SNPs in a region b (e.g. a LD block) and the corresponding genotype matrix is Xb and sample correlation matrix is D^b. Then the conditional mean and variance of β^b are + + + + +E(β^b|βb,D^b)=1N[E(XbTXβ|βb,D^b)+E(XbTε|βb,D^b)]=D^bβb + + + + + + + +Var(β^b|βb,D^b)=1N2var(XbTXbβb+XbT(Xbβb+ε)|βb,D^b)=1N2var(XbT(Xbβb+ε)|βb,D^b)=1N2XbTvar(Xbβb+ε|βb,D^b)Xb=1N(1hb2)D^b + + + +where hb2=ibσi2 is the heritability of SNPs in region b, and Xb and βb denote the genotype matrix and effect sizes of SNPs not in region b. The conditional distribution of βb is: + + + + +f(βb|β^b,D^b)N(D^bβb,1N(1hb2)D^b)ibf(βi){N(D^bβb,1N(1hb2)D^b)ib[ p0N(0,σi2p0)+(1p0)δ0 ],underthefirstpriorN(D^bβb,1N(1hb2)D^b)ib[ pTiN(0,V)+(1pTi)δ0 ],underthesecondprior + + +

+

Although it is difficult to derive E(βb|β^b,D^b) from the joint conditional distribution of βb, each element of βb follows a mixed normal distribution conditioning on β^b, D^b, and all other elements in βb. Therefore, we apply a Gibbs sampler to draw samples from f(βb|β^b,D^b) and use the sample mean as an approximation for E(βb|β^b,D^b). We further performed a sensitivity analysis on the choice of the size of block b (S6 Fig). Specifically, we ran AnnoPred on the data of Crohn’s disease with different sizes of block and found that the results were robust to the sizes. In practice, the size of block b is specified by the total number of variants divided by 3,000.

+
+ +Calculation of PRS +

PRS is calculated using the following formula + + + + +PRS=j=1MXjEA(βj|β^,D^), + + + +where EA denotes the posterior expectation as described above. In practice, the individual-level genotype matrix is not available and we use the LD matrix estimated from a reference panel or the validation samples to substitute D^. We apply the same standard of choosing the size of b as described in [10]. Choices of prior and p0 can be tuned in an independent cohort. For the data analysis described in this work, we adopted a cross-validation scheme to select tuning parameter due to the challenge in finding multiple independent cohorts without overlapping with the training GWAS summary statistics. The training datasets in our real data analyses and simulations are always fixed, i.e. GWAS summary statistics. We did not perform a classical cross-validation by using different subsets of the complete data to train and test our prediction model. The purpose of cross-validation in our study is purely parameter tuning. To select a suitable tuning parameter, we divide the independent testing dataset (individual level genotype and phenotype data) into two equal parts (A and B), and select the tuning parameters by optimizing prediction accuracy on dataset A. We then evaluate prediction accuracy using the remaining half of testing data, i.e. dataset B. Finally, we repeat the analysis one more time by choosing the tuning parameter on dataset B while evaluating the prediction accuracy on dataset A. Results from these two separate analyses are averaged to quantify model performance. For T2D where multiple independent cohorts are available (phs000237 and phs000388), we used an independent cohort for parameter tuning and the other for evaluating performance (S12 Table). The results are consistent with the cross-validation.

+
+ +Comparison with existing methods +

We compared AnnoPred with several commonly used risk prediction methods based on summary data of association studies. PRSsig and PRSall were both calculated as the inner product of marginal effect size estimates and the corresponding genotypes. PRSall used all the SNPs that are shared between training and testing datasets while PRSsig only used SNPs with p-values below 5 × 10−8 in the training set. PRSP+T used SNPs passing both LD pruning and p-value thresholding. The thresholds are tuned in an independent dataset over a grid (0, 0.1, 0.2, … 0.9 for LD; 1, 0.3, 0.1, 0.03, 0.01, 3E-3, 1E-3, 3E-4, 1E-4, 3E-5, 1E-5, 1E-6, 1E-7, 5E-8, 1E-8 for p-value). LDpred can be viewed as a special case of AnnoPred, assuming the whole genome as the only functional annotation. This is because when enrichment is constant (i.e. causal variants are uniformly distributed across the genome), per-SNP heritability estimates would be nearly constant and therefore results in similar performance to LDpred. We have performed an additional simulation to demonstrate this using WTCCC genotype data with ~15K individuals and ~330K variants. We randomly divided the genome into two parts (two annotations) and uniformly selected causal SNPs. Then the traits were simulated in a similar way as other simulations in this paper. We estimated per-SNP heritability using LDSC in the two annotation categories, respectively. We ran the procedure for 100 times and the distributions of estimated per-SNP heritability in both regions are summarized in the figure below (the dashed line denotes the true per-SNP heritability, added as S4 Fig in the manuscript), which indicates that the per-SNP heritability estimates are uniform across the genome under constant enrichment. Therefore, AnnoPred would be mathematically equivalent with LDpred with enrichment is constant. We downloaded python code for PRSP+T and LDpred from Github (https://github.com/bvilhjal/ldpred). All the tuning parameters were tuned through cross-validation as we did for AnnoPred. Besides all these PRSs, we also compared AnnoPred with a evaluating method used in [5], which uses 1E-1, 1E-2,…, 1E-5 as p-value threshold to select SNPs and report the accuracy for the best performed threshold (S4 and S5 Tables).

+

Given that many large-scale GWAS summary statistics have included almost all available cohorts for a disease of interest, it is challenging to find independent datasets with individual-level genotype and phenotype information and sufficient sample sizes. We were able to identify ideal validation datasets for the five diseases we analyzed in this paper. The performance of different methods on more traits shall be evaluated when we get access to more data in the future.

+
+ +Simulation settings +

We simulated traits from WTCCC genotype data, which contain 15,918 individuals genotyped for 393,273 SNPs after filtering variants with missing rate above 1% and individuals with genetic relatedness above 0.05. We first generated two annotations and each annotation was simulated by randomly selecting 10% of the genome, denoted as A1 and A2, which we assume are known when applying AnnoPred. Denote the heritability of the trait as hg2 (25% or 50%) and the number of causal variants as m (300 or 3,000). Causal variants were generated as follows: m3 causal variants were selected from A1, m3 from A2 and the rest from (A1UA2)C corresponding to a high enrichment of signals in A1 and A2. Effect sizes of causal variants were sampled from N(0,hg2m). For each simulation, we used 70% of the data to calculate the training summary statistics and randomly divided the rest 30% into two parts for parameter tuning. We also randomly selected half of the training data to calculate summary statistics in order to study the effect of sample size on prediction accuracy.

+

In order to evaluate the improvement in accuracy, we performed a permutation test to compare the CORs of AnnoPred and LDpred. Suppose the CORs of LDpred and AnnoPred in simulations are x1, x2, …, xn and y1, y2, …, yn, respectively. And the hypothesis we want to test is + + + + +H0:μx=μyH1:μxμy + + + +where μx and μy represent the population mean of accuracies of LDpred and AnnoPred. We used |x¯y¯| as the test statistics and the p value can be calculated as p=Pr(|x¯y¯)>|x¯obsy¯obs||H0), in which x¯y¯ represents the random variable and x¯obsy¯obs represents the actually observed values. We used permutation to approximate the distribution of (x¯y¯) when H0 is true. Specifically, we first pooled xis and yis together. Then x˜1,x˜2,,x˜n and y˜1,y˜2,,y˜n were sampled from the pooled data for N = 106 times and we calculated (x˜¯y˜) for each x˜is and y˜is sampled, which formed the empirical distribution of (x¯y¯) under H0. And the p value could be approximated by p^=k=1NI{|x˜¯ky˜¯k|>|x¯obsy¯obs|}N, in which x˜¯ky˜¯k represents the sampled test statistic of the kth permutation.

+

To further study the effect of sample size on prediction performance, we simulated traits using SNPs of chromosome 1, chromosomes 1 and 2, chromosomes 1 to 4 and the whole genome while keeping the same proportion of causal variants and heritability to mimic the situation of increasing sample size. The corresponding relative sample sizes (NMMs, where N is the number of individuals, M is the total number of variants and Ms is the number of variants used in simulation) for the four scenarios are ~135K, ~67K, 37K and ~11K. For each effective sample size, we simulated traits under four settings: h2 = 0.25, p = 0.001; h2 = 0.25, p = 0.01; h2 = 0.5, p = 0.001; h2 = 0.5, p = 0.01, where p represents the proportion of causal variants (Fig 1).

+
+
+ +Ethics statement +

The study was approved by YALE UNIVERSITY HUMAN INVESTIGATION COMMITTEE with approval number 100 FR1 and 100 FR27.

+
+ +Data access + +GWAS summary statistics and validation data +

We trained AnnoPred using publicly accessible GWAS summary statistics and evaluated risk prediction performance using individual-level genotype and phenotype data from cohorts independent from the training samples. Only SNPs shared between training and testing datasets were kept in our analyses. Details for each training and testing dataset are provided in S1 Text and S8 Table.

+

For Crohn’s disease, we trained the model using summary statistics from International Inflammatory Bowel Disease Genetics Consortium (IIBDGC; Ncase = 6,333 and Ncontrol = 15,056) [25]. Samples from the Wellcome Trust Case Control Consortium (WTCCC) were removed from the meta-analysis and used as the validation dataset (Ncase = 1,689 and Ncontrol = 2,891) [26]. For breast cancer, we trained the model using summary statistics from Genetic Associations and Mechanisms in Oncology (GAME-ON) study (Ncase = 16,003 and Ncontrol = 41,335) [27], and tested the performance using samples from the Cancer Genetic Markers of Susceptibility (CGEMS) study (Ncase = 966 and Ncontrol = 70) [28]. Shared samples between CGEMS and GAME-ON were removed. We used samples from the CIDR-GWAS of breast cancer for trans-ethnic analysis (Ncase = 1,666 and Ncontrol = 2,038) [29]. For rheumatoid arthritis, we used summary statistics from a meta-analysis with 5,539 cases and 20,169 controls to train the model [30]. WTCCC samples were removed from the meta-analysis and used for validation (Ncase = 1,829 and Ncontrol = 2,892) [26]. For type-II diabetes, the training dataset is Diabetes Genetics Replication and Meta-analysis (DIAGRAM) consortium GWAS with 12,171 cases and 56,862 controls [31]. We used samples from Northwestern NUgene Project for validation (Ncase = 662 and Ncontrol = 517) [32]. Samples from Institute for Personalized Medicine (IPM) eMERGE project are used for trans-ethnic analysis (African American: Ncase = 517 and Ncontrol = 213; Hispanic: Ncase = 477 and Ncontrol = 102) [33]. The training dataset for celiac disease is from a GWAS with 4,533 cases and 10,750 controls [34]. Samples in the National Institute of Diabetes and Digestive and Kidney Diseases (NIDDK) celiac disease study were used for validation (Ncase = 1,716 and Ncontrol = 530) [35].

+
+ +Software availability +

AnnoPred software and source code are freely available online at https://github.com/yiminghu/AnnoPred.

+
+
+ +Supporting information + + + +Enrichment of proportion of cases in the top 5% testing samples with high PRS. +

(TIFF)

+ +
+ + + +Boxplots of the simulation results in <xref ref-type="table" rid="pcbi.1005589.t001">Table 1</xref>, p-values of the permutation tests (Methods) quantify the improvement of AnnoPred over PRS without incorporating functional annotations. +

(TIFF)

+ +
+ + + +Heritability enrichment across GenoCanyon and tissue-specific GenoSkyline annotations. +

The horizontal line marks no enrichment.

+

(TIFF)

+ +
+ + + +Per-SNP heritability estimation under constant enrichment in simulation. +

Dashed line marks the true per-SNP heritability.

+

(TIFF)

+ +
+ + + +Proportion of SNPs in GenoCanyon and tissue-specific GenoSkyline annotations. +

(TIFF)

+ +
+ + + +Prediction accuracy of AnnoPred on Crohn’s disease data using different LD radiuses. +

(TIFF)

+ +
+ + + +Comparing signal strength of SNPs with high priors and low priors in independent validation cohorts with underpowered sample size (<2000). +

(A) Breast cancer (B) Type-II diabetes (C) Comparing consistency of SNPs’ effect direction between training and testing datasets. Each bar quantifies the proportion of SNPs with consistent effect directions. The association tests and effect size estimation on the testing data are underpowered due to the limited sample size.

+

(TIFF)

+ +
+ + + +GWAS signal enrichment across 61 annotation categories. +

(XLSX)

+ +
+ + + +AUCs of different methods. +

The highest AUCs are highlighted in boldface.

+

(XLSX)

+ +
+ + + +Comparison of the complete model and AnnoPred with baseline annotations. +

The highest AUCs are highlighted in boldface.

+

(XLSX)

+ +
+ + + +Comparison of the AnnoPred with method used in (Speed and Balding 2014) for evaluation in real data analysis. +

The highest AUCs are highlighted in boldface.

+

(XLSX)

+ +
+ + + +Comparison of the AnnoPred with method used in (Speed and Balding 2014) for evaluation in simulation. +

The highest correlations are highlighted in boldface.

+

(XLSX)

+ +
+ + + +AUCs for trans-ethnic analyses. +

The highest AUCs are highlighted in boldface.

+

(XLSX)

+ +
+ + + +CORs for trans-ethnic analyses. +

The highest CORs are highlighted in boldface.

+

(XLSX)

+ +
+ + + +URLs for training and testing datasets. +

(XLSX)

+ +
+ + + +Prediction accuracies after removing SNPs in MHC regions. +

The highest CORs/AUCs are highlighted in boldface.

+

(XLSX)

+ +
+ + + +Prediction accuracies of AnnoPred when different annotations used. +

The highest CORs/AUCs are highlighted in boldface.

+

(XLSX)

+ +
+ + + +p-values from the likelihood ratio tests comparing different models. +

(XLSX)

+ +
+ + + +Prediction accuracies on T2D when tuning the parameter in an independent cohort. +

(XLSX)

+ +
+ + + +Details on GWAS summary statistics and validation data. +

(DOCX)

+ +
+
+ + + +

We sincerely thank DIAGRAM, GAME-ON, IIBDGC, and ImmunoBase for making their GWAS summary data publicly accessible. This study makes use of data generated by the Wellcome Trust Case-Control Consortium. A full list of the investigators who contributed to the generation of the data is available from www.wtccc.org.uk. Funding for the project was provided by the Wellcome Trust under award 076113, 085475 and 090355. We also thank Dr. Bjarni J. Vilhjálmsson for sharing his codes. And finally we thank Jina Li for her insightful suggestions and support.

+
+ +References +Chatterjee N, Shi J, Garcia-Closas M. Developing and evaluating polygenic risk prediction models for stratified disease prevention. Nat Rev Genet. 2016;advance online publication. doi: 10.1038/nrg.2016.27 27140283 +McCarthy MI, Abecasis GR, Cardon LR, Goldstein DB, Little J, Ioannidis JP, et al. Genome-wide association studies for complex traits: consensus, uncertainty and challenges. Nature reviews genetics. 2008;9(5):35669. doi: 10.1038/nrg2344 18398418 +Wei Z, Wang W, Bradfield J, Li J, Cardinale C, Frackelton E, et al. Large sample size, wide variant spectrum, and advanced machine-learning technique boost risk prediction for inflammatory bowel disease. The American Journal of Human Genetics. 2013;92(6):100812. doi: 10.1016/j.ajhg.2013.05.002 23731541 +Zhou X, Carbonetto P, Stephens M. Polygenic modeling with Bayesian sparse linear mixed models. PLoS Genet. 2013;9(2):e1003264. doi: 10.1371/journal.pgen.1003264 23408905 +Speed D, Balding DJ. MultiBLUP: improved SNP-based prediction for complex traits. Genome research. 2014;24(9):15507. doi: 10.1101/gr.169375.113 24963154 +Minnier J, Yuan M, Liu JS, Cai T. Risk classification with an adaptive naive bayes kernel machine model. Journal of the American Statistical Association. 2015;110(509):393404. doi: 10.1080/01621459.2014.908778 26236061 +Li C, Yang C, Gelernter J, Zhao H. Improving genetic risk prediction by leveraging pleiotropy. Human genetics. 2014;133(5):63950. doi: 10.1007/s00439-013-1401-5 24337655 +Maier R, Moser G, Chen G-B, Ripke S, Coryell W, Potash JB, et al. Joint analysis of psychiatric disorders increases accuracy of risk prediction for schizophrenia, bipolar disorder, and major depressive disorder. The American Journal of Human Genetics. 2015;96(2):28394. doi: 10.1016/j.ajhg.2014.12.006 25640677 +Purcell SM, Wray NR, Stone JL, Visscher PM, O'Donovan MC, Sullivan PF, et al. Common polygenic variation contributes to risk of schizophrenia and bipolar disorder. Nature. 2009;460(7256):74852. doi: 10.1038/nature08185 19571811 +Vilhjálmsson BJ, Yang J, Finucane HK, Gusev A, Lindström S, Ripke S, et al. Modeling linkage disequilibrium increases accuracy of polygenic risk scores. The American Journal of Human Genetics. 2015;97(4):57692. doi: 10.1016/j.ajhg.2015.09.001 26430803 +Mavaddat N, Pharoah PD, Michailidou K, Tyrer J, Brook MN, Bolla MK, et al. Prediction of breast cancer risk based on profiling with common genetic variants. Journal of the National Cancer Institute. 2015;107(5):djv036. +Ripke S, Neale BM, Corvin A, Walters JT, Farh K-H, Holmans PA, et al. Biological insights from 108 schizophrenia-associated genetic loci. Nature. 2014;511(7510):421. doi: 10.1038/nature13595 25056061 +Schrodi SJ, Mukherjee S, Shan Y, Tromp G, Sninsky JJ, Callear AP, et al. Genetic-based prediction of disease traits: prediction is very difficult, especially about the future. Front Genet. 2014;5(162):118. +Lu Q, Powles RL, Wang Q, He BJ, Zhao H. Integrative Tissue-Specific Functional Annotations in the Human Genome Provide Novel Insights on Many Complex Traits and Improve Signal Prioritization in Genome Wide Association Studies. PLoS Genet. 2016;12(4):e1005947. doi: 10.1371/journal.pgen.1005947 27058395 +Gusev A, Lee SH, Trynka G, Finucane H, Vilhjálmsson BJ, Xu H, et al. Partitioning heritability of regulatory and cell-type-specific variants across 11 common diseases. The American Journal of Human Genetics. 2014;95(5):53552. doi: 10.1016/j.ajhg.2014.10.004 25439723 +Pickrell JK. Joint analysis of functional genomic data and genome-wide association studies of 18 human traits. The American Journal of Human Genetics. 2014;94(4):55973. doi: 10.1016/j.ajhg.2014.03.004 24702953 +Lu Q, Hu Y, Sun J, Cheng Y, Cheung K-H, Zhao H. A Statistical Framework to Predict Functional Non-Coding Regions in the Human Genome Through Integrated Analysis of Annotation Data. Sci Rep. 2015;5. doi: 10.1038/srep10576 26015273 +Finucane HK, Bulik-Sullivan B, Gusev A, Trynka G, Reshef Y, Loh P-R, et al. Partitioning heritability by functional annotation using genome-wide association summary statistics. Nature Genetics. 2015. +Zhou X. A Unified Framework for Variance Component Estimation with Summary Statistics in Genome-wide Association Studies. bioRxiv. 2016:042846. +Kichaev G, Pasaniuc B. Leveraging functional-annotation data in trans-ethnic fine-mapping studies. The American Journal of Human Genetics. 2015;97(2):26071. doi: 10.1016/j.ajhg.2015.06.007 26189819 +Li Y, Kellis M. Joint Bayesian inference of risk variants and tissue-specific epigenomic enrichments across multiple complex human diseases. Nucleic Acids Research. 2016:gkw627. +Lu Q, Yao X, Hu Y, Zhao H. GenoWAP: GWAS signal prioritization through integrated analysis of genomic functional annotation. Bioinformatics. 2016;32(4):5428. doi: 10.1093/bioinformatics/btv610 26504140 +Yang J, Lee SH, Wray NR, Goddard ME, Visscher PM. Commentary on "Limitations of GCTA as a solution to the missing heritability problem". bioRxiv. 2016. doi: 10.1101/036574. +Bulik-Sullivan B. Relationship between LD Score and Haseman-Elston Regression. bioRxiv. 2015. doi: 10.1101/018283. +Franke A, McGovern DP, Barrett JC, Wang K, Radford-Smith GL, Ahmad T, et al. Genome-wide meta-analysis increases to 71 the number of confirmed Crohn's disease susceptibility loci. Nat Genet. 2010;42(12):111825. doi: 10.1038/ng.717 21102463; PubMed Central PMCID: PMCPMC3299551. +Burton PR, Clayton DG, Cardon LR, Craddock N, Deloukas P, Duncanson A, et al. Genome-wide association study of 14,000 cases of seven common diseases and 3,000 shared controls. Nature. 2007;447(7145):66178. doi: 10.1038/nature05911 17554300 +Michailidou K, Hall P, Gonzalez-Neira A, Ghoussaini M, Dennis J, Milne RL, et al. Large-scale genotyping identifies 41 new loci associated with breast cancer risk. Nature genetics. 2013;45(4):35361. doi: 10.1038/ng.2563 23535729 +Hunter DJ, Kraft P, Jacobs KB, Cox DG, Yeager M, Hankinson SE, et al. A genome-wide association study identifies alleles in FGFR2 associated with risk of sporadic postmenopausal breast cancer. Nature genetics. 2007;39(7):8704. doi: 10.1038/ng2075 17529973 +Zheng Y, Ogundiran TO, Falusi AG, Nathanson KL, John EM, Hennis AJ, et al. Fine mapping of breast cancer genome-wide association studies loci in women of African ancestry identifies novel susceptibility markers. Carcinogenesis. 2013:bgt090. +Stahl EA, Raychaudhuri S, Remmers EF, Xie G, Eyre S, Thomson BP, et al. Genome-wide association study meta-analysis identifies seven new rheumatoid arthritis risk loci. Nature genetics. 2010;42(6):50814. doi: 10.1038/ng.582 20453842 +Morris AP, Voight BF, Teslovich TM, Ferreira T, Segre AV, Steinthorsdottir V, et al. Large-scale association analysis provides insights into the genetic architecture and pathophysiology of type 2 diabetes. Nature genetics. 2012;44(9):981. doi: 10.1038/ng.2383 22885922 +McCarty CA, Chisholm RL, Chute CG, Kullo IJ, Jarvik GP, Larson EB, et al. The eMERGE Network: a consortium of biorepositories linked to electronic medical records data for conducting genomic studies. BMC medical genomics. 2011;4(1):13. +Tayo BO, Teil M, Tong L, Qin H, Khitrov G, Zhang W, et al. Genetic background of patients from a university medical center in Manhattan: implications for personalized medicine. PLoS One. 2011;6(5):e19166. doi: 10.1371/journal.pone.0019166 21573225; PubMed Central PMCID: PMCPMC3087725. +Dubois PC, Trynka G, Franke L, Hunt KA, Romanos J, Curtotti A, et al. Multiple common variants for celiac disease influencing immune gene expression. Nature genetics. 2010;42(4):295302. doi: 10.1038/ng.543 20190752 +Garner C, Ahn R, Ding YC, Steele L, Stoven S, Green PH, et al. Genome-wide association study of celiac disease in North America confirms FRMD4B as new celiac locus. PLoS One. 2014;9(7):e101428. Epub 2014/07/08. doi: 10.1371/journal.pone.0101428 24999842; PubMed Central PMCID: PMCPmc4084811. + +
+
\ No newline at end of file diff --git a/xml/math/manuscript_933c4c.xml b/xml/math/manuscript_933c4c.xml new file mode 100644 index 0000000..061cd78 --- /dev/null +++ b/xml/math/manuscript_933c4c.xml @@ -0,0 +1,729 @@ + + +
+ + + + + Research Article + Computational and Systems Biology + Artículo de investigación + Biología computacional y de sistemas + + + + Kitchen Sink + A word processor for structured content + + + + + Doe + John + + john.doe@university + + + + + + Mustermann + Hansjörg + + + + + + + + The Mouse Genome Sequencing Consortium + mouse-project@example.com + + + + + + Kelly + Laura A. + + + + + + Randall + Daniel Lee + Jr. + + Dan Randall + +

This is a bio example.

+

With multiparagraphs.

+
+ +
+
+
+
+
+ + + + Kastner + Sabine + + + + + + German Primate Center GmbH + Neurobiology Laboratory + Göttingen + Germany + + + The Rockefeller University + Laboratory of Neural Systems + New York + United States + + + University of Göttingen + Department of Biology + Göttingen + Germany + + + Princeton University + Princeton + United States + + + The Rockefeller University + Another Laboratory + New York + United States + + + 29 + 01 + 1999 + + 318 + 7187 + Des zones d’incertitudes en traduction + 837 + 841 + 837-841 + + + 06 + 06 + 1998 + + + 05 + 01 + 1998 + + + 24 + 05 + 1998 + + + 14 + 03 + 1998 + + + + © 2018 Substance Consortium + 2018 + Substance Consortium + + http://creativecommons.org/licenses/by/4.0/ + This is an open access article distributed under the terms of the Creative Commons Attribution License, which permits unrestricted use, distribution, reproduction and adaptation in any medium and for any purpose provided that it is properly attributed. For attribution, the original author(s), title, publication source (PeerJ) and either DOI or URL of the article must be cited. + + + +

Please note, this article uses content from different open access articles (eLife) for demoing purposes.

+
+ + eLife Digest +

This is an example of executive summary with sub sections.

+ + Custom abstract sub section +

Sub section content.

+
+
+ +

This is an example of web summary.

+
+ + optogenetics + two-photon + calcium imaging + Mouse + nada + si + + + + + + https://dx.doi.org/10.13039/100000011 + Howard Hughes Medical Institute + + + F32 GM089018 + + +
+
+ + + Inline content +

Lorem [1] ipsum [2] dolor sit amet. Formatting bold,italic, sub,sup, monospace, small caps, underline, overline, strike through.

+

Formatting content inside a link: italic,bold. Link inside of formatting: this is an italic link facilisis diam nec neque accumsan, reference to a table Table 1.

+

The Dow Jones Industrial Average for February 7, 2006 .

+

Math as part of the text . You can also set a reference to block formula, like this: (1).

+
+ + Block level content + +

Curabitur vehicula mattis sodales. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

+
+ + + + + + + +

Item 1

+ + +

Item 2

+
+ +

Item 3

+
+
+
+ +

Item 4

+ + +

Item 5

+
+ +

Item 6

+ + +

Item 7

+
+ +

Item 8

+
+
+
+
+
+ +

Item 9

+
+
+ + + + + + Tables + + + + Example Table +

This is a table example.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ABCD
13
5Formatting in table cell bold,italic, sub,sup, monospace
9Hyper link in table cell.Reference citation in table cell [1]
Table footnote*Another table footnoteTable footnote with multiple targets*, †16
+ + + + +

This is a table-footnote.

+
+ + +

Another table-footnote.

+
+
+
+
+
+ + Figures +

Reference to simple figure Figure 1. Reference to footnote 1. Citation with two references [1,2].

+ + + + Figure with permissions. +

Legend.

+ + + + © 2014 Surname et al. + 2014 + Surname et al. + + http://creativecommons.org/licenses/by/4.0/ + License text. + + +
+

Lorem ipsum.

+ + + + + First panel +

First panel legend

+ + +
+ + + + Second panel +

Second panel caption

+ + +
+
+

abc

+ + + + Figure with metadata. +

Legend.

+ + + + Value A + Value B + + + + Value C + + +
+
+ + Supplementary Files + + + +

Description of Supplementary File

+ +
+ + + +

A remote file

+ +
+
+
+ + Sections and Subsections + + Section Level 2 + + Section Level 3 + + + + Section heading with <break id="br1"/>Line-Break + + + + + + + +

This is the first footnote.

+
+ +

This. is the second footnote.

+
+
+ + + + 2017 + 10.1101/102392 + + + Alasoo + K + + + Rodrigues + J + + + Mukhopadhyay + S + + + Knights + AJ + + + Mann + AL + + + Kundu + K + + + HIPSCI Consortium + + + Hale + C + + + Dougan + G + + + Gaffney + DJ + + + bioRxiv + Shared genetic effects on chromatin and gene expression reveal widespread enhancer priming in immune response + + + + + 2016 + GSE69545 + + + Allison + KA + + + Glass + CK + + + NCBI Gene Expression Omnibus + Affinity and Dose of TCR Engagement Yield Proportional Enhancer and Gene Activity in CD4+ T Cells + + + + + 1141 + 1144 + 282 + 1998 + 10.1126/science.282.5391.1141 + 9804555 + + + Baukrowitz + T + + + Schulte + U + + + Oliver + D + + + Herlitze + S + + + Krauter + T + + + Tucker + SJ + + + Ruppersberg + JP + + + Fakler + B + + + Science + PIP2 and PIP as determinants for ATP inhibition of KATP channels + + + + + New York + Oxford University Press + 2006 + 978-0195301069 + 10.1093/acprof:oso/9780195301069.001.0001 + + + Buzsaki + G + + + Rhythms of the Brain + + + + + 180 + 207 + Sunderland, MA + Sinauer Associates + 1989 + 978-0878936588 + + + Coyne + JA + + + Orr + HA + + + + + Otte + D + + + Endler + JA + + + Speciation and its consequences + Two rules of speciation + + + + + 36 + 38 + Fall 2017 + 2017 + + + Craig + DJ + + + Columbia Magazine + A voice for women and girls + + + + + http://www.michaeleisen.org/blog/?p=1894 + 2016 + + + Eisen + M + + + it is NOT junk + The Imprinter of All Maladies + + + + + Proceedings of the 17th Annual Meeting of International Society for Magnetic Resonance in Medicine + Hawaii, United States + 2009 + + + Leemans + A + + + Jeurissen + B + + + Sijbers + J + + + Jones + D + + + ExploreDTI: a graphical toolbox for processing, analyzing, and visualizing diffusion MR data + + + + + Monrovia, Liberia + NMCP, LISGIS, and ICF International + 2012 + + + National Malaria Control Program - Ministry of Health and Social Welfare + + + Liberia Institute of Statistics and Geo-Information Services + + + ICF International + + + + + United States Agency for International Development + + + President’s Malaria Initiative + + + Liberia Malaria Indicator Survey 2011 + + + + + US20100941530 + 2011 + + + Patterson + JB + + + Lonergan + DG + + + Flynn + GA + + + Qingpeng + Z + + + Pallai + PV + + + United States patent + IRE-1alpha inhibitors + + + + + 27 + International Edition + 21 + 4 + Film + 2018 + + + Rose + Steve + + + The Guardian + What if superheroes aren’t really the good guys? + + + + + Nijmegen, The Netherlands + Radboud University Nijmegen Medical Centre + 2006 + + + Schneider + P + + + PhD thesis: Submicroscopic Plasmodium falciparum gametocytaemia and the contribution to malaria transmission + + + + + Zenodo + 2.0.1 + 2018 + 10.5281/zenodo.1203712 + + + Willner + Sven + + + Gieseke + Robert + + + pyhector + + + +
+
\ No newline at end of file