# RelativisticPy
**RelativisticPy reads mathematics as it is written, in LaTeX, plain text or Unicode,
and computes it.** Its core is algebra, calculus, linear algebra and index notation over
any space. Probability, signals, optimisation, number theory, quantum mechanics and
General Relativity are read in the notation of their books. It is for people, in Python,
at the command line and in notebooks, and for AI agents, as a tool.
> **For:** everyone. **You will learn:** what RelativisticPy is, and where to start for
> what you want to do.
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook()
>>> wb.expr(r"\int_0^\infty x^2 e^{-x} \, dx")
2
>>> wb.expr("d/dx sin(x)^2")
2*sin(x)*cos(x)
>>> wb.expr("∑_{n=1}^∞ 1/n²")
pi**2/6
>>> wb.expr(r"\det \begin{pmatrix} 2 & 1 \\ 1 & 3 \end{pmatrix}")
5
>>> wb.exe(r"X \sim \mathcal{N}(0, 1)")
[]
>>> wb.expr(r"\Pr(X > 1)")
1/2 - erf(sqrt(2)/2)/2
>>> wb.expr(r"ds^2 = -\left(1 - \frac{2M}{r}\right) dt^2 + \frac{dr^2}{1 - \frac{2M}{r}} + r^2 d\Omega^2")
>>> wb.expr(r"R_{abcd} R^{abcd}")
48*M**2/r**6
```
## Why
Computer algebra asks you to translate mathematics into its own functions first:
`integrate(x**2*exp(-x), (x, 0, oo))` for \(\int_0^\infty x^2 e^{-x}\,dx\).
RelativisticPy reads the notation itself, as books, papers and people write it, so an
equation copied from a paper runs as it is, and a whole paper can be
[checked](checking.md), equation by equation. Index notation never needed spacetime: an
index can range over coordinates, assets, days or the states of a qubit.
Notation is ambiguous, and a wrong answer is worse than none. Where RelativisticPy
assumes what a book would, a note says so. What it cannot read or decide, it refuses,
saying why and what to write instead. A wrong answer given without a word is a bug, and
the [roadmap](roadmap.md) says which are known.
## Where to start
Install it and run a first program in [Getting started](getting-started.md). Then,
by what you want to do:
| I want to | Read, in order |
|---|---|
| compute: algebra, calculus, matrices, probability and more | [The language](language.md), the page of [each field](language.md#fields), [LaTeX](latex.md) |
| give an AI agent mathematics to do | [MCP server, for agents](mcp.md), [the language reference](reference.md) |
| study General Relativity | [Tensors and geometry](tensors.md), [Solving tensor equations](notation.md), [Numerics](numerics.md) |
| check a paper | [LaTeX](latex.md), [Checking papers](checking.md) |
| compute with data | [Beyond spacetime](spaces.md), [Python API](python.md) |
| know the language | [The language](language.md), [the language reference](reference.md), [Glossary](glossary.md) |
| work in Jupyter or marimo | [Jupyter and notebooks](jupyter.md), [Live mathematics in notebooks](live.md), [Examples](examples.md) |
| move from another tool | [Coming from other tools](coming-from.md), [Coming from 1.x](upgrading.md) |
| know how it works | [How it works](architecture.md), [Roadmap](roadmap.md) |
When a result surprises you, see [Troubleshooting](troubleshooting.md).
## For agents
`relativisticpy mcp` serves RelativisticPy to an agent over the Model Context Protocol:
tools to compute, to verify a step and to check a paper ([MCP server](mcp.md)). Each value
says whether it is a complete answer, and a refusal says why.
Everything here is in the installed package too: `relativisticpy help` lists the
pages, `relativisticpy help reference` prints the whole language on one page, and
`relativisticpy help NAME` one function in full, as `relativisticpy help besselj`. The
site serves [llms.txt](https://relativisticpy.org/llms.txt), an index of these pages for
language models, and [llms-full.txt](https://relativisticpy.org/llms-full.txt), all of
them in one file.
# Getting started
> **For:** everyone, first. **You will learn:** how to install RelativisticPy, run a
> workbook from Python, and run a program, a notebook and a check from the command line.
## Install
RelativisticPy needs Python 3.10 or newer. PyPI still serves the releases of an earlier
implementation, 1.1.9 to 1.2.9, which pip would choose; until they are withdrawn there,
install it from GitHub:
```bash
pip install "relativisticpy @ git+https://github.com/cottrellashley/relativisticpy"
```
Its only dependency is [SymPy](https://www.sympy.org), which does the algebra. Extras
add what numerical work needs:
| Extra | Adds | For |
|---|---|---|
| `numeric` | NumPy and SciPy | numbers, NumPy functions and geodesics: [Numerics](numerics.md) |
| `data` | NumPy, SciPy, pandas and scikit-learn | data in index notation: [Beyond spacetime](spaces.md) |
| `jax` | NumPy, SciPy and JAX | computing with JAX, on a GPU, and gradients |
| `mcp` | the MCP SDK | serving RelativisticPy to AI agents, `relativisticpy mcp`: [MCP server](mcp.md) |
| `live` | anywidget | the editor, which computes as you type: [Live mathematics in notebooks](live.md) |
```bash
pip install "relativisticpy[data] @ git+https://github.com/cottrellashley/relativisticpy"
```
## Raw strings
> **Write LaTeX in Python in raw strings:** `r"\frac{1}{2}"`, not `"\frac{1}{2}"`. In an
> ordinary string, Python turns `\a`, `\b`, `\f`, `\n`, `\r`, `\t` and `\v` into control
> characters before RelativisticPy sees them, so `"\theta"` arrives as a tab and `heta`.
> RelativisticPy refuses such text, and says to write a raw string.
## Your first workbook
A `Workbook` is a session, like a notebook: definitions persist from one call to the
next. `expr` runs a program and returns the value of its last expression; `exe` returns
the value of every expression.
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook()
>>> wb.exe(r"""
... f(x) := x^2 e^{-x}
... f'(x)
... \int_0^\infty f(x) \, dx
... """)
[(-x**2 + 2*x)*exp(-x), 2]
```
Plain text and Unicode say the same, and mix with LaTeX:
```python
>>> wb.expr("integrate(f(x), (x, 0, oo))"), wb.expr("∫_0^∞ f(x) dx")
(2, 2)
```
`:=` defines. `=` defines too, but only what has no meaning yet: with f defined,
`f(1) = e^{-1}` is a claim, and is decided:
```python
>>> wb.expr("f(1) = e^{-1}"), wb.expr("f(1) = 1")
(True, False)
```
Results come back as SymPy values. [The language](language.md) has the rest, and each
field has a page, in the notation of its books: [matrices](matrices.md),
[vectors](vectors.md), [random variables](probability.md), [optima](optima.md),
[number theory and sequences](discrete.md) and [quantum notation](quantum.md).
## Tensors
Index notation computes over any space. Over spacetime, with a metric, it is General
Relativity:
```python
>>> wb = Workbook()
>>> wb.expr(r"""
... Coordinates := [t, r, \theta, \phi]
... g_{\mu\nu} := diag(-(1 - 2M/r), 1/(1 - 2M/r), r^2, r^2 \sin^2\theta)
... """)
>>> wb.exe(r"""
... R
... R_{abcd} R^{abcd}
... """)
[0, 48*M**2/r**6]
```
With a metric in force, `R = 0` asks whether the Ricci scalar vanishes, and says so.
Tensors come back as [`Tensor`](python.md#tensor) values, which know their indices and
coordinates:
```python
>>> christoffel = wb.expr(r"\Gamma^{a}_{bc}")
>>> christoffel.indices
Indices('^{a}_{bc}')
>>> christoffel.nonzero()[("theta", "phi", "phi")]
-sin(theta)*cos(theta)
```
Mistakes come back as errors that point at the source:
```python
>>> wb.expr(r"R^{a}_{bc}")
Traceback (most recent call last):
...
relativisticpy.errors.IndexNotationError: R has 2 or 4 indices, but 3 are given
--> :1:1
|
1 | R^{a}_{bc}
| ^^^^^^^^^^
```
## A program
A program is a text file, by convention ending in `.relpy`. Write one:
```bash
cat > schwarzschild.relpy <<'EOF'
g_{\mu\nu} := Schwarzschild(M)
\Gamma^{r}_{tt}
R_{abcd} R^{abcd}
EOF
```
`relativisticpy schwarzschild.relpy` runs it and prints each result. From Python,
`Workbook().run_file("schwarzschild.relpy")` runs the file, and `exe` the same program
given as text:
```python
>>> Workbook().exe(r"""
... g_{\mu\nu} := Schwarzschild(M)
... \Gamma^{r}_{tt}
... R_{abcd} R^{abcd}
... """)
[M*(-2*M + r)/r**3, 48*M**2/r**6]
```
The command does more:
```bash
relativisticpy -c '\int_0^1 x^2 \, dx' # run code given on the command line
relativisticpy --latex schwarzschild.relpy # print the results as LaTeX
relativisticpy -j 8 schwarzschild.relpy # share component-wise work among 8 processes
relativisticpy # an interactive prompt, where definitions persist
relativisticpy --help # every option
```
## A notebook
A Markdown file whose equations are in displays, `$$ ... $$`, is a notebook: GitHub
typesets it, and RelativisticPy runs its displays in order, as one program.
```bash
cat > sphere.md <<'EOF'
# The 2-sphere
A sphere of radius $a$:
$$
ds^2 = a^2 \left(d\theta^2 + \sin^2\theta\, d\phi^2\right)
$$
Its Ricci scalar:
$$
R
$$
EOF
relativisticpy sphere.md # print the results
relativisticpy sphere.md --render # print the document, with each result typeset under its display
```
[Jupyter and notebooks](jupyter.md) says more, and the [examples](examples.md) are
notebooks of this kind.
## A check
`relativisticpy check` runs the display equations of a LaTeX document, or a notebook, in
order, as a reader would, and gives each a verdict: which hold, which differ, which
define something, and which it could not read.
```bash
cat > sphere.tex <<'EOF'
\begin{equation} ds^2 = a^2 (d\theta^2 + \sin^2\theta\, d\phi^2) \end{equation}
The sphere is curved: \begin{equation} R = \frac{2}{a^2} \end{equation}
and not by half as much: \begin{equation} R = \frac{1}{a^2} \end{equation}
EOF
relativisticpy check sphere.tex
```
From Python, `wb.check` takes a file, or the text of a document:
```python
>>> report = Workbook().check(r"""
... \begin{equation} ds^2 = a^2 (d\theta^2 + \sin^2\theta\, d\phi^2) \end{equation}
... The sphere is curved: \begin{equation} R = \frac{2}{a^2} \end{equation}
... and not by half as much: \begin{equation} R = \frac{1}{a^2} \end{equation}
... """)
>>> [(finding.line, finding.verdict) for finding in report]
[(2, 'defines'), (3, 'holds'), (4, 'differs')]
```
[Checking papers](checking.md) explains every verdict.
## Where next
- [The language](language.md): statements, `:=` and `=`, functions, equations and
calculus, with a page for each field; and the [language reference](reference.md), all
of it on one page.
- [The MCP server](mcp.md), to give the language to an AI agent.
- [Tensors and geometry](tensors.md), for General Relativity.
- [Beyond spacetime](spaces.md), for data.
- [Checking papers](checking.md), for LaTeX documents.
- [Troubleshooting](troubleshooting.md), when a result surprises you.
Offline, `relativisticpy help` lists these pages and prints any of them.
# The language
> **For:** everyone who writes RelativisticPy, whatever the field. **You will learn:**
> statements, names, what `:=` and `=` mean, functions, equations and calculus, where
> each field's notation is, and what the language makes of Python's habits.
> **Before this:** [Getting started](getting-started.md).
A RelativisticPy program is a sequence of statements: definitions, which
give names to things, and expressions, whose values are the program's results.
Everything below can be written in plain text or in LaTeX; the
[LaTeX page](latex.md) explains how the two relate. The
[language reference](reference.md) lists everything the language reads, on one page.
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook()
```
## Statements
One statement per line. Semicolons, LaTeX's `\\` and `\newline` also separate
statements. Comments start with `#` (or LaTeX's `%`).
```python
>>> wb.exe("n := 2; n^2 # a comment")
[4]
```
Since `%` starts a comment, `x % 2` would be `x`: in plain text, a `%` between
an operand and a number, as Python writes a remainder (`x % 2`, or
`x % 2 == 0`), is an error. Write `#` to comment there. A word after it, as in
`M := 1.989e30 % kg`, is a comment.
A statement continues onto the next line when a bracket is open, when the line
ends with an operator, or when the next line starts with an operator that
cannot start a statement, such as `+`, `*` or `=`. A line that starts with `-`
is a statement of its own, as `-x` is, unless it is indented further than the
statement before it, as long equations usually are:
```python
>>> wb.exe("""
... total := 1 + 2 +
... 3
... + 4
... total
... - 5
... -total
... """)
[5, -10]
```
A line that ends with an operator by mistake is reported as the mistake, rather
than the statement on the next line, which was read as its continuation.
A loop written in words, as an algorithm is printed, `\textbf{for } k = 1, \ldots, 5`
with its steps on the lines after it, indented further, is refused, steps and all: the
language has no loops. Write each step out, or what the loop computes as a sequence, from
its first member, as `x_0 := 1` then `x_{k+1} := x_k / 2`.
## Numbers and arithmetic
Arithmetic is exact: `1/2` is one half, not `0.5`. Decimals stay decimals.
Powers are written `^` or `**`, and juxtaposition is multiplication, though
not of two numbers: `10 000` is an error. Digits grouped in threes by thin
spaces, as SI writes them, are one number: `299\,792\,458`.
```python
>>> wb.exe("1/2 + 1/3\n2.5 * 2\n2^10\n3 p q\n299\\,792\\,458")
[5/6, 5.00000000000000, 1024, 3*p*q, 299792458]
```
`pi`, `e` and `i` are the constants, and `oo` (or `\infty`) is infinity.
```python
>>> wb.exe("e^{i pi}\n1/oo")
[-1, 0]
```
## Names and symbols
A name that has not been defined is a symbol. Greek letters can be spelled
`theta`, `\theta` or `θ`; all three are the same symbol.
```python
>>> wb.expr(r"theta + \theta + θ")
3*theta
```
A subscript on a symbol makes a new symbol: `r_{s}` is the symbol `r_s`, and so
is `r_s`.
```python
>>> wb.expr("r_{s} := 2 G M\nr_s / M")
2*G
```
A subscript that labels a quantity is part of its name, whatever it is written with:
`\lambda_1`, `\delta_0`, `V_{10}`, `M_\odot`, `r_+` and `\sigma_x` are names of their own,
and a name the program defines wins over a built-in tensor, as `R_\odot` does over the
Ricci tensor. An index of a tensor in force, a label declared over a space, and a
built-in tensor with its indices stay indices, as in `T_{\mu\nu}` and `g_{tt}`. On the
left of `:=` a number or an order raised on a name is part of it, as in `\sigma^2 := ...`,
and `\Delta x` is one name, the change in x:
```python
>>> names = Workbook()
>>> names.exe(r"""
... \lambda_1 := 2
... \sigma^2 := \frac{1}{4}
... \Delta x := \frac{1}{2}
... \lambda_1^2 + \sigma^2 + \Delta x
... """)
[19/4]
```
A one-letter subscript that the value of a name being defined is written with makes a
family, and a member is the family at its subscript. A family written with its own
members is a recurrence: given its first members, a member is computed one after
another, or in closed form where SymPy finds one:
```python
>>> names.exe(r"""
... c_n := \frac{1}{n^2}
... F_0 := 0
... F_1 := 1
... F_{n+2} := F_{n+1} + F_n
... c_1 + c_2
... F_{10}
... """)
[5/4, 55]
```
A name with scripts, then names in brackets, defines a function, and so does a primed
name on the left of `:=`. Of a function of one variable, `f^{(4)}` is the fourth
derivative, and a function named without its argument is the function at its
parameters, as y is in `\frac{dy}{dx}`:
```python
>>> names.exe(r"""
... R_{nl}(r) := r^2 e^{-r}
... H'(x) := 2 x
... y(x) := x^3
... R_{nl}(1) + H'(3)
... y^{(2)}(1) + \frac{dy}{dx}
... """)
[exp(-1) + 6, 3*x**2 + 6]
```
`Workbook.explain` says how each was read, and a note says so where another reading was
possible.
A bar over a quantity the program defines or declares complex, `\bar{z}` or
`\overline{z}`, is its complex conjugate, and so is a bar over an expression,
`\overline{3 + 4i}`; a star is too, on such a name or on brackets, `z^*` and
`(3 + 4i)^*`. Over a name that means nothing, `\bar{x}` is a name of its own, as it is
where the program defines it, `\bar{x} := \ldots`.
State what a symbol is as books do, with a relation on its name alone: `a > 0`,
`0 < x < 1`, `a, b > 0`, `x \in \mathbb{R}`, `n \in \mathbb{N}` or `n \in \mathbb{Z}_{>0}`.
It is an assumption for the rest of the program, shows nothing, and SymPy simplifies
with it:
```python
>>> wb.exe(r"""
... a, b > 0
... \sqrt{a^2 b^2}
... \sqrt{c^2}
... """)
[a*b, sqrt(c**2)]
```
A name may be used before it is assumed: what was defined with it takes the assumption
from then on, and what was shown stays as it was. What SymPy cannot keep on a symbol,
as x < 1 in `0 < x < 1` or `a > r` in `a > r > 0`, is kept beside it and used where it
decides something, as by `solve`; so is what is assumed of a coordinate, whose symbol
stays as it is. A relation between names alone, as `T_h > T_c`, stays a condition, and
one on a name that has a value is a claim, checked. `Workbook.explain` says which.
The declarations `Constants`, `Reals`, `Integers`, `Complex` and `Positive`, as in
`Positive := [a]`, say the same of a list of names, and `Coordinates` declares the
coordinates.
Where a program says nothing of a name, its symbol stays general. An integral or a limit
that would then hold conditions on a parameter, a modulus of one, or be left undone, is
given under the assumption books make, and a note says so: a parameter is a scale, a
width, a mass, a frequency, positive, and the variable of an integral over real limits is
real. The fewest parameters are assumed, and none the program said something of:
```python
>>> step = list(wb.each(r"\int_0^\infty e^{-s t} \, dt"))[0]
>>> step.values, step.assuming
([1/s], ['s > 0'])
>>> step.notes
['assuming s > 0, as books take a scale to be; the program does not say what s is']
```
`solve` keeps the solutions the program's assumptions allow, and says which it dropped.
## Definitions, and what `=` means
`:=` defines a name, or gives it a new value; LaTeX's `\equiv` and `\coloneqq` mean the
same.
```python
>>> wb.expr(r"""
... E \equiv m c^2
... E
... """)
c**2*m
```
Papers write `=` both to define and to claim, so `=` defines only what has no meaning
yet, and otherwise states something to check or to solve. What it does depends on what
its left side already means:
| You write | When | It means |
|---|---|---|
| `x := 2`, `x \equiv 2`, `x \coloneqq 2` | always | define x, or give it a new value |
| `x = 2` | x has no meaning yet | define x; so do `f(x) = x^2`, a new tensor `T_{ab} = ...` and a line element `ds^2 = ...` |
| `x = 3` | x already has a value | a claim, checked: is x equal to 3? |
| `R = 0`, `g_{tt} = -1` | a metric is in force | a claim about a built-in, or about a component |
| `t = 0` | t is a coordinate | a condition: read, but not computed |
| `x^2 + y^2 = 1` | otherwise | an equation, to solve |
| `a = b = c` | in a derivation | one claim for each link |
To give a name that has a value a new one, or a built-in's name a meaning of your own,
write `:=`.
A claim is decided, or refused as undecided. An equation SymPy cannot show to hold,
though numbers do not show its sides to differ, as an identity it cannot prove, and an
inequality SymPy cannot compare, as `e^x \geq 1 + x`, raise an `UndecidedError` rather
than show the claim as if it were an answer. An equation that numbers show not to hold,
as `x^2 + y^2 = 1`, stays an equation, and an inequality between rational functions of
names, as `a > 0` or `x \geq y + 1`, is a condition, shown as written.
Functions are defined by writing their parameters:
```python
>>> wb.expr("h(x, y) := x^2 - y\nh(3, 1)")
8
```
Longer functions are blocks. Names defined inside a function stay inside it,
and a function sees the names of the scope it was defined in:
```python
>>> wb.expr("""
... k := 10
... energy : (v) -> {
... half := 1/2
... half k v^2
... }
... energy(2) + half
... """)
half + 20
```
## Equations
`=` between expressions that are not a name being defined is an equation.
```python
>>> wb.expr("x^2 + y^2 = 1")
Eq(x**2 + y**2, 1)
```
Equations are what `solve` and `dsolve` solve, and `RHS` and `LHS` take them
apart:
```python
>>> wb.expr("solve(x^2 = 4, x)")
[-2, 2]
>>> wb.expr("RHS(dsolve(f'(x) = f(x), f(x)))")
C1*exp(x)
```
An equation is shown, not solved, unless it is given to `solve`: a name it holds stays a
symbol. A value after it that holds that name says so in a note, with how to solve it:
```python
>>> step = list(Workbook().each("x^2 = 4\nx + 1"))[1]
>>> step.values, step.notes
([x + 1], ['x is a symbol here: the equation on line 1 holds x, and is shown, not solved; for the values of x, solve it, as in solve(x^2 = 4, x)'])
```
## Evaluation
An evaluation bar substitutes values, as on paper:
```python
>>> wb.expr(r"x^2 + y |_{x=3, y=1}")
10
>>> wb.expr(r"\left. \frac{d}{dx} x^3 \right|_{x=2}")
12
```
A bar written with `\left.` and `\right|` evaluates what they enclose, and only that. With
limits, a bar or a bracket is the difference of two values, F(b) − F(a), in the variable
written with them; where none is written, in that of an integral beside it, or else in the
one symbol it holds:
```python
>>> wb.expr(r"x + \left. x^2 \right|_{x=2}")
x + 4
>>> wb.expr(r"\left[ x e^x \right]_0^1 - \int_0^1 e^x \, dx")
1
```
## Calculus
Derivatives can be written in every common notation:
```python
>>> wb.exe(r"""
... diff(sin(x), x)
... \frac{d}{dx} \sin x
... \frac{\partial^2}{\partial x \partial y} x^2 y^3
... \pdv{x^2 y}{y}
... d{x^3}/d{x}
... """)
[cos(x), cos(x), 6*x*y**2, x**2, 3*x**2]
```
Lagrange's primes differentiate a function you have defined, or an unknown one:
```python
>>> wb.exe("q(t) := t^3\nq''(t)\nu'(t)")
[6*t, Derivative(u(t), t)]
```
A subscript on a function the program defines is a partial derivative, as Stewart writes
it: `f_x` and `f_{xy}` by the variables they name, `f_1` and `f_{12}` by those they number,
and `D_1 f` too, each with a note:
```python
>>> wb.exe(r"""
... f(x, y) := x^2 y^3
... f_x
... f_{12}(1, 2)
... D_1 f
... """)
[2*x*y**3, 24, 2*x*y**3]
```
Integrals end at their differential, which may also come first or sit in the
numerator of a fraction, where it ends the integral with its term. An evaluation
bar before the differential is inside the integral. A differential alone
integrates 1:
```python
>>> wb.exe(r"""
... \int_0^1 x^2 \, dx
... \int_0^\infty e^{-x} dx
... \int \frac{dx}{x}
... \int_1^\infty \frac{dr}{r^2} - \pi
... \int_0^\pi \left. \sin(x y) \right|_{y=1} dx
... \int_0^L dx
... integrate(x y, (x, 0, 1), (y, 0, 2))
... """)
[1/3, 1, log(x), 1 - pi, 2, L, 1]
```
Where nothing defines δ, `\delta(x)` of a variable, or of a point as in `\delta(x - a)`, is
Dirac's delta, with a note; δ of what is no point, as `\delta(g^{-1})`, is not:
```python
>>> wb.expr(r"\int_{-\infty}^{\infty} x^2 \delta(x - 2) \, dx")
4
```
Limits, sums and products follow LaTeX. A sum or a product is its value where SymPy
finds a closed form within a few seconds, with its index an integer; one that converges
only under conditions on a parameter is given as books give it, with a note, as an
integral is. Otherwise it is kept as written, with a note:
```python
>>> wb.exe(r"""
... \lim_{x \to 0} \frac{\sin x}{x}
... \lim_{x \to 0^+} \frac{1}{x}
... \sum_{n=1}^{\infty} \frac{1}{n^2}
... \sum_{k=1}^{N} k
... \sum_{n=1}^{\infty} \frac{1}{n^n}
... """)
[1, oo, pi**2/6, N**2/2 + N/2, Sum(n**(-n), (n, 1, oo))]
```
In plain text and Unicode, calculus is typed as AsciiMath types it, and reads as the LaTeX
it spells: a solidus between differentials is Leibniz's fraction, `int`, `lim` and `sum`
with their scripts are `\int`, `\lim` and `\sum`, and `sum(f, (n, a, b))` is `\sum`, as
`integrate(f, (x, a, b))` is `\int`:
```python
>>> wb.exe("""
... d/dx sin(x)
... d(x^3)/dx
... int_0^1 x^2 dx
... lim_(x->0) sin(x)/x
... sum(1/n^2, (n, 1, oo))
... ∫_0^π sin²x dx
... """)
[cos(x), 3*x**2, 1/3, 1, pi**2/6, pi/2]
```
The Laplace, Fourier and z-transforms and their inverses are written as books write them,
a calligraphic letter with braces, `\mathcal{L}\{f(t)\}(s)`, which is the transform
whatever the plain letter means. Their variables are named by convention, by the letters
used: ℒ takes t to s, 𝒵 takes n to z, from n = 0, and ℱ takes x to s, with
\(e^{-2\pi i x s}\) as Bracewell writes it, or t to ω, with \(e^{-i\omega t}\). A program
chooses another convention by defining ℱ by its integral,
`\mathcal{F}\{f\}(\omega) := \frac{1}{\sqrt{2\pi}} \int_{-\infty}^{\infty} f(t)\, e^{-i\omega t}\, dt`,
and a note says which convention is used:
```python
>>> transforms = Workbook()
>>> transforms.exe(r"""
... \mathcal{L}\{t^2\}
... \mathcal{L}^{-1}\left\{\frac{1}{s^2 + 1}\right\}
... \mathcal{F}\{e^{-\pi x^2}\}
... \mathcal{Z}\{(1/2)^n\}(z)
... """)
[2/s**3, sin(t), exp(-pi*s**2), 2*z/(2*z - 1)]
```
The greatest and the least value of what follows, and where it is, are written as books
write them, `\max_{x}`, `\min_{x \in S}` or `\arg\max_{x}`, with constraints after
"subject to": [Optima](optima.md) has them.
## Functions you can call
Elementary functions (`sin`, `cos`, `tan`, `exp`, `ln`, `log`, `sqrt`, the
inverse and hyperbolic functions, `Abs`, `sign`, `floor`, `ceiling`,
`factorial`, `factorial2` (`n!!`), `binomial`, `gamma`, `re`, `im`, `conjugate`,
...), algebra (`simplify`, `expand`, `factor`, `collect`, `cancel`, `apart`,
`together`, `trigsimp`, `subs`, `N`), calculus (`diff`, `integrate`, `limit`,
`series`, `doit`), equations (`solve`, `dsolve`, `RHS`, `LHS`, `Eq`), matrices
(`det`, `trace`, `rank`, `inverse`, `expm`, `norm` and the rest of
[Matrices](matrices.md)), `latex`, `symbols`, and the
[spacetimes](tensors.md#spacetimes). A function without parentheses applies to
what follows it: `sin x` is `sin(x)`. In LaTeX it does so only when it is
written as a command, `\sin x` or `\operatorname{sign} x`, and a function's
name with nothing to act on is a symbol, as the lapse \(N\) is in
`ds^2 = -N^2 dt^2 + \ldots`. A Greek letter written as one, `\gamma` or `γ`,
is always a letter, so `\gamma(r)` in a metric is an unknown function; Euler's
gamma function is `gamma(x)`, spelled out.
A function you call without defining it stays unknown, which is how to write
an unknown function such as \(A(r)\) in a metric. So does a name with a label that nothing
defines, before names in brackets, as `\Phi_N(r)` and `V_{\rm eff}(r)`, and a name
written with `\operatorname` that nothing defines, which applies to what follows it:
`\operatorname{lb} 8` is lb(8). A note says each is unknown.
## Piecewise functions and other notation
```python
>>> wb.exe(r"""
... H(x) := \begin{cases} 1 & \text{if } x \geq 0 \\ 0 & \text{otherwise} \end{cases}
... H(2) + H(-2)
... step(x) := { 1, x >= 0; 0, otherwise }
... step(-1)
... |-3| + 4! + \binom{5}{2} + \lfloor 2.7 \rfloor
... """)
[1, 0, 39]
```
## Fields
Each field is read in the notation of its books, and has a page of its own:
- [Matrices](matrices.md): matrices written as environments or as lists of rows, and the
notation of linear algebra, as `A^T`, `\operatorname{tr} A`, `\|A\|_2` and `A \otimes B`.
- [Vectors](vectors.md): the dot and cross products, unit vectors, `\nabla` in the
coordinates in force, and integrals along curves and over regions.
- [Random variables](probability.md): `X \sim D`, probabilities, expectations, variances,
and the laws they follow.
- [Optima](optima.md): `\max`, `\min`, `\sup`, `\inf` and `\arg\max`, with constraints
after "subject to".
- [Number theory and sequences](discrete.md): the arithmetic functions, sums over divisors
and primes, congruences, and sequences, `x[n]`, as signal processing writes them.
- [Quantum notation](quantum.md): Dirac's kets and bras, commutators, and operators as
values.
## Coming from Python
The language looks like Python in places, `:=`, `**` and calls such as
`diff(f, x)`, but it is not Python. What Python would mean by something the
language reads otherwise is an error rather than a different computation, with
what to write instead:
| Python | What the language says |
|---|---|
| `x[1]` | of a list, it indexes as Python does, which the language does not: a component is written with indices, `V^{0}`; of a sequence, defined as `x[n] := ...`, it is its value at 1 |
| `[i^2 for i in range(3)]` | a list comprehension: write the list out, or a sum, `\sum_{i=0}^{2} i^2` |
| `import sympy` | the functions are built in: there is nothing to import |
| `series(sin(x), x, 0, n=5)` | a keyword argument: give the value in its place, `series(sin(x), x, 0, 5)` |
| `x % 2` | `%` starts a comment, as in LaTeX, so this would be `x` |
| `"\frac{1}{2}"` | Python turned `\f` into a form feed: write LaTeX in a raw string, `r"\frac{1}{2}"` |
```python
>>> wb.expr("x := [1, 2, 3]\nx[1]")
Traceback (most recent call last):
...
relativisticpy.errors.ParseError: x[1] indexes as Python does, which the language does not
--> :2:1
|
2 | x[1]
| ^^^^
hint: a component is written with indices, as in V^{0}; for a product, put a space before the bracket
```
An equation in a call is an equation, as in `subs(x^2, x = 2)` or
`solve(x^2 = 4, x)`: only after the first argument, a name set to a value with
no space around `=`, and used by no other argument, is taken for a keyword
argument.
Three habits of NumPy and MATLAB are read as they mean, each with a note, where what they
are written on is a matrix, and refused elsewhere: `A @ B` is the product of matrices,
`A.T` the transpose, and `eig(A)` the eigenvalues, as `spec(A)` writes them.
**Next:** [LaTeX](latex.md), for how LaTeX is read, then the page of your
[field](#fields), [Tensors and geometry](tensors.md) for General Relativity, or
[Beyond spacetime](spaces.md) for data. When a result surprises you, see
[Troubleshooting](troubleshooting.md).
# LaTeX
> **For:** everyone, since every result can be read as LaTeX, and above all anyone who
> pastes it from papers. **You will learn:** how LaTeX is read, letters, scripts,
> functions and brackets, the environments and commands, Unicode, and the looser
> notation of papers. **Before this:** [The language](language.md).
RelativisticPy reads LaTeX as mathematics. Paste an equation from a paper or
your notes and it runs; mix it with plain text as you like.
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook()
>>> wb.expr(r"\frac{1}{2} \sqrt{\pi} \cdot \left. \frac{d}{dx} x^3 \right|_{x=1}")
3*sqrt(pi)/2
```
**From Python, write LaTeX in a raw string,** `r"..."`. In an ordinary string,
Python turns `\a`, `\b`, `\f`, `\n`, `\r`, `\t` and `\v` into control
characters before RelativisticPy sees them, so `"\frac{1}{2}"` arrives as a
form feed and `rac{1}{2}`, and `"\theta"` as a tab and `heta`. RelativisticPy
says so, rather than reading them:
```python
>>> wb.expr("\frac{1}{2}")
Traceback (most recent call last):
...
relativisticpy.errors.ParseError: Python turned \f in \frac into a form feed
--> :1:1
|
1 | ␌rac{1}{2}
| ^ a form feed, not \f
note: in a Python string that is not raw, \a, \b, \f, \n, \r, \t and \v are control characters
hint: write the string as a raw string, with r before its quote: r"\frac{1}{2}"
```
## How LaTeX is read
**Typesetting is ignored.** Spacing (`\,`, `\;`, `\quad`), sizing (`\left`,
`\big`), `\displaystyle`, `\label{...}`, `\tag{...}`, math delimiters (`$`, `$$`,
`\[ \]`) and the `&` of alignment environments only change how an equation
looks, so they are skipped. `\mathrm{d}x` is `d x`.
**Letters are symbols.** As in typeset maths, a run of letters in LaTeX is a
product of single-letter symbols: `\frac{2GM}{c^2 r}` is
\(2 G M / (c^2 r)\). Greek names stay whole (`\alpha`, and `alpha` too), as do
names you have defined and builtins such as `diff`. Wrap a longer name in
`\mathrm{...}` or `\text{...}` to keep it one symbol; an escaped underscore
joins words, as in `\mathrm{geodesic\_equations}`. Every statement in a display
(`\begin{equation}`, `align` and the other environments, `\[ \]`, `$$`, and the
displays of a Markdown notebook) is LaTeX, however it is written. In plain
text (a statement outside a display, without LaTeX commands), `GM` is a single
name, as in a programming language.
A Markdown notebook runs its displays in order: `$$ ... $$`, `\[ ... \]`,
display environments such as `\begin{equation}`, and fenced blocks of maths,
```` ```math ````, as GitHub writes them. A fenced block marked
`relativisticpy` (or `relpy`) is a program, run as it is written; other code
blocks, code spans and inline maths are not run.
```python
>>> wb.exe(r"""
... \frac{2GM}{c^2 r}
... \mathrm{GM} + 1
... """)
[2*G*M/(c**2*r), GM + 1]
```
**A script without braces is one letter, as in TeX.** `^` and `_` take one
letter, one command or a braced group, so `R^a_b` is \(R^{a}{}_{b}\), and
`\delta^a_b` and `G^t_t` mean what they look like when typeset. TeX sets
`\Gamma^r_tt` as \(\Gamma^r{}_t\, t\), and so does RelativisticPy: write
`\Gamma^{r}_{tt}`. A Greek letter spelled out is one letter, as its command
is (`x^mu` is \(x^\mu\)), and a number is whole (`x^10` is \(x^{10}\)). A
sign is the whole script, a label, as in `h_+ \cos\omega t` and `e^+e^-`,
unless what it signs is written against it, as plain text writes a power:
`x^-1` is \(x^{-1}\). A name written with an underscore in plain text, such as
`r_s` or `x_0`, is one name, as in a programming language.
```python
>>> wb.exe(r"""
... x^ab + y^{ab}
... r_s := 2 G M
... 1 - r_s/r
... h_+ \cos(\omega t) + x^-1
... """)
[b*x**a + y**ab, -2*G*M/r + 1, h_+*cos(omega*t) + 1/x]
```
**Functions take what follows them.** `\sin x` is \(\sin(x)\), `\sin^2\theta`
is \(\sin^2(\theta)\) and `\sin^{-1} x` is \(\arcsin(x)\). Square brackets hold
an argument as parentheses do: `\exp[-x^2]`. Without brackets a function's
argument runs over the following factors (`\sin\omega t` is
\(\sin(\omega t)\), and `\ln A(r)` is \(\ln A(r)\)) and stops at explicit
spacing, an operator, another function or a differential: in
`\sin^2\theta\, d\phi^2` the argument is \(\theta\). Only `\log` takes a
subscript, its base, as in `\log_2 x`, and `\max` and `\min` the variables they are
over, as `\max_v` and `\arg\min_w` are [optima](optima.md): `\det_g` is an
error.
**What RelativisticPy prints reads back.** Results are typeset as SymPy
typesets them, with a function's arguments in braces, `a{\left(t \right)}`,
and a derivative of the function after it alone, `\frac{d}{d t} a{\left(t
\right)}`. Both read back as they were meant, so a result written into a paper
holds when the paper is [checked](checking.md):
```python
>>> wb.expr(r"\frac{d}{d t} a{\left(t \right)} \frac{d}{d t} b{\left(t \right)} + a^{2}{\left(t \right)}")
a(t)**2 + Derivative(a(t), t)*Derivative(b(t), t)
```
**Brackets group.** `\left[ ... \right]` and `\{ ... \}` group like parentheses.
`\left| ... \right|` is an absolute value and `\left. ... \right|_{x=a}` an
evaluation bar of what it encloses; with limits, `\left. ... \right|_a^b` and
`\left[ ... \right]_a^b` are the difference of its values there.
**A bracket right after a name calls it.** `A(r)` is the function A at r: an unknown
function, if nothing defines A, which is how a metric writes one. A name numbered by
a subscript is a name of its own, so `\psi_1(x)` and `R_{21}(r)` are called as
`x_0(t)` is. To multiply a name by a bracket, leave a space or write `\,`, as in
`G\,(p^2 + q^2)`:
```python
>>> wb.exe(r"A(r) + G\,(p^2 + q^2)")
[G*(p**2 + q**2) + A(r)]
```
**Definitions.** `\equiv`, `\coloneqq` and `≔` all mean `:=`. A primed or accented
name is a name of its own, which a definition gives a value, as in
`x' := \gamma (x - v t)` or `\hat{p} := 2`. A name written as an operator, with its
argument after it, defines a function, as `\operatorname{sinc} x := \frac{\sin \pi x}{\pi x}`
does. What `:=` cannot define is refused, saying how it was read: a dot is a time
derivative, so `\dot{x} := v` is refused, and so is `\psi_n(x) := \sin(n x)`, which is
read as ψ_n times x. Only `\equiv` states an identity where its left side cannot be
defined.
## Environments
| Environment | Meaning |
|---|---|
| `matrix`, `pmatrix`, `bmatrix`, `Bmatrix`, `smallmatrix`, `array` | a matrix |
| `vmatrix` | a determinant |
| `cases`, `dcases` | a piecewise function, with `\text{if}` and `\text{otherwise}`; so is an `array` in `\left\{ ... \right.` |
| `equation`, `align`, `gather`, `split`, `eqnarray`, `flalign`, `alignat`, `aligned`, `gathered`, `math`, breqn's `dmath` and `dgroup`, IEEEtrantools' `IEEEeqnarray`, and their starred forms | statements separated by `\\`; in `align`, each pair of columns is an equation |
| `multline` | one equation, broken over rows |
```python
>>> wb.exe(r"""
... \begin{align}
... a &:= 2 \\
... b &:= a^2 + 1 \\
... a + b
... \end{align}
... """)
[7]
```
## Commands
| Kind | Commands |
|---|---|
| Fractions and roots | `\frac` `\dfrac` `\tfrac` `\cfrac` `\sqrt` `\sqrt[n]` `\binom` |
| Big operators | `\sum` `\prod` `\int` `\iint` `\iiint` `\oint` `\lim` |
| Derivatives | `\frac{d}{dx}` `\frac{\partial^2 f}{\partial x \partial y}` `\pdv` `\dv` `\partial_\mu` `\nabla_\mu` |
| Functions | `\sin` `\cos` `\tan` `\cot` `\sec` `\csc` `\arcsin` `\arccos` `\arctan` `\sinh` `\cosh` `\tanh` `\coth` `\exp` `\ln` `\log` `\log_b` `\det` `\min` `\max` `\gcd` `\arg` `\Re` `\Im` `\operatorname{...}` |
| Accents | `\dot` `\ddot` (time derivatives of functions of one variable) and `\bar` `\hat` `\tilde` `\vec` `\check` `\breve` |
| Delimiters | `\left` `\right` `\big`... `\lvert` `\rvert` `\lfloor` `\rfloor` `\lceil` `\rceil` |
| Relations | `=` `\equiv` `\coloneqq` `<` `>` `\le` `\leq` `\ge` `\geq` `\ne` `\neq` `\to` |
| Operators | `\cdot` `\times` `\div` |
| Symbols | all Greek letters and their `\var` forms, `\infty`, `\hbar`, `\ell` |
| Text and style | `\text` `\mathrm` `\mathbf` `\mathcal` `\boldsymbol` and friends |
A function is also read as books write it, by the forms its integration declares:
`\Gamma(x)`, with one argument and no indices, is Euler's gamma function, while
`\Gamma^{\lambda}_{\mu\nu}` stays the Christoffel symbol, and a definition of the name in
the program always comes first. A book name that no integration provides yet is refused
as not supported yet, saying what it is, rather than read as an unknown function
([Integrations](integrations.md#written-forms)):
```python
>>> wb.expr(r"\Gamma\left(\tfrac{1}{2}\right)")
sqrt(pi)
```
[The language reference](reference.md#commands) lists every command, with what it
means. An unknown command is an error, with a suggestion:
```python
>>> wb.expr(r"\farc{1}{2}")
Traceback (most recent call last):
...
relativisticpy.errors.ParseError: unknown LaTeX command \farc
--> :1:1
|
1 | \farc{1}{2}
| ^^^^^
hint: did you mean \frac?
```
A command of LaTeX or of a package that RelativisticPy does not read, such as
the physics package's `\abs` or `\dd`, says what to write instead, and an
unknown environment lists the environments there are:
```python
>>> wb.expr(r"\abs{x}")
Traceback (most recent call last):
...
relativisticpy.errors.ParseError: \abs, the physics package's absolute value, is not supported
--> :1:1
|
1 | \abs{x}
| ^^^^
hint: write |x|, or \left| x \right|
```
## Unicode
Unicode maths reads like the LaTeX it stands for: `θ` is `\theta`, `∂` is
`\partial`, `∫` is `\int`, `·` is `\cdot`, `≤` is `\le`, and superscripts are
spelled out, so `r²` is `r^{2}`. A symbol is one symbol, as its command is:
`ℏ` is `\hbar` and `⊙` is `\odot`. Unicode's spaces (the no-break space, the
thin space) are spacing, like `~` and `\,`, and a byte order mark is ignored.
```python
>>> wb.expr("∫_0^1 θ² dθ")
1/3
```
## Notation from papers
Papers are written in LaTeX that is older, looser and more personal than a
notebook's, and RelativisticPy reads it too. That is what lets it
[check a paper](checking.md) as it stands.
**Derivations.** Relations chain, and each link is a claim. In an alignment, a
row that starts with a relation (`&=&`), or with an operator after an
alignment marker (`& & + c`), continues the row before it, as does a bracket
broken over two rows, `\left( a \right. \\ & \left. + b \right)`:
```python
>>> wb.exe(r"""
... \begin{eqnarray}
... E &=& {1 \over 2} m v^2 \nonumber \\
... &=& {m v^2 \over 2} \ ,
... \end{eqnarray}
... """)
[Eq(E, m*v**2/2), True]
```
**Sentences.** The punctuation that ends a sentence is ignored, as in
`E = mc^2\ .`. Commas and wide spaces (`\quad`, `\qquad`) between equations
separate them, as do `\Rightarrow`, `\implies` and `\iff`, and words such as
`\text{and}`, `\text{or}` and `\text{where}`:
```python
>>> wb.exe(r"{\rm GM}/r + {n \choose 2} \qquad r_+ + r^* \qquad \hbar\omega \ .")
[GM/r + binomial(n, 2), r^* + r_+, hbar*omega]
>>> wb.exe(r"x \equiv 2, \quad y \equiv 3 \quad \text{and} \quad x + y")
[5]
```
A definition shares its line with other equations, as above, and names listed
before `\in` are one declaration: `a, b \in \mathcal{A}`. Names set equal to a
list of values, `\mu, \nu = 0, 1, 2, 3`, give the range of indices; that is read
but not computed, and defines nothing.
| Kind | Notation |
|---|---|
| Plain TeX | `{a \over b}`, `{n \choose k}`, the font switches `{\rm d}`, `{\bf x}`, `{\cal L}`, `\matrix{a & b \cr c & d}`, `\pmatrix`, `\cases`, `\bgroup` |
| Relations read but not computed | `\sim` `\simeq` `\approx` `\cong` `\propto` `\ll` `\gg` `\in` `\subset` `\to` `\leftrightarrow`, `:` as in `\phi : M \to N`, and ranges such as `\mu, \nu = 0, 1, 2, 3` |
| Identities | `A \equiv B`, when A cannot be defined, states that the two are equal |
| Labels on symbols | `r_+`, `i^-`, `r_\pm`, `r^*` and prescripts such as `{}^{(3)}R` name symbols rather than raising to powers |
| Primes | after a numeric subscript a prime marks the whole name, so `\phi_0'(r)` is the derivative of \(\phi_0\); after a braced script it marks the symbol, so `R_{\mu\nu}'` reads as `R'_{\mu\nu}`; after an unbraced index, the index: `x^\mu'` is `x^{\mu'}` |
| Index labels | `\mu'`, `\mu_1`, `\mu_{p+1}`, `\phi_{t*}`, nested groups such as `R_{\rho\sigma{\mu\nu}}`, `\phi,{}_\mu` for \(\phi_{,\mu}\), and MTW's staggered `{\Gamma^r}_{tt}` |
| Operators | `\Box` (\(\nabla^\mu\nabla_\mu\)), the Lie derivative `\pounds_V`, the wedge product `A_{\mu} \wedge B_{\nu}`, `\otimes`, `\pm` and `\mp` (both values), and the Poisson bracket with respect to a canonical pair, `\{f, g\}_{q, p}`, read as its derivatives |
| Not computed | `\cdots` and `\ldots`, the Hodge dual `*F`, composition `\circ`, integrals over regions `\int d^4x` and `\iint_{x^2 + y^2 \le 1} f \, dA`, and sums over indices without limits, `\sum_b`, are read, and say why they cannot be computed |
A relation that is read but not computed says so:
```python
>>> wb.expr(r"\rho \propto a^{-3}")
Traceback (most recent call last):
...
relativisticpy.errors.CompileError: '∝' is read but not computed: RelativisticPy decides equations and inequalities
--> :1:1
|
1 | \rho \propto a^{-3}
| ^^^^^^^^^^^^^^^^^^^
```
**Next:** [Checking papers](checking.md), to run the equations of a whole paper, or
[Tensors and geometry](tensors.md), for the tensors they are written in.
# Matrices
> **For:** anyone who computes with matrices. **You will learn:** how to write a matrix,
> and the notation of linear algebra as books write it. **Before this:**
> [The language](language.md).
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook()
```
## Writing a matrix
Matrices are written as LaTeX environments, or as lists of rows, and `vmatrix` is a
determinant:
```python
>>> wb.exe(r"""
... \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}
... \begin{vmatrix} a & b \\ c & d \end{vmatrix}
... """)
[[[1, 2], [3, 4]], a*d - b*c]
```
## Arithmetic
In arithmetic, lists and matrices are vectors and matrices: a number scales
them, arrays of one shape add, matrices multiply as matrices, and a square
matrix has integer powers, so \(A^{-1}\) is its inverse. A matrix written in blocks,
as `\begin{pmatrix} B & AB \end{pmatrix}`, is one matrix. Anything else, such as
adding a number to a list, is an error. NumPy's `A @ B` is the product `A B` of matrices,
with a note, and of anything else it is refused.
```python
>>> wb.exe(r"""
... 2 [1, 2] + [0, 1]
... \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} \begin{pmatrix} u \\ v \end{pmatrix}
... \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}^{-1}
... """)
[[2, 5], [[u + 2*v], [3*u + 4*v]], [[-2, 1], [3/2, -1/2]]]
```
## The notation of linear algebra
The rest of the notation of matrices is read as books write it, by what it is written
on: a superscript T is the transpose of a matrix and a power of a number, and
\(\rho(A)\) is the spectral radius of a matrix, while \(\rho(1 + 3w)\) is not. Each
reading is recorded, as `Workbook.explain` shows, with a note where another was
possible, and a definition of the program's own always wins. The functions of a matrix
are in the [reference](reference.md#functions), and `relativisticpy help kron` describes
one in full.
| Written | Read as |
|---|---|
| `A^T`, `A^\top`, `A^\intercal`, `Aᵀ` | the transpose, where T has no value |
| `A^t`, `{}^tA`, `\tilde{A}` | the transpose too, with a note: where t means nothing, `A^t` is no power |
| `A.T` | the transpose, as NumPy writes it, with a note; of what is no matrix, refused |
| `A^\dagger`, `A^*`, `A^{-1}`, `A^+` | the conjugate transpose, the inverse and the pseudoinverse |
| `\operatorname{tr} A`, `\det A`, `\operatorname{rank} A` | the trace, the determinant and the rank; without brackets, of the factors that follow, so `\operatorname{tr} A B` is tr(AB) |
| `e^{A t}`, `\exp(A)`, `\log A`, `\sqrt{A}`, `A^{1/2}`, `A^k` | functions of the matrix, not of each entry |
| `\rho(A)`, `\kappa(A)`, `\lambda_{\max}(A)`, `\lambda_k(A)` | the spectral radius, the condition number and the eigenvalues, counted from the smallest |
| `\operatorname{spec}(A)`, `\sigma(A)` | the spectrum: every eigenvalue, from the smallest, as often as it is one; `\sigma` of what is no matrix is what it was |
| `\|A\|_2`, `\|A\|_F`, `\|A\|_\infty`, `\|x\|_1` | norms, of orders 2, Frobenius's, \(\infty\) and 1 |
| `\operatorname{adj} A`, `\ker A`, `\dim \ker A`, `\operatorname{vec} A`, `(A^3)_{12}` | the adjugate, the null space and its dimension, the columns stacked, and an entry, counted from 1 |
| `A \otimes B`, `A \oplus B` | the Kronecker product and the direct sum; between tensors, `\otimes` is their product |
| `I`, `\mathbb{1}`, `𝟙`, `\mathbf{1}` | added to a matrix, the identity of its size; `\mathbf{1}` in a product, the vector of ones of the size it meets |
A number added to a square matrix is that multiple of the identity, and a product that is
a 1 × 1 matrix, as a row times a matrix times a column, is the number it holds, however it
is written. A function of a matrix of a name nothing defines, as `\det M` or
`\operatorname{tr}(\ln M)`, is an unknown value, det(M) or tr(log M), since M may be a
matrix of any size: a claim about it relates, and is not proven by its 1 × 1 case. Each
says so in a note. In plain text, two bars side by side are a norm, as `\|` writes one:
`||x||_1` is `\|x\|_1`.
```python
>>> wb.exe(r"""
... A := \begin{pmatrix} 0 & 1 \\ -2 & -3 \end{pmatrix}
... B := \begin{pmatrix} 0 \\ 1 \end{pmatrix}
... C := \begin{pmatrix} 1 & 0 \end{pmatrix}
... \left(\operatorname{tr} A\right)^2 - 4 \det A
... \operatorname{rank} \begin{pmatrix} B & AB \end{pmatrix}
... C (s I - A)^{-1} B
... \lambda_{\max}(A) + \|A\|_\infty
... C \cdot B
... \sigma(A)
... """)
[1, 2, 1/(s**2 + 3*s + 2), 4, 0, [-2, -1]]
>>> wb.exe(r"""
... R := \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix}
... e^{R t}
... R^T R + \rho(R)
... """)
[[[cos(t), sin(t)], [-sin(t), cos(t)]], [[2, 0], [0, 2]]]
>>> print(wb.explain(r"R^T - \lambda I"))
line 1: R^T - \lambda I
matrix or number: R^T is the transpose of R, since R is a matrix, and T has no value
matrix or number: I is the identity of the size of R^T, since nothing defines I, and it is added to the matrix R^T
R: a value, defined on line 2
\lambda: a symbol
I: the identity
note: I is read as the identity of the size of R^T, as it is added to it; to name it, define I
```
A power SymPy leaves undone, as \(A^n\) of some singular matrices, is refused, saying so.
`eig(A)` of a matrix written without indices is its eigenvalues, as MATLAB gives them and
`spec(A)` writes them, with a note; of a map written with its indices, as
`eig(A^{a}{}_{b})`, it is the eigenvalues and the eigenvectors, as NumPy's `eig` gives them:
```python
>>> wb.expr("eig(A)")
[-2, -1]
```
## Maps written with indices
Given a map written with its indices, as `A^{a}{}_{b}`, a function of a matrix acts on
its matrix of components, and its value is a number or a map of the same space (see
[Beyond spacetime](spaces.md#linear-algebra)).
**Next:** [Vectors](vectors.md), or [Beyond spacetime](spaces.md), for linear algebra in
index notation over data.
# Vectors
> **For:** anyone who computes with vectors and fields. **You will learn:** the products
> of vectors, `\nabla` in any coordinates, and integrals along curves and over regions.
> **Before this:** [The language](language.md).
```python
>>> from relativisticpy import Workbook
```
## Vectors and their products
A list, a tuple or a column of numbers is a vector, and is read as one by what it meets:
`\cdot` between vectors is their dot product and `\times` their cross product, while
between numbers both multiply; `|\mathbf{v}|` and `\|\mathbf{v}\|` are its length, the
root of the sum of each component times its conjugate, of a row and a column alike, and
`\mathbf{p}^2` is \(\mathbf{p} \cdot \mathbf{p}\). `dot(u, v)` and `cross(u, v)`, as
programs write them, are the same two products; neither conjugates a side, as NumPy's
`dot` does not. Beside `\cdot` or `\times`, `\mathbf{1}` is the vector of ones as long as
the vector it meets. Derivatives, integrals, evaluation bars and limits of a vector are
taken component by component. Where nothing defines them, `\hat{\mathbf{x}}`,
`\hat{\imath}` and `\mathbf{i}`, `\mathbf{j}`, `\mathbf{k}` are the unit vectors of
Cartesian coordinates, and so is `\hat{x}`, unless it is the position x: in the angle
brackets of a wavefunction of x, or beside an operator that differentiates by x, as
`\hat{p} := -i\hbar \frac{d}{dx}` does, where the statement writes no hat that only a unit
vector can be, as `\hat{y}` is; a function is read as it was where it is defined.
`\hat{\mathbf{r}}` and `\mathbf{e}_\theta` are those of the coordinates in force. A
typeface makes a name of its own where the program defines both: after `\mathbf{r} := (x,
y, z)` and `r := |\mathbf{r}|`, `\mathbf{r}` is the vector and r its length; where it
defines one of them, the other stands for it, with a note (decision 9 of
[the notation decisions](https://github.com/cottrellashley/relativisticpy/blob/main/design/notation.md)).
```python
>>> products = Workbook()
>>> products.exe(r"""
... \mathbf{u} := (1, 2, 3)
... \mathbf{v} := (4, 5, 6)
... \mathbf{u} \cdot \mathbf{v}
... \mathbf{u} \times \mathbf{v}
... dot(\mathbf{u}, \mathbf{v})
... cross(\mathbf{u}, \mathbf{v})
... |\mathbf{u}|
... """)
[32, [-3, 6, -3], 32, [-3, 6, -3], sqrt(14)]
```
## Vector calculus
`\nabla` with no index is vector calculus's: `\nabla f`, `\nabla \cdot \mathbf{v}`,
`\nabla \times \mathbf{v}` and `\nabla^2 f`, or `\Delta f`, act on the factor after them,
and `(\mathbf{u} \cdot \nabla)` on what follows it. An equation between vectors is
decided component by component, and `\mathbf{0}` is the zero vector.
```python
>>> vc = Workbook()
>>> vc.exe(r"""
... \mathbf{v} := xy\,\hat{\mathbf{x}} + 2yz\,\hat{\mathbf{y}} + 3zx\,\hat{\mathbf{z}}
... \mathbf{v} \cdot \hat{\mathbf{y}}
... \nabla \cdot \mathbf{v}
... \nabla \times \mathbf{v}
... \nabla \times (\nabla f(x, y, z)) = \mathbf{0}
... \mathbf{r}(t) := (\cos t, \sin t, t)
... |\mathbf{r}'(t)|
... \int_0^{2\pi} \mathbf{r}(t) \, dt
... """)
[2*y*z, 3*x + y + 2*z, [-2*y, -3*z, -x], equation: holds in all 3 components, sqrt(2), [0, 0, 2*pi**2]]
```
## Coordinates
The operators are those of the coordinates in force, computed from their metric as index
notation gives them, with each vector's components along their unit vectors: the
gradient is \(g^{ij}\partial_j f\) and the divergence
\(\frac{1}{\sqrt{g}}\partial_i(\sqrt{g}\, v^i)\). The scale factors come from a line
element, from the Cartesian coordinates the program writes in the coordinates it
declares, as `x := r \sin\theta \cos\phi`, or, for coordinates it only declares, from
their names: spherical, cylindrical or polar, as a note says. Without coordinates, they
are x, y and z, or the variables of the function, as of `f(x, y)`.
```python
>>> cylinder = Workbook()
>>> cylinder.exe(r"""
... ds^2 = d\rho^2 + \rho^2\, d\varphi^2 + dz^2
... \mathbf{u} := \omega \rho\, \hat{\boldsymbol{\varphi}}
... \nabla \times \mathbf{u}
... \nabla^2 \rho^2
... """)
[[0, 0, 2*omega], 4]
```
## Cartesian tensors
Where the metric in force is written as the identity, as Cartesian coordinates' line
element is, an index may be repeated in any position and is summed, as in Cartesian
tensors; so too in a space declared as \(\mathbb{R}^n\). There, `\epsilon_{ijk}`, which
nothing defines, is the Levi-Civita symbol, +1 of 1, 2, 3; in spacetime, whose sign is a
convention, it is not read yet.
```python
>>> cartesian = Workbook()
>>> cartesian.exe(r"""
... ds^2 = dx^2 + dy^2 + dz^2
... A_{i} := [u(x, y, z), v(x, y, z), w(x, y, z)]
... \epsilon_{ijk} \partial_j (\epsilon_{klm} \partial_l A_m) = \partial_i \partial_j A_j - \partial_j \partial_j A_i
... """)
[ε_{ijk} ∂_j (ε_{klm} ∂_l A_m) = ∂_i ∂_j A_j − ∂_j ∂_j A_i: holds in all 3 components]
```
## Gradients, Hessians and integrals
Of a function the program defines, written at a point rather than at its variables,
`\nabla f(\mathbf{a})` is its gradient there, a column, and `\nabla^2 f(\mathbf{a})` its
Hessian, as optimisation books write them, said in a note; `\Delta f` is always the
Laplacian. Integrals over a disk or a ball about the origin, written
`\iint_{x^2 + y^2 \le 1}`, and over a box, `\iiint_{[0, 1]^3}`, are taken in turn; any
other region is refused. An integral along a curve the program defines as a function of
one parameter whose value is a vector, with the parameter's range stated, as
`C(t) := (\cos t, \sin t, 0), \quad 0 \le t \le 2\pi`, is written `\oint_C` or `\int_C`:
in it, `d\mathbf{r}` is the curve's tangent times the differential of its parameter, the
curve's name is its point, and x, y and z are its components, so that
`\oint_C \mathbf{F} \cdot d\mathbf{r}` is the circulation of a field. Where SymPy finds
no closed form in five seconds, and nothing but the parameters is left, it is computed
numerically, as a note says.
```python
>>> newton = Workbook()
>>> newton.exe(r"""
... f(x, y) := x^2 + x y + y^2 - 3x
... \nabla^2 f(0, 0)
... \begin{pmatrix} 0 \\ 0 \end{pmatrix} - \left[\nabla^2 f(0, 0)\right]^{-1} \nabla f(0, 0)
... \Delta f
... \iint_{x^2 + y^2 \le 1} e^{-(x^2 + y^2)} \, dA
... C(t) := (\cos t, \sin t, 0), \quad 0 \le t \le 2\pi
... \oint_C (-y\,\hat{\mathbf{x}} + x\,\hat{\mathbf{y}}) \cdot d\mathbf{r}
... """)
[[[2, 1], [1, 2]], [[2], [-1]], 4, -pi*exp(-1) + pi, 2*pi]
```
**Next:** [Random variables](probability.md), or [Tensors and geometry](tensors.md), for
index notation over any metric.
# Random variables
> **For:** anyone who computes probabilities. **You will learn:** how to declare a random
> variable, and to write probabilities, expectations and variances as books do.
> **Before this:** [The language](language.md).
```python
>>> from relativisticpy import Workbook
```
## Declaring a random variable
`X \sim D` declares a random variable, as books write it: `\sim` between a name nothing
defines and a distribution, for the rest of the program. It shows nothing, and a note says
what it declared. Each distribution is written in the forms books give it, which say what its
arguments are: `\mathcal{N}(\mu, \sigma^2)` and `N(\mu, \sigma^2)` take the variance, as
most books write them, `\Gamma(k, \theta)` the shape and the scale, and
`\operatorname{Exp}(\lambda)` the rate. Called by its name in plain text, a distribution takes
its parameters as SymPy and SciPy do, `Normal(mu, sigma)` the standard deviation. The
[reference](reference.md#random-variables) lists them, with the binomial, Poisson, Bernoulli,
uniform, gamma, χ², Student's t, beta and geometric distributions.
## Probabilities and expectations
`\Pr(A)`, `\mathbb{P}(A)` and `P(X = 2)` are probabilities, `\mathbb{E}[X]` an expectation,
and `\operatorname{Var}(X)` and `\operatorname{Cov}(X, Y)` the variance and the covariance;
inside them `\mid` is the conditional bar. P alone, a pressure elsewhere, is a probability
only of an event of random variables, and E an expectation only of them. Without brackets,
`\mathbb{E}` and `\operatorname{Var}` act on the product written after them, as
`\operatorname{tr}` does, so that `\operatorname{Var} 3Z` is the variance of 3Z. SymPy
computes each exactly; where it finds no closed form in 5 seconds and the problem has no
parameters, SciPy computes it numerically, and a note says so:
```python
>>> rv = Workbook()
>>> rv.exe(r"""
... N \sim \operatorname{Poisson}(\lambda)
... P(N = 2)
... Z \sim \mathcal{N}(0, 1)
... \Pr(Z > 1)
... \operatorname{Var}(3Z + 1)
... \mathbb{E}[Z^4]
... \operatorname{Var} 3Z
... """)
[lambda**2*exp(-lambda)/2, 1/2 - erf(sqrt(2)/2)/2, 9, 3, 9]
```
## Laws given by other random variables
A law may be given by another random variable, as a Poisson number of trials gives a
binomial number of successes, or for each value another takes. Given a random variable, an
expectation is a function of it, and the laws of total expectation and probability give the
rest:
```python
>>> rv.exe(r"""
... X \mid N \sim \operatorname{Bin}(N, p)
... \mathbb{E}[X \mid N]
... \mathbb{E}[X]
... \operatorname{Var}(X)
... Y \sim \operatorname{Bernoulli}(1/2)
... W \mid Y = 0 \sim \mathcal{N}(-1, 1)
... W \mid Y = 1 \sim \mathcal{N}(1, 1)
... \Pr(W > 0)
... """)
[p*N, lambda*p, lambda*p, 1/2]
```
## Samples and independence
Random variables declared in one statement with `\overset{\text{iid}}{\sim}`, or with
`\text{independent}` after the distribution, are independent; declared apart, they are taken
independent, and a note says so. `X_1, \ldots, X_n \overset{\text{iid}}{\sim} D` declares a
sample of n, whose members `X_i` a sum takes in turn. A capital letter nothing defines,
inside a probability, an expectation or a variance, is a random variable of a law not given,
as books write one, so that a rule that holds for every law is decided. The probabilities a
program gives events, as `\Pr(A \mid B_1) := 0.9`, are what it writes of them; an event of
a random variable it declares takes its probability from the law, and giving it another is
refused, as is defining a name declared a random variable:
```python
>>> sample = Workbook()
>>> sample.exe(r"""
... X_1, \ldots, X_n \overset{\text{iid}}{\sim} \mathcal{N}(\mu, \sigma^2)
... \bar{X} := \frac{1}{n} \sum_{i=1}^{n} X_i
... \mathbb{E}[\bar{X}]
... \operatorname{Var}(\bar{X})
... \operatorname{Var}(a Y + b) = a^2 \operatorname{Var}(Y)
... \Pr(B) := 0.01
... \Pr(A \mid B) := 0.9
... \Pr(A \mid B) \Pr(B)
... """)
[mu, sigma**2/n, True, 0.00900000000000000]
```
## Events of several variables
Events of several random variables that share one are not independent, and are not
computed as if they were. Of discrete variables, an event is summed over the values one of
them can take where it holds, and a variable an event gives a value takes it in the others.
What SymPy gives of several continuous variables together is kept only where a simulation
bears it out, and refused otherwise, saying so:
```python
>>> counts = Workbook()
>>> counts.exe(r"""
... X \sim \operatorname{Poisson}(2)
... Y \sim \operatorname{Poisson}(3)
... P(X = 1 \mid X + Y = 3)
... P(X = 1, X + Y = 3)
... \mathbb{E}[X \mid X + Y = 3]
... """)
[54/125, 9*exp(-5), 6/5]
```
## Densities and generating functions
`f_X(x)`, `F_X(x)` and `F_X^{-1}(q)` are X's density, distribution function and quantile, and
`M_X(t)` and `\varphi_X(t)` its moment-generating and characteristic functions. Where a
probability holds only for some values of a parameter the program says nothing of, it is
given where the parameter is among the values the variable takes, as a book gives it, and a
note says so:
```python
>>> rv.exe(r"""
... T \sim \operatorname{Exp}(\lambda)
... \Pr(T > t)
... f_Z(x)
... F_Z^{-1}(0.975)
... M_N(s)
... """)
[exp(-lambda*t), sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)), 1.95996398454005, exp(lambda*(exp(s) - 1))]
```
A moment-generating function is the expectation of an exponential only where it is finite,
as where `t < \lambda` of the exponential distribution: past it the expectation is ∞, and of
a symbol a note says what is assumed. A mean or a variance that does not exist, as of
Student's t with one degree of freedom, Cauchy's law, is refused, and its second moment is ∞:
```python
>>> [step.assuming for step in rv.each("M_T(s)")]
[['s < λ']]
>>> rv.exe(r"""
... V \sim \operatorname{Exp}(1)
... \mathbb{E}[e^{V/2}]
... \mathbb{E}[e^{2V}]
... C \sim t_1
... \mathbb{E}[C^2]
... """)
[2, oo, oo]
```
## Over data
Over data, `\mathbb{E}_t`, `\operatorname{Var}_t` and `\operatorname{Cov}_t` are statistics
along an index, as [Beyond spacetime](spaces.md#statistics) says; without an index, of data,
they are refused, saying so.
**Next:** [Optima](optima.md), or [Beyond spacetime](spaces.md#statistics), for
statistics of data.
# Optima
> **For:** anyone who maximises or minimises. **You will learn:** how to write an
> optimum and its constraints, how it is found, and when it is global.
> **Before this:** [The language](language.md).
```python
>>> from relativisticpy import Workbook
```
## Writing an optimum
The greatest and the least value of what follows, and where it is, are written as books
write them, with the variables beneath the operator: `\max_{x}`, `\min_{x \in S}`,
`\sup_{0 \le x < 1}` and `\inf_{x > 0}`, and `\arg\max_{x}`, `\operatorname*{arg\,min}_{w}`
or `\underset{x}{\min}`, which give the point, not the value. In plain text, `min_{x}` and
`argmax_{x >= 0}`. A set or a condition beneath the operator says what the variables range
over; constraints follow the words "subject to" or "s.t.", on the same line or on the
lines after it, and names before a comma share the relation after them, as in
`x, y \geq 0`. An optimum is of the whole sum it begins, up to a relation or "subject to",
as `\min_x x^2 - 4x + 7` is, and of its factor alone where it is a factor, as in
`2 \max_x f(x)`. `\max(a, b)` is still the greater of two values:
```python
>>> optima = Workbook()
>>> optima.exe(r"""
... \min_{x \in \mathbb{R}} \left(x^2 - 4x + 7\right)
... \arg\max_{x \geq 0} \; x e^{-x}
... \max_{0 \leq x \leq 3} \left(x^3 - 3x\right)
... \sup_{x \geq 0} \frac{x}{1 + x}
... \min_{x, y} \; x + y \quad \text{subject to} \quad x^2 + y^2 = 2
... \max_{x, y} \; 3x + 5y \quad \text{subject to} \quad x \leq 4, \quad 2y \leq 12, \quad 3x + 2y \leq 18, \quad x, y \geq 0
... """)
[3, 1, 18, 1, -2, 36]
```
## How an optimum is found
An optimum over variables is found as the program runs, by the
[optimizers](reference.md#optimizers) the integrations declare, in turn. SymPy's come
first, and find closed forms: from the stationary points and the ends of the domain of a
function of one variable, the Lagrange and KKT conditions of several, the simplex method of
a linear program, or by trying each point of a finite domain, as of `x \in \{0, 1\}^3`.
SciPy's come next, where the problem has no parameters, and find numbers; a problem written
with decimals, as data is, goes to them first. A note says which optimizer found the
optimum, how, and whether it is proven global:
```python
>>> [step.notes for step in optima.each(r"\min_{x, y} \; x + y \quad \text{subject to} \quad x^2 + y^2 = 2")]
[['the global minimum, found exactly by SymPy, from the Lagrange conditions; the constraints bound the region (kkt)']]
```
An optimum is said to be global only where that is proven: of a function of one variable,
where every stationary point in its domain is found, those of a periodic function too, and
every point where it is not defined, toward which its values are approached and never
reached; of several, of a convex problem, or of a polynomial one over a bounded region.
A search by SciPy gives an optimum only where it converged and nothing lower is found far
away, and it is not said to be global unless the problem is convex. Where more than one
point reaches the optimum, the note says which, an interval or a curve of them too, and
`\arg\min` gives the least:
```python
>>> [step.notes for step in optima.each(r"\arg\min_x \left(|x - 1| + |x + 1|\right)")]
[['the global minimum, found exactly by SymPy, from its stationary points, the points where it has no derivative, and the ends of its domain (extrema); every point of [−1, 1] reaches it, and −1 is given']]
```
## Variables and parameters
The variables are real, or whole numbers, as `n \in \mathbb{N}` says. A variable is a
vector where its set is `\mathbb{R}^n` or `\{0, 1\}^n`, or a matrix it is multiplied by
gives its length, as `A \mathbf{x}` does, and its components may be written `x_1, x_2`; a
tensor, where it is written with an index of a space. What the program assumes of its
parameters is used, as `a > 0`, and so is what it assumes of the variables themselves, as
`x \in [0, 1]` before `\min_x`, which a note says; where the answer depends on signs it does
not say, it is found as books find it, with the parameters real and the fewest of them
positive, which a note says (decision 1 of
[the notation decisions](https://github.com/cottrellashley/relativisticpy/blob/main/design/notation.md)).
A maximum that no point reaches, or that is infinite, is refused, and `\sup` gives the
bound:
```python
>>> optima.exe(r"""
... A := \begin{pmatrix} 1 & 1 & 0 \\ 0 & 1 & 1 \end{pmatrix}
... \mathbf{b} := \begin{pmatrix} 1 \\ 2 \end{pmatrix}
... \arg\min_{\mathbf{x}} \|\mathbf{x}\|_2 \quad \text{subject to} \quad A\mathbf{x} = \mathbf{b}
... \max_{x \in \{0, 1\}^3} \; 60x_1 + 100x_2 + 120x_3 \quad \text{subject to} \quad 10x_1 + 20x_2 + 30x_3 \leq 50
... L(v) = -m c^2 \sqrt{1 - \frac{v^2}{c^2}}
... H(p) = \max_v \left(p v - L(v)\right)
... H(p)
... """)
[[[0], [1], [1]], 220, c*sqrt(c**2*m**2 + p**2)]
>>> optima.expr(r"\max_x x^2")
Traceback (most recent call last):
...
relativisticpy.errors.EvaluationError: \max_x has no maximum: what it is of grows without bound, to ∞
--> :1:1
|
1 | \max_x x^2
| ^^^^^^^^^^
hint: the bound it never reaches is \sup, as in \sup_{x} f(x)
```
## Over data, and matrices
Over an index of data, an optimum binds the index as a sum does, and is the greatest or
the least value along it, and `\arg\max` its label: see
[Beyond spacetime](spaces.md#optima-over-an-index). `A \succ 0` and `A \succeq 0` say that
a symmetric matrix is positive definite or semidefinite, and between vectors, as in the
constraint `w \succeq 0`, hold of each component.
**Next:** [Number theory and sequences](discrete.md), or [Beyond spacetime](spaces.md),
for optima over data.
# Number theory and sequences
> **For:** anyone who computes with integers: number theory, combinatorics and signals.
> **You will learn:** the arithmetic functions, sums over divisors and primes,
> congruences, and sequences, as signal processing writes them.
> **Before this:** [The language](language.md).
```python
>>> from relativisticpy import Workbook
```
## Arithmetic functions
The arithmetic functions are written by the letters number theory gives them: Euler's
totient `\varphi(n)`, the Möbius function `\mu(n)`, the divisor functions `\sigma_k(n)` and
`d(n)`, `\omega(n)` and `\Omega(n)`, von Mangoldt's `\Lambda(n)` and the partitions `p(n)`.
Physics writes the same letters for an angle, a mean, a frequency or a momentum, so a letter
is the arithmetic function only where its argument is an integer: a whole number above 0, a
name the program assumes an integer, as `n \in \mathbb{N}` does, or the index of a sum.
Anywhere else it is what it was, and a note says which reading was taken. π is a constant,
so `\pi(10)` is 10π; `\pi(n)` counts primes only of a name assumed an integer. `H_n` and
`B_n` are the harmonic and the Bernoulli numbers only where n is such a name, so that `H_0`
stays Hubble's constant; `H_n(x)` is Hermite's polynomial. The Stirling numbers are written
in Karamata's brackets, `{n \brace k}` and `{n \brack k}`, and the Catalan, Fibonacci and Bell
numbers by their names (see the [reference](reference.md#functions)). `C(n, k)`, as Rosen
writes it, is the binomial coefficient where nothing defines C and both arguments are
counts: numbers, or names books write whole numbers with, as n and k, with a note; `C(x, t)`
stays a function, as a concentration is:
```python
>>> nt = Workbook()
>>> nt.exe(r"""
... \varphi(36) + \mu(30) + d(28)
... \varphi(x)
... \pi(10)
... n \in \mathbb{N}
... H_{n+1} - H_n
... \sum_{k=0}^{5} {5 \brace k}
... C(5, 2)
... """)
[17, phi(x), 10*pi, 1/(n + 1), 52, 10]
```
## Sums over divisors and primes
A condition under a sum or a product gives its index its values: `d \mid n` the divisors of
n, `p \le x` the primes up to x, as number theorists let p range over the primes, and
`p \text{ prime}` every prime, whose product of Euler's factors is a value of ζ. The rows of
`\substack` are conditions that each value meets. A sum over an index alone, `\sum_k`, of
binomial coefficients is over every integer, as Concrete Mathematics writes it, and the
coefficients leave the terms that are not 0:
```python
>>> nt.exe(r"""
... \sum_{d \mid 28} d
... 36 \prod_{p \mid 36} \left(1 - \frac{1}{p}\right)
... \sum_{\substack{1 \le k \le 10 \\ \gcd(k, 10) = 1}} k
... \prod_{p \text{ prime}} \frac{1}{1 - p^{-2}}
... \sum_k \binom{n}{k} x^k y^{n-k}
... """)
[56, 12, 20, pi**2/6, (x + y)**n]
```
## Congruences
`a \bmod m` is the remainder, and `a^{-1} \bmod m` the inverse of a modulo m. `\equiv` with
a modulus on its right is a congruence, a claim decided by the remainders; standing alone,
of a name nothing defines, it is an assumption, as `x > 0` is, and congruences and bounds
that leave the name one value give it that value, by the Chinese remainder theorem.
`\equiv` without a modulus still defines. `solve` gives the remainders that the solutions
of congruences leave, and `[x^n] F(x)` is the coefficient of x^n in the power series of F:
```python
>>> crt = Workbook()
>>> crt.exe(r"""
... 12! \bmod 13
... 17^{-1} \bmod 43
... 3^{100} \equiv 1 \pmod{101}
... x \equiv 2 \pmod{3}
... x \equiv 3 \pmod{5}
... x \equiv 2 \pmod{7}
... 0 \leq x < 105
... x
... solve(y^2 \equiv 1 \pmod{8}, y)
... [z^{10}] \frac{1 - \sqrt{1 - 4z}}{2z}
... """)
[12, 38, True, 23, [1, 3, 5, 7], 16796]
```
## Sequences
Square brackets right after a name are read by what the name is. `x[n] := \ldots` defines a
sequence, a function of the integer n, as Oppenheim and Schafer write a discrete-time
signal, and `x[3]` and `x[n - 1]` are its values. Where nothing defines δ or u, `\delta[n]`
is the unit impulse, 1 at n = 0 and 0 elsewhere, and `u[n]` the unit step, 1 from n = 0 on,
each with a note. That reading needs the brackets to hold an integer as books write a
point, whole numbers and names in sums, differences and multiples, so that
`\delta[(-g)^{-1/2}]` stays a variation. Where δ has a value, as after `\delta := 0.1`,
`\delta[n]` is δ times n, and a note says so. A list or a tensor is read as before, and in
plain text, brackets after a name that is no sequence are refused, as Python's indexing.
A sum over a sequence's index is taken a term at a time: an impulse leaves its term at the
one point where it is 1, and a step cuts its term's range to where it is 1. What is left is
summed in closed form where SymPy finds one, under what the program assumes, as `|z| > 1/2`.
A sum without limits whose index is a sequence's point, as in `\sum_k x[k] h[n - k]`, runs
over every integer, with a note:
```python
>>> signals = Workbook()
>>> signals.exe(r"""
... x[n] := \delta[n] + 2\delta[n-1] + 3\delta[n-2]
... h[n] := \delta[n] + \delta[n-1]
... y[n] := \sum_k x[k] h[n-k]
... [y[0], y[1], y[2], y[3]]
... g[n] := \left(\frac{1}{2}\right)^n u[n]
... g[3] + g[-1]
... \sum_{n=-\infty}^{\infty} g[n]
... \mathcal{Z}\{g[n]\}(z)
... """)
[[1, 3, 5, 3], 1/8, 2, 2*z/(2*z - 1)]
>>> print(signals.explain(r"u[n - 1]"))
line 1: u[n - 1]
sequence or product: u[n - 1] is step, the unit step, since u[n] is how signal processing writes it, and nothing defines u
n: a symbol
note: u[n - 1] is read as the unit step, step; for a sequence of your own, define u[n] := ... first
```
## Difference equations
A sequence defined through its own members, as `s[n] := \frac{1}{2} s[n-1] + u[n]`, is a
difference equation, at initial rest, as books take one: the sequence is 0 before its input
starts. Its values at whole numbers are computed one after another, and at a symbol in
closed form, where SymPy's `rsolve` finds one. `solve` solves a difference equation for a
sequence nothing defines, at rest too. An equation between sequences that nothing defines,
as `y[n] - \frac{3}{4} y[n-1] = x[n]`, is a difference equation of its own, and their capital
letters are their z-transforms, a delay of k samples \(z^{-k}\): so `Y(z)/X(z)` is the
transfer function, whose `poles` and `zeros` are the roots of its denominator and
numerator. The z-transform of a sequence written with impulses and steps is taken over every
n, and the inverse gives a sequence back, with its step:
```python
>>> systems = Workbook()
>>> systems.exe(r"""
... s[n] := \frac{1}{2} s[n-1] + u[n]
... s[2]
... s[n]
... solve(v[n] - \frac{1}{2} v[n-1] = \delta[n], v[n])
... y[n] - \frac{3}{4} y[n-1] + \frac{1}{8} y[n-2] = x[n]
... H(z) := \frac{Y(z)}{X(z)}
... H(z)
... poles(H(z))
... h[n] := \mathcal{Z}^{-1}\{H(z)\}
... h[n]
... """)
[7/4, (2 - 1/2**n)*step(n), [step(n)/2**n], Eq(y(n) + y(n - 2)/8 - 3*y(n - 1)/4, x(n)), 8*z**2/(8*z**2 - 6*z + 1), [1/4, 1/2], (2**(n + 1) - 1)*step(n)/4**n]
```
## The frequency response
The frequency response is written at \(e^{j\omega}\): `H(e^{j\omega}) := \sum_n h[n]
e^{-j\omega n}` defines H as a function of ω, and H at \(e^{j\theta}\) is its value at θ,
whose modulus and phase are `|H(e^{j\omega})|` and `\arg H(e^{j\omega})`. j is the imaginary
unit where a program says so, `j := \sqrt{-1}`, as engineering books do; elsewhere it is a
name, and where it meets a number in a sum, as in `1 + j`, a note says so.
```python
>>> dtft = Workbook()
>>> dtft.exe(r"""
... j := \sqrt{-1}
... \omega \in \mathbb{R}
... |a| < 1
... h[n] := a^n u[n]
... H(e^{j\omega}) := \sum_n h[n] e^{-j\omega n}
... H(e^{j\omega})
... H(e^{j\pi})
... """)
[1/(-a*exp(-I*omega) + 1), 1/(a + 1)]
```
## Convolution
An asterisk, `*` or `\ast`, between two sequences at points of one index is their
convolution, \(\sum_k x[k]\,h[n - k]\) over every integer k, and between two functions
applied at one variable it is \(\int f(\tau)\,g(t - \tau)\,d\tau\) over every τ, with u and δ
in them the unit step and the Dirac delta where nothing defines them; each is said in a
note. Between anything else, as `2*x`, it multiplies, and written side by side or with
`\cdot`, the two multiply. `\circledast` is the circular convolution, of the length its
subscript gives, `\circledast_N`, or else of the longer sequence (`design/notation.md`, 27):
```python
>>> convolved = Workbook()
>>> convolved.exe(r"""
... x[n] := \delta[n] + 2\delta[n-1] + 3\delta[n-2] + 4\delta[n-3]
... h[n] := \delta[n] + \delta[n-1]
... y[n] := x[n] * h[n]
... [y[0], y[1], y[2], y[3], y[4]]
... (x \circledast h)[0]
... t > 0
... \left(e^{-t} u(t)\right) * \left(e^{-2t} u(t)\right)
... """)
[[1, 3, 5, 7, 4], 5, (exp(t) - 1)*exp(-2*t)]
```
**Next:** [Quantum notation](quantum.md), or the
[reference](reference.md#functions), for every arithmetic function by name.
# Quantum notation
> **For:** anyone who computes quantum mechanics. **You will learn:** Dirac's kets and
> bras, commutators, wavefunctions, and operators as values. **Before this:**
> [The language](language.md), and [Matrices](matrices.md).
```python
>>> from relativisticpy import Workbook
```
## Kets, bras and commutators
Dirac's notation, commutators and operators are read as books write them, by what they
are written with. As for [matrices](matrices.md), each reading is recorded, as
`Workbook.explain` shows, with a note where another was possible.
A ket a program defines as a column is that vector, and its bra is the conjugate
transpose: a bracket is their inner product, `\langle\phi|A|\psi\rangle` a row times a
matrix times a column, and `|a\rangle\langle b|` a matrix. A label may be a sign, an
expression or several, as in `|j, m\rangle`, and `|00\rangle`, of kets the program
defines, is `|0\rangle \otimes |0\rangle`. `[A, B]` of matrices or operators is their
commutator, AB - BA, and `\{A, B\}` their anticommutator; of anything else they are a
list and a set, as before.
```python
>>> qm = Workbook()
>>> qm.exe(r"""
... |+\rangle := \frac{1}{\sqrt{2}} \begin{pmatrix} 1 \\ 1 \end{pmatrix}
... |-\rangle := \frac{1}{\sqrt{2}} \begin{pmatrix} 1 \\ -1 \end{pmatrix}
... X := \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}
... Z := \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}
... \langle + | X | + \rangle
... |+\rangle\langle+| + |-\rangle\langle-|
... [X, Z]
... """)
[1, [[1, 0], [0, 1]], [[0, -2], [2, 0]]]
```
## Wavefunctions
A function of one variable is a wavefunction, and so is a bracket defined as
`\langle x|\alpha\rangle := ...`. A bracket of wavefunctions is an integral, of
\(\phi^* A \psi\), over the domain the program states for the variable, or over the whole
line, and angle brackets around an operator are its expectation value, in the one state
the program defines or the state a subscript names, as in `\langle x \rangle_\psi`,
divided by \(\langle\psi|\psi\rangle\), as a state need not be normalised. A function named
\(\phi\) or \(\Phi\), which books give potentials and phases too, is a state only where a
ket or a subscript names it.
Written the other way round, a bracket a program defines is its conjugate, its labels
real; and `\psi^*(x)` is the conjugate of \(\psi(x)\).
## Operators
An expression that ends in an operator with nothing to act on, as `-i\hbar\frac{d}{dx}`
does, is an operator. Defined, it is a value: it acts on the rest of the term after it,
as \(\frac{d}{dx}\) does, as in `\hat{p}\psi(x)` and `\hat{p} x \psi(x)`, and products
and powers compose it, as in `\hat{p}^2`. Defined with
`\pm` in its name, as in `a_\pm := ...`, it is two, one for each sign. A claim between
operators is decided by applying both sides to a test function, as a note says.
```python
>>> qm.exe(r"""
... 0 \leq x \leq a
... \psi(x) := \sqrt{\frac{2}{a}} \sin\left(\frac{\pi x}{a}\right)
... \hat{p} := -i\hbar \frac{d}{dx}
... \langle\psi|\psi\rangle
... \langle x \rangle_\psi
... \langle \hat{p}^2 \rangle_\psi
... a_\pm := \frac{1}{\sqrt{2\hbar m\omega}} \left(\mp i\hat{p} + m\omega x\right)
... [a_-, a_+] = 1
... """)
[1, a/2, pi**2*hbar**2/a**2, True]
```
## Rules
Angle brackets hold what a program defines, as `\langle x^2 \rangle := ...` does, or the
bracket of two, as `\langle p, q \rangle := \int_{-1}^{1} p(x) q(x) \, dx` defines; around
two vectors they are their inner product. An `=` whose left side is written with
operators and kets that nothing defines states a rule for what follows, not a claim: a
commutator, as `[\hat{x}, \hat{p}] = i\hbar`, operators acting on a ket, as
`a|n\rangle = \sqrt{n}|n - 1\rangle`, or a bracket, as `\langle m|n\rangle =
\delta_{mn}`, whose labels stand for any label. The algebra of those operators and kets
reduces by the rules: operators act on kets, bras meet kets, and products are put in the
order the commutators give. The modulus of a bracket of them is the root of the bracket
times its conjugate, so that a sum over a label, as of `|\langle k|H'|0\rangle|^2`, is
taken.
```python
>>> rules = Workbook()
>>> rules.exe(r"""
... \langle (1, 2), (3, 4) \rangle
... \langle m | n \rangle = \delta_{mn}
... a |n\rangle = \sqrt{n}\, |n - 1\rangle
... a^\dagger |n\rangle = \sqrt{n + 1}\, |n + 1\rangle
... \langle n | (a + a^\dagger)^2 | n \rangle
... [\hat{x}, \hat{p}] = i\hbar
... [\hat{x}^3, \hat{p}] = 3i\hbar \hat{x}^2
... """)
[11, 2*n + 1, True]
```
## Other notation
`\langle j_1, j_2; m_1, m_2|j_1, j_2; j, m\rangle` is a Clebsch–Gordan coefficient, as
Sakurai writes it, and the physics and braket packages' `\ket`, `\bra`, `\braket`,
`\ketbra`, `\expval` and `\mel` read as what they print.
**Next:** [Tensors and geometry](tensors.md), or [Beyond spacetime](spaces.md), where
an index ranges over the states of a qubit.
# Tensors and geometry
> **For:** physicists computing with a metric. **You will learn:** how to define a
> metric, compute its curvature, write index notation by coordinate and by label, and
> what `=` means beside `:=`. **Before this:** [the language](language.md).
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook()
```
## Coordinates and the metric
Index notation needs coordinates; geometry needs a metric. Give the
coordinates, then the metric's components with both indices down:
```python
>>> wb.expr(r"""
... Coordinates := [t, r, \theta, \phi]
... g_{\mu\nu} := \begin{pmatrix}
... -(1 - \frac{2M}{r}) & 0 & 0 & 0 \\
... 0 & \frac{1}{1 - \frac{2M}{r}} & 0 & 0 \\
... 0 & 0 & r^2 & 0 \\
... 0 & 0 & 0 & r^2 \sin^2\theta
... \end{pmatrix}
... """)
```
A nested list works as well as a matrix, and so does `diag(...)`. A metric given
with both indices *up*, `g^{\mu\nu} := ...`, is inverted for you. Or write the
line element:
```python
>>> wb.expr(r"ds^2 = -(1 - \frac{2M}{r}) dt^2 + \frac{dr^2}{1 - \frac{2M}{r}} + r^2 d\Omega^2")
```
In a line element, `dt` or `d t` is the differential of the coordinate `t`, and
`d\Omega^2` is the solid angle element \(d\theta^2 + \sin^2\theta\, d\phi^2\).
A [spacetime](#spacetimes) brings its own coordinates: `g_{\mu\nu} := Kerr(M, a)`.
Without declared coordinates, a line element names them, in the order their
differentials first appear: `ds^2 = r^2 d\Omega^2 - dt^2 + dr^2` is in
\((\theta, \phi, t, r)\), so `g_{00}` is \(g_{\theta\theta}\). Declare
`Coordinates := [...]` first to fix the order. Written alone, `ds^2` is the line
element of the metric in force:
```python
>>> sphere = Workbook()
>>> sphere.exe(r"ds^2 = r^2 d\Omega^2 - dt^2 + dr^2" "\n" "Coordinates" "\n" "ds^2")
[[theta, phi, t, r], dphi**2*r**2*sin(theta)**2 + dr**2 - dt**2 + dtheta**2*r**2]
```
A metric is checked where it is defined. One with the wrong number of components,
one that is not symmetric, or one whose determinant is zero, as when a line element
leaves out a coordinate's differential, is refused there, with the reason; the
metric in force, if there is one, stays:
```python
>>> flat = Workbook()
>>> flat.exe(r"Coordinates := [t, r]" "\n" r"ds^2 = -dt^2")
Traceback (most recent call last):
...
relativisticpy.errors.MetricError: the metric is degenerate: its determinant is zero
--> :2:1
|
2 | ds^2 = -dt^2
| ^^^^^^^^^^^^
note: no term of it has dr
hint: give it a term with dr
```
`ds^2 = 0`, which says that a path is null, is a condition, read but not computed:
it defines no metric.
### Names defined after the metric
Papers often write a metric first and say what it is written with afterwards:
"\(ds^2 = -\Delta\, dt^2 + \Delta^{-1} dr^2 + r^2 d\Omega^2\), where
\(\Delta = 1 - 2M/r\)". A name or function the metric in force is written with, and
defined after it, takes that value in the metric from then on, so curvature computed
afterwards is that of the metric the paper means:
```python
>>> rn = Workbook()
>>> rn.exe(r"""
... ds^2 = -\Delta dt^2 + \Delta^{-1} dr^2 + r^2 d\Omega^2
... R_{abcd} R^{abcd}
... \Delta = 1 - \frac{2M}{r}
... R_{abcd} R^{abcd}
... """)
[(4*Delta**2 - 8*Delta + 4)/r**4, 48*M**2/r**6]
```
The same holds for a function, as \(f\) in `ds^2 = -f(r) dt^2 + \frac{dr^2}{f(r)} + ...`
followed by `f(r) = 1 - \frac{2M}{r}`, and for a definition written with `:=`. What
was computed before the definition stays as it was.
## Index notation
Indices go up with `^` and down with `_`. Inside braces each letter is its own
index, as in LaTeX, while Greek names stay whole: `_{ab}` is \(a, b\) and
`_{\mu\nu}` (or `_{mu nu}`) is \(\mu, \nu\). The plain-text style `_{a}_{b}` works
too.
An index repeated once up and once down is summed over (Einstein's
convention); the others are the result's free indices:
```python
>>> wb.expr(r"g_{ab} g^{bc}")
g_{ab} g^{bc} in (t, r, θ, φ): 4 of 16 components non-zero
g_{tb} g^{bt} = 1
g_{rb} g^{br} = 1
g_{θb} g^{bθ} = 1
g_{φb} g^{bφ} = 1
>>> wb.expr(r"g_{ab} g^{ab}")
4
```
Indices are raised and lowered with the metric automatically: ask for any
tensor with its indices wherever you need them. Before anything is computed,
the rules of index notation are checked, and a mistake is reported where it was
written:
```python
>>> wb.expr(r"R_{ab} R_{ab}")
Traceback (most recent call last):
...
relativisticpy.errors.IndexNotationError: index a appears twice as a lower index; a summed index must appear once up and once down
--> :1:1
|
1 | R_{ab} R_{ab}
| ^^^^^^^^^^^^^
```
## The built-in tensors
Once a metric is defined, these are available by name, recognised by name *and*
number of indices:
| Tensor | Written | Indices |
|---|---|---|
| metric | `g_{ab}`, `g^{ab}` | 2 |
| Christoffel symbols | `C^{a}_{bc}`, `\Gamma^{a}_{bc}` | 3 |
| Riemann tensor | `R^{a}_{bcd}` | 4 |
| Ricci tensor | `Ric_{ab}`, `R_{ab}` | 2 |
| Einstein tensor | `G_{ab}` | 2 |
| Weyl tensor | `W_{abcd}`, `C_{abcd}` | 4 |
| Kronecker delta | `\delta^{a}_{b}` | 2 |
| metric determinant | `g` | 0 |
| Ricci scalar | `Ric`, `R` | 0 |
| Kretschmann scalar | `Kretschmann` | 0 |
The conventions are those of Misner, Thorne & Wheeler and of Carroll:
$$
\Gamma^a{}_{bc} = \tfrac12 g^{ad}\left(\partial_b g_{dc} + \partial_c g_{db} - \partial_d g_{bc}\right)
$$
$$
R^a{}_{bcd} = \partial_c \Gamma^a{}_{db} - \partial_d \Gamma^a{}_{cb}
+ \Gamma^a{}_{ce}\Gamma^e{}_{db} - \Gamma^a{}_{de}\Gamma^e{}_{cb}
$$
$$
R_{bd} = R^a{}_{bad}, \qquad R = g^{bd} R_{bd}, \qquad G_{ab} = R_{ab} - \tfrac12 R\, g_{ab}
$$
```python
>>> wb.exe("R\nKretschmann\nG_{tt}")
[0, 48*M**2/r**6, 0]
```
`R` is the Ricci scalar unless your metric uses `R` as a symbol (the radius of a
sphere, say), in which case `R` stays a symbol, and a note says so wherever it is
read that way; `Ric` is always the Ricci scalar. Likewise `g` is the metric
determinant unless the metric uses `g`, when `\det(g_{\mu\nu})` still is. Spelled
out, as `RicciScalar` or `Riemann`, a built-in is no name of the language: it is a
symbol, with a note saying what to write. To rename a built-in, write
`MetricSymbol := G`; likewise
`ConnectionSymbol`, `RiemannSymbol`, `RicciSymbol`, `EinsteinSymbol`,
`WeylSymbol`, `DerivativeSymbol` and `CovariantDerivativeSymbol`.
With a metric in force, an equation about a built-in is a claim to check, never
a new definition: `R = 0` asks whether the Ricci scalar vanishes, and
`R_{\mu\nu} \equiv R^\alpha{}_{\mu\alpha\nu}`, as papers define the Ricci tensor,
checks that it is the contraction of the Riemann tensor:
```python
>>> wb.exe(r"""
... R = 0
... R_{\mu\nu} \equiv R^\alpha{}_{\mu\alpha\nu}
... """)
[True, R_{μν} = R^α{}_{μαν}: holds in all 10 components]
```
To give a built-in's name a meaning of your own, use `:=`.
## Components
An index can be fixed to a component, by number or by coordinate name. Writing a
coordinate's name as an index does the same:
```python
>>> wb.exe(r"""
... \Gamma^{r}_{\theta\theta}
... \Gamma^{a=1}_{b=2 c=2}
... C^{a:1}_{b:2 c:2}
... g_{01}
... """)
[2*M - r, 2*M - r, 2*M - r, 0]
```
Fixing some indices and not others gives the rest as a tensor:
```python
>>> print(wb.expr(r"\Gamma^{r}_{t b}"))
Γ^r_{t b} in (t, r, θ, φ): 1 of 4 components non-zero
Γ^r_{t t} = M (r − 2M)/r³
```
A sum with whole-number limits is carried out, component by component for a
tensor, so `\sum_{n=0}^{2} R_{\mu\nu}` is zero here; one to infinity, or to a
symbol, is its closed form where SymPy finds one, and is otherwise kept as written.
## Defining tensors
Define a tensor from its components, or from an expression in other tensors.
The free indices on the right must match the left, in any order:
```python
>>> wb.expr(r"""
... u^{\mu} := [1/\sqrt{1 - 2M/r}, 0, 0, 0]
... u_{\mu} u^{\mu}
... """)
-1
>>> wb.expr(r"""
... T^{\mu\nu} := (\rho + p) u^\mu u^\nu + p g^{\mu\nu}
... T^{\mu}{}_{\mu}
... """)
3*p - rho
```
## What `=` means
Papers use `=` both to define and to claim, so RelativisticPy decides by what the
left side already means. `:=` (or `\equiv`, `\coloneqq`) always defines, or
redefines. `=` defines only what has no meaning yet:
| You write | When | It means |
|---|---|---|
| `x = 2`, `f(x) = x^2`, `T_{\mu\nu} = \ldots` | the name has no meaning yet | a definition |
| `ds^2 = \ldots` | always | the metric, from its line element |
| `\Delta = \ldots` | the metric in force is written with \(\Delta\) | a definition, which the metric takes ([above](#names-defined-after-the-metric)) |
| `K = \ldots`, `u^\mu = \ldots`, `f(x) = \ldots` | it already has a value | a claim, checked |
| `R = 0`, `R_{\mu\nu} = 0`, `g_{\mu\nu} = \ldots` | it is built in, or the metric in force | a claim, checked |
| `g_{tt} = \ldots`, `f(2) = 4` | a component, or a value | a claim, checked |
| `\pi = 3.14159` | a constant | a claim, checked |
| `R = \frac{2}{R^2}` | the name is in its own value | an equation, never a definition |
| `t = 0`, `ds^2 = 0`, `(k = 0)` | a coordinate in force, a null path, a case in brackets | a condition, read but not computed |
A claim where a definition could have been meant says so, in a note on its step
(see [Python](python.md)):
```python
>>> claims = Workbook()
>>> claims.exe("K := 48\nK = 47")
[False]
>>> [step.notes for step in claims.each("K = 48")]
[['K already has a value, so = compares it; to give K a new value, write K := ...']]
>>> claims.exe("K := 47\nK")
[47]
```
So retyping a corrected tensor, `u^\mu = [2, 0]` after `u^\mu = [1, 0]`, compares
the two rather than overwriting the first; an equation about a component, such as
`g_{tt} = -(1 - 2M/r)`, neither replaces the metric nor defines a new tensor's every
component; and `R = 0` written before any metric is the equation \(R = 0\) of
[index notation](notation.md), not a new meaning for \(R\).
A letter followed by brackets could be a function or a product. A constant, or a
name the statement also writes as a factor, as \(G\) is in
`\frac{2GM}{r} + G(p^2 + q^2)`, where in LaTeX \(2GM\) is \(2 \cdot G \cdot M\),
multiplies what is in the brackets; so does a name written as a factor before, where
the brackets hold more than names, as \(\rho\) does in `\rho(1 + 3w)` after
`p = w\rho`. Otherwise a letter that means nothing is an unknown function: of
names, as `\alpha(t, r)`, without a word; of anything else, with a note saying how
to write the product:
```python
>>> claims.expr(r"\frac{2GM}{r} + G(p^2 + q^2)")
2*G*M/r + G*(p**2 + q**2)
>>> [step.notes for step in claims.each(r"\gamma(t - v x)")]
[['\\gamma is not defined, so \\gamma(t - v x) is an unknown function applied to t - v x; for a product, write \\gamma \\cdot (t - v x)']]
```
## Derivatives
`\partial_\mu` (or `d_{\mu}`) is the partial derivative and `\nabla_\mu` (or
`D_{\mu}`) the covariant derivative. Each acts on the factor written after it,
so \(\partial_\mu \phi\, \partial^\mu \phi\) means
\((\partial_\mu\phi)(\partial^\mu\phi)\); use brackets for more. The comma and
semicolon notations mean the same: `T^{\mu\nu}{}_{;\nu}` is \(\nabla_\nu T^{\mu\nu}\).
They apply to a scalar too, one you define, a built-in one such as `R`, or a
function of the coordinates: `\phi_{,\mu}` is \(\partial_\mu \phi\) and
`\phi_{;\mu}{}^{;\mu}` is \(\Box\phi\). A name with no value has no derivative, so
that is an error.
```python
>>> [tensor.nonzero() for tensor in wb.exe(r"""
... \nabla_\lambda g_{\mu\nu}
... \nabla_\mu G^{\mu\nu}
... """)]
[{}, {}]
```
(No nonzero components: the metric is covariantly constant, and the Einstein
tensor is conserved.)
Components are taken after the derivative: \(\nabla_\mu T^{\mu t}\) is the \(t\)
component of \(\nabla_\mu T^{\mu\nu}\), which involves every component of
\(T\). A component chosen inside the operand, as in `\nabla_\mu (A^{\mu} B^{t})`,
is an error rather than a guess; define the operand as a tensor first.
A Leibniz derivative such as `\frac{d}{dx}` acts on the rest of the term:
`\frac{d}{dx} x^2 y` is \(\frac{d}{dx}(x^2 y)\).
A number on `\partial` or `\nabla` is the order of the derivative, never an
index: `\partial_t^2` and `\partial^2_t` are \(\partial_t \partial_t\). With no
index, `\partial^2` is \(\partial^\mu \partial_\mu\), and `\nabla^2` is
\(\nabla^\mu \nabla_\mu\), the same as `\Box`: the Laplacian of the metric in
force, which in spacetime is the d'Alembertian. (Some texts write
\(\nabla^2\) for the Laplacian of space alone, as in \(\Box = -\partial_t^2 +
\nabla^2\); RelativisticPy's is that of all the coordinates.)
```python
>>> flat = Workbook()
>>> flat.exe(r"""
... ds^2 = -dt^2 + dx^2 + dy^2 + dz^2
... \partial^2_t (t^3) = \partial_t \partial_t (t^3)
... \nabla^2 (x^2 + y^2 + z^2 - t^2)
... """)
[True, 8]
```
On a tensor with one index, a number written bare above it, as in `k^3`, could be
a component or a power, so it is refused; in braces, `k^{3}` is the component,
and `k_{a} k^{a}` is \(k\) contracted with itself. (`k^0` and `k^1` are
components: neither is a power anyone writes.)
```python
>>> flat.exe(r"""
... k^\mu := [\omega, 0, 0, \omega]
... k^{3}
... k_{a} k^{a}
... """)
[omega, 0]
>>> flat.exe("k^3")
Traceback (most recent call last):
...
relativisticpy.errors.IndexNotationError: k is a tensor, so k^3 could be its component with upper index 3 or a power of it
...
```
## Symmetrisation
Round brackets symmetrise and square brackets antisymmetrise, as in
`T_{(ab)}` and `F_{[\mu\nu]}`. A bracket takes the indices at the level it opens
at: `T_{(a}{}^{b}{}_{c)}` symmetrises \(a\) and \(c\), and leaves \(b\) alone. The
brackets may span several tensors, which is how the second Bianchi identity is
written:
```python
>>> wb.expr(r"\nabla_{[\lambda} R_{\rho\sigma]\mu\nu} = 0")
∇_{[λ} R_{ρσ]μν} = 0: holds in all 200 components
```
## Tensor equations
With a metric in force, an equation between tensors stands for one equation per
component. Those that do not hold identically are listed, ready to solve. (To
rearrange and solve an equation between tensors as an equation, before there
are components, see [Solving tensor equations](notation.md).) Here are the vacuum field
equations for a general static, spherically symmetric metric:
```python
>>> fresh = Workbook()
>>> equations = fresh.expr(r"""
... Coordinates := [t, r, \theta, \phi]
... g_{\mu\nu} := diag(-e^{2 \alpha(r)}, e^{2 \beta(r)}, r^2, r^2 \sin^2\theta)
... R_{\mu\nu} = 0
... """)
>>> len(equations.equations())
4
>>> fresh.expr(r"dsolve(R_{tt} + e^{2 \alpha(r) - 2 \beta(r)} R_{rr} = 0, \beta(r))")
Eq(beta(r), C1 - alpha(r))
```
## Spacetimes
Each of these is a function returning a metric, used as
`g_{\mu\nu} := Schwarzschild(M)`. Parameters are symbols or numbers, and a
decimal is the exact fraction it denotes, so `Schwarzschild(1.7)` is exactly a
vacuum. Units are geometric (\(G = c = 1\)) unless `G` and `c` follow a
spacetime's own parameters, as in `Schwarzschild(M, G, c)`. A parameter left out
is the symbol the table names it with: `Kerr(M)` is `Kerr(M, a)`, and
`Schwarzschild()` is `Schwarzschild(M)`. The scale factor of `FLRW(k, a)` may be
named, and is then a function of \(t\), or given as an expression of \(t\). A name
that is not a spacetime is refused where the metric is defined, with the closest
spacetime's name:
```python
>>> Workbook().exe(r"g_{\mu\nu} := Schwarzchild(M)")
Traceback (most recent call last):
...
relativisticpy.errors.CompileError: unknown spacetime Schwarzchild
--> :1:15
|
1 | g_{\mu\nu} := Schwarzchild(M)
| ^^^^^^^^^^^^
note: the spacetimes are Minkowski, Schwarzschild, ReissnerNordstrom, Kerr, KerrNewman, FLRW, DeSitter and AntiDeSitter
hint: did you mean Schwarzschild(M)?
```
| Function | Spacetime |
|---|---|
| `Minkowski()` | flat spacetime, \((t, x, y, z)\) |
| `Schwarzschild(M)` | static black hole |
| `ReissnerNordstrom(M, Q)` | charged black hole |
| `Kerr(M, a)` | rotating black hole, Boyer–Lindquist coordinates |
| `KerrNewman(M, a, Q)` | rotating, charged black hole |
| `FLRW(k, a)` | homogeneous, isotropic universe with scale factor \(a(t)\) |
| `DeSitter(L)`, `AntiDeSitter(L)` | constant curvature, radius \(L\) |
```python
>>> cosmos = Workbook()
>>> cosmos.expr(r"g_{\mu\nu} := FLRW(k)" "\n" r"G^{t}{}_{t}")
-3*(k + Derivative(a(t), t)**2)/a(t)**2
```
That is the first Friedmann equation, \(3(\dot a^2 + k)/a^2 = 8\pi G \rho\),
waiting for its right-hand side.
## Geodesics
`geodesic_equations(\tau)` gives the geodesic equations for the metric in
force, with each coordinate a function of the affine parameter \(\tau\). To
integrate them numerically, which is done from Python, with
`relativisticpy.numeric.geodesic`, see [Numerics](numerics.md); `geodesic(...)` in
the language says so.
```python
>>> wb.expr(r"geodesic_equations(\tau)")[2]
Eq(-sin(theta(tau))*cos(theta(tau))*Derivative(phi(tau), tau)**2 + Derivative(theta(tau), (tau, 2)) + 2*Derivative(r(tau), tau)*Derivative(theta(tau), tau)/r(tau), 0)
```
The same equations come from a Lagrangian. A derivative with respect to a
vector, \(\partial L / \partial \dot x^\mu\), has an index of its own:
```python
>>> lagrangian = Workbook()
>>> euler_lagrange = lagrangian.expr(r"""
... g_{\mu\nu} := Schwarzschild(M)
... x^{\mu} := [t(\tau), r(\tau), \theta(\tau), \phi(\tau)]
... L := g_{\mu\nu} \dot{x}^\mu \dot{x}^\nu |_{t=t(\tau), r=r(\tau), \theta=\theta(\tau), \phi=\phi(\tau)}
... \frac{d}{d\tau} \frac{\partial L}{\partial \dot{x}^\mu} - \frac{\partial L}{\partial x^\mu}
... """)
>>> euler_lagrange.indices
Indices('_{\\mu}')
```
## Performance
Geometric quantities are computed once per metric and cached, using their
symmetries (Christoffel symbols for \(b \le c\), Riemann components for
\(c < d\)). Simplifying components is the expensive part, and
`Workbook(workers=N)` (or `relativisticpy -j N`) spreads it over processes.
Results that vanish are recognised exactly by algebra alone (see
[How it works](architecture.md#simplification)), which is why checking that the
Kerr metric solves the vacuum equations takes seconds.
Some times, measured on an eight-core laptop processor (AMD Ryzen 7 8745HS):
| | One worker | Eight workers |
|---|---|---|
| A sum of 1,000 fractions, and its derivative | 0.4 s, 1.1 s | |
| Christoffel symbols to the Kretschmann scalar, for Schwarzschild, Reissner–Nordström, FLRW or a general spherically symmetric metric | 0.2 to 0.6 s | |
| The Christoffel symbols of Kerr | 3.5 s | 1.6 s |
| `R_{\mu\nu} = 0` for Kerr, a vacuum solution | 14 s | 5.4 s |
| The Ricci tensor of Kerr–Newman | 47 s | 49 s |
| Carroll's lecture notes, checked whole | 4 s | |
Some quantities are far harder. The full Riemann tensor of Kerr, simplified
component by component, takes more than a quarter of an hour even with eight
workers, because a few of its components take that long on their own. Ask for
what you need: the vacuum equations need only the Ricci tensor, which is
computed straight from the connection.
**Next:** [Solving tensor equations](notation.md), to work with equations before their
components are known, or [the language reference](reference.md).
# Solving tensor equations
> **For:** anyone working with tensor equations before their components are known.
> **You will learn:** how equations in index notation are kept, solved, traced,
> simplified and substituted into. **Before this:** [tensors and
> geometry](tensors.md).
Components answer *what is this tensor here?* Index notation answers *what does
this equation say?* RelativisticPy works at both levels. An equation with a
tensor that has no components yet, such as the energy–momentum tensor
\(T_{\mu\nu}\), is kept as an equation between tensors. It can be rearranged,
traced, simplified and solved as on paper, and turned into components later,
once there is a metric.
## Einstein's equations, solved
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook()
>>> wb.exe(r"EFE := G_{\mu\nu} + \Lambda g_{\mu\nu} = 8\pi G T_{\mu\nu}")
[]
>>> wb.expr("EFE")
IndexEquation(G_{μν} + Λ g_{μν} = 8π G T_{μν})
>>> wb.expr(r"solve(EFE, T_{\mu\nu})")
IndexEquation(T_{μν} = (G_{μν} + Λ g_{μν})/(8π G))
>>> wb.expr(r"solve(EFE, T^{\mu\nu})")
IndexEquation(T^{μν} = (G^{μν} + Λ g^{μν})/(8π G))
```
Solving for the Ricci tensor takes more than moving terms across, because the
Einstein tensor \(G_{\mu\nu} = R_{\mu\nu} - \frac{1}{2} R g_{\mu\nu}\) contains
its trace, \(R\). `solve` traces the equation, solves the trace for \(R\) and
substitutes it back. This is trace reversal:
```python
>>> wb.expr("trace(EFE)")
IndexEquation(4Λ − R = 8π G T)
>>> wb.expr("solve(trace(EFE), R)")
IndexEquation(R = 4Λ − 8π G T)
>>> wb.expr(r"solve(EFE, R_{\mu\nu})")
IndexEquation(R_{μν} = 8π G T_{μν} + (Λ − 4π G T) g_{μν})
```
As in papers, \(T\) without indices is the trace \(T^\mu{}_\mu\). Equations
compare by what they say, so the solution equals the form in textbooks:
```python
>>> wb.expr(r"solve(EFE, R_{\mu\nu})") == wb.expr(
... r"R_{\mu\nu} = \Lambda g_{\mu\nu} + 8\pi G \left(T_{\mu\nu} - \frac{1}{2} T g_{\mu\nu}\right)")
True
```
## The operations
| Operation | What it does |
|---|---|
| `solve(E, T_{\mu\nu})` | solve an equation for a tensor, with its indices up or down. The equation must be linear in the tensor; its trace may appear too. An equation of scalars, as a trace is, is solved for a scalar, as in `solve(trace(E), R)` |
| `trace(E)` | contract the two free indices of an equation, or an expression, with the metric |
| `simplify(E)` | the canonical form, under the tensors' symmetries and the identities below |
| `subs(E, rule)` | apply a rule: a definition, a contraction, or a value for a scalar such as `\Lambda = 0` |
| `LHS(E)`, `RHS(E)` | one side of an equation |
A rule given to `subs` applies whatever its indices are called, and in either
position. It may be a definition, such as that of the Einstein tensor:
```python
>>> wb.expr(r"subs(EFE, G_{ab} = R_{ab} - \frac{1}{2} R g_{ab})")
IndexEquation(R_{μν} + (Λ − R/2) g_{μν} = 8π G T_{μν})
```
A rule for a scalar puts its value into the coefficients:
```python
>>> wb.expr(r"subs(EFE, \Lambda = 0)")
IndexEquation(G_{μν} = 8π G T_{μν})
```
It may also be a contraction. Here is the energy density that an observer moving
with a perfect fluid measures:
```python
>>> fluid = r"((\rho + p) u^\mu u^\nu + p g^{\mu\nu}) u_\nu"
>>> wb.expr(rf"subs({fluid}, u^\alpha u_\alpha = -1)")
IndexExpression(−ρ u^μ)
```
## What simplify knows
Canonical forms come from SymPy's implementation of the Butler–Portugal
algorithm. It knows each tensor's symmetries and renames dummy indices, so
\(T_{\mu\alpha} u^\alpha\) and \(T_{\mu\beta} u^\beta\) are the same term.
RelativisticPy adds the identities of General Relativity:
- the symmetries of the Riemann tensor, and the first Bianchi identity,
\(R_{\rho[\sigma\mu\nu]} = 0\), also where its indices are contracted, as in
\(R_{\rho[\sigma\mu\nu]} u^\nu = 0\);
- its contractions: \(R^\alpha{}_{\mu\alpha\nu} = R_{\mu\nu}\),
\(R^\mu{}_\mu = R\) and \(G^\mu{}_\mu = (1 - n/2) R\) in \(n\) dimensions;
- the Weyl tensor is traceless; \(g^\mu{}_\mu = n\), and the metric with one
index up is \(\delta^\mu{}_\nu\);
- the trace of a tensor \(T_{\mu\nu}\) of your own is written \(T\).
```python
>>> wb.expr(r"simplify(R_{\rho\sigma\mu\nu} + R_{\rho\mu\nu\sigma} + R_{\rho\nu\sigma\mu})")
IndexExpression(0)
>>> wb.expr(r"simplify(R^{\alpha}{}_{\mu\alpha\nu} - R_{\nu\mu})")
IndexExpression(0)
>>> wb.expr(r"simplify(G^\mu{}_\mu)")
IndexExpression(−R)
```
## Identities
Without a metric there are no components, so an equation between tensors can
only be notation. `holds()` says whether it is an identity:
```python
>>> identities = Workbook()
>>> identities.expr(r"G_{\mu\nu} = R_{\mu\nu} - \frac{1}{2} R g_{\mu\nu}").holds()
True
>>> identities.expr(r"g^{\mu\nu} g_{\nu\sigma} = \delta^\mu_\sigma").holds()
True
>>> identities.expr(r"R_{\mu\nu} = 0").holds()
False
```
The last is a field equation, not an identity. When a paper is
[checked](checking.md), identities in index notation are verified this way. Without
a metric, `R` is the Ricci scalar of the notation, so `R = -\kappa T` is an equation
of notation, not a new meaning for `R` (see [What `=` means](tensors.md#what-means)).
Index notation has rules: an index appears once in a term, or twice to be
summed, once up and once down; and every term has the same free indices.
RelativisticPy checks them before anything is computed:
```python
>>> wb.expr(r"G_{\mu\nu} = 8\pi T_{\mu\nu\rho}")
Traceback (most recent call last):
...
relativisticpy.errors.IndexNotationError: the two sides have different free indices: _{\mu\nu} on the left, _{\mu\nu\rho} on the right
--> :1:1
|
1 | G_{\mu\nu} = 8\pi T_{\mu\nu\rho}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
An equation that breaks the rules may still be about components. Papers write
\(\Gamma^\theta_{r\theta} = 1/r\), with \(r\) and \(\theta\) naming
coordinates, so such an equation is read as a statement about components, which
needs a metric. So is any equation whose indices are the coordinates in force.
## From notation to components
Notation turns into components where it meets them. With a metric in force,
defining a tensor by notation gives its components. Here the field equations,
solved for \(T_{\mu\nu}\) in an FLRW universe, give its energy density:
```python
>>> cosmos = Workbook()
>>> cosmos.exe(r"""
... ds^2 = -dt^2 + a(t)^2 \left(\frac{dr^2}{1 - k r^2} + r^2 d\Omega^2\right)
... EFE := G_{\mu\nu} + \Lambda g_{\mu\nu} = 8\pi G T_{\mu\nu}
... T_{\mu\nu} := RHS(solve(EFE, T_{\mu\nu}))
... """)
[]
>>> cosmos.expr(r"T_{tt}")
-Lambda/(8*pi*G) + 3*(k + Derivative(a(t), t)**2)/(8*pi*G*a(t)**2)
```
That is the first Friedmann equation, \(8\pi G \rho = 3(\dot a^2 + k)/a^2 -
\Lambda\). The trace-reversed equations, solved as notation, then hold
component by component:
```python
>>> cosmos.expr(r"R_{\mu\nu} = RHS(solve(EFE, R_{\mu\nu}))")
R_{μν} = RHS(solve(EFE, R_{μν})): holds in all 10 components
```
## Not yet
Derivatives are not yet part of the notation. \(\nabla_\mu T^{\mu\nu} = 0\)
works on components, with a metric, but cannot yet be rearranged as notation.
Nor can a tensor be defined abstractly, as
\(T_{\mu\nu} := (\rho + p) u_\mu u_\nu + p g_{\mu\nu}\) with a velocity \(u\)
that has no components. Both are on the [roadmap](roadmap.md).
**Next:** [Checking papers](checking.md), to run a paper's equations, or [the language
reference](reference.md).
# Checking papers
> **For:** authors and readers of papers, and anyone who checks them in continuous
> integration. **You will learn:** how to check a LaTeX document or a Markdown notebook,
> what each verdict means, and how to read a report from Python. **Before this:**
> [LaTeX](latex.md).
A paper is a program whose statements are its display equations.
`relativisticpy check` runs them in order, as a reader would, and says what
became of each: which hold, which do not, which relate quantities the paper never
defines, and which it could not read.
```bash
relativisticpy check notes.tex # the whole document
relativisticpy check notes.tex --lines 9058:9112 # one passage
relativisticpy check notes.tex --all # every statement, with reasons
relativisticpy check notes.tex --time-limit 60 # seconds for each statement; inf for none
relativisticpy check notes.tex -j 4 # four processes for component-wise work
relativisticpy check notes.tex --strict # fail on what is listed as failing
relativisticpy check notebook.md # a Markdown notebook
```
A statement gets 30 seconds by default, to be computed and judged; one that takes
longer is not computed. The command exits with status 0 whatever it finds, unless
it is given `--strict`: then an equation that differs, notation that is ill-formed,
a statement that cannot be parsed or is over its time limit, or a document in which
no equation was found, makes it exit with status 1, for a continuous integration job
to act on.
## An example
Here is a short passage in the style of a textbook, with a mistake in one of its
equations:
```python
>>> from relativisticpy import Workbook
>>> from relativisticpy.documents import Document
>>> paper = Document(r"""
... \newcommand{\be}{\begin{equation}}
... \newcommand{\ee}{\end{equation}}
... A static, spherically symmetric spacetime has the line element
... \be ds^2 = -e^{2\alpha(r)}{\rm d} t^2 + e^{2\beta(r)}{\rm d} r^2 + r^2 d\Omega^2 \ , \ee
... whose connection includes
... \begin{eqnarray}
... \Gamma^1_{00} &=& e^{2(\alpha-\beta)}\partial_1\alpha \ , \cr
... \Gamma^1_{22} &=& -r e^{-2\beta} \ , \qquad \Gamma^3_{23} = {\cos\theta \over \sin\theta} \ .
... \end{eqnarray}
... Its curvature has
... \be R_{22} = e^{-2\beta}[r(\partial_1\alpha - \partial_1\beta) - 1] + 1 \ . \ee
... A body in orbit has
... \be \omega^2 = \frac{G M}{r^3} \ . \ee
... """, "paper.tex")
>>> report = Workbook().check(paper)
>>> print(report.describe())
paper.tex: 4 equations, 6 statements, checked in ... s
✓ holds 3 proven equal
✗ differs 1 of known quantities, whose sides are not equal: a mistake, or a condition
↔ relates 1 relations between quantities nothing defines, not identities
= defines 1 definitions
paper.tex:12:5: ✗ differs R_{22} = e^{-2\beta}[r(\partial_1\alpha - \partial_1\beta) - 1] + 1
the left side minus the right is (2r β'(r) − 2r α'(r)) e^(−2 β(r))
Not listed: 3 holds, 1 relates, 1 defines. --all lists every statement.
```
Nothing was declared. The line element named the coordinates t, r, θ and φ,
`\alpha(r)` made `\alpha` a function of r from then on, `0` and `1` in
`\Gamma^1_{00}` are the coordinates t and r, and the `\qquad` separated two
equations. The sign in R₂₂ should be the other way round: every quantity in it is
known, so the difference of its sides is a mistake, or a condition the passage has
not stated. The orbit's ω, G and M are defined nowhere, so that equation relates
them; it is not an identity, and not a mistake either.
`Workbook.check` takes a `Document`, the text of a document, or the path of a LaTeX
file or a Markdown notebook; text with a line break or a `\begin` that is not the
path of a file is read as a document. A file must be UTF-8. It takes optionally
`lines`, a part of the document, and a `time_limit` in seconds for each statement.
The document runs in a workbook of its own, with the same workers, so the workbook's
definitions take no part and are kept. Whatever fails in one statement is a finding
about it, and the check goes on.
## Verdicts
| Mark | Verdict | Meaning | Fails `--strict` |
|---|---|---|---|
| ✓ | holds | proven equal: component by component, or, for an equation in [index notation](notation.md) without components, as notation. If both sides are zero the finding says so: such an equation may hold only because space is flat there, or its quantities are not yet defined | no |
| ✗ | differs | every quantity is known, and the sides are not equal: a mistake, or a condition such as an equation of motion the text has not stated. The finding shows the difference of the sides, or, for tensors, in how many components they differ and the first few | yes |
| ↔ | relates | the sides involve quantities nothing defines: not a coordinate, not a name the metric is written with, not declared or defined before. It is a relation to solve, such as a law or Einstein's equation, not an identity. An equation for functions nothing defines relates too, even of those a metric is written with, as \(\partial_0\beta = 0\) of \(\beta(t, r)\), unless it writes a quantity computed from the metric, as \(R_{00}\). The finding names those quantities | no |
| ✗ | ill-formed | the notation breaks the rules of index notation, as written: an index three times in one term, a Greek index twice up or twice down, or terms or sides whose free indices differ. Only plain notation is judged, so the paper is never blamed for what RelativisticPy may have read otherwise | yes |
| = | defines | a definition, which the equations after it use | no |
| → | computes | an expression, computed | no |
| ~ | not computed | a relation that RelativisticPy reads but does not decide, such as ≈, ∝ or →; a condition on a coordinate; an equation that is neither proven nor shown to differ; a division by zero; or a statement over its time limit | yes, for the time limit |
| ? | not understood | something RelativisticPy cannot do yet, such as the derivative of an abstract tensor, with the reason. A failure of RelativisticPy's own is an internal error, which invites a report | no |
| ! | not parsed | not read, with the reason, the place and a hint | yes |
An equation holds when it is proven. Its sums, products and integrals are carried
out, and the difference of its sides must vanish, exactly or, between
floating-point numbers, to a relative 10⁻¹²: `0.1 + 0.2 = 0.3` holds. When no
proof is found, numbers tell the other two cases apart. The symbols are given
positive values, and functions that nothing defines, such as `\alpha(r)`, random
polynomials. An equation whose sides differ wherever they are tried differs, or
relates if a quantity in it is defined nowhere; one whose sides agree, as
\(\sqrt{x^2} = x\) does for positive x, or cannot be computed, is not decided. A
side that is exactly zero has no size for a floating-point number to be compared
with, so `0.1 + 0.2 - 0.3 = 0` differs.
## The report
The report begins with a summary: how many statements met each verdict, what each
verdict means, the commonest reasons statements were not understood, and how long
the check took. It then lists what fails, each finding located as `paper.tex:12:5`,
which terminals and editors link to, with the statement as the file has it, the
reason, the hint and, for a statement that could not be read, the place in it where
reading failed. It ends by counting what it did not list. Nothing is cut short,
unless the report is given the width of a terminal, to wrap its lines to.
```python
>>> print(report.describe(all=True))
paper.tex: 4 equations, 6 statements, checked in ... s
✓ holds 3 proven equal
✗ differs 1 of known quantities, whose sides are not equal: a mistake, or a condition
↔ relates 1 relations between quantities nothing defines, not identities
= defines 1 definitions
paper.tex:5:5: = defines ds^2 = -e^{2\alpha(r)}{\rm d} t^2 + e^{2\beta(r)}{\rm d} r^2 + r^2 d\Omega^2
paper.tex:8:3: ✓ holds \Gamma^1_{00} &=& e^{2(\alpha-\beta)}\partial_1\alpha
paper.tex:9:3: ✓ holds \Gamma^1_{22} &=& -r e^{-2\beta}
paper.tex:9:47: ✓ holds \Gamma^3_{23} = {\cos\theta \over \sin\theta}
paper.tex:12:5: ✗ differs R_{22} = e^{-2\beta}[r(\partial_1\alpha - \partial_1\beta) - 1] + 1
the left side minus the right is (2r β'(r) − 2r α'(r)) e^(−2 β(r))
paper.tex:14:5: ↔ relates \omega^2 = \frac{G M}{r^3}
nothing defines G, M and ω: the left side minus the right is ω² − G M/r³
```
From Python, a `Report` is a sequence of `Finding`s, and a `Verdict` is its name,
so that `report.count("differs")` counts. `report.ok` says whether the check passes
`--strict`, and `report.failed(...)` whether it fails a policy of one's own, such
as only mistakes. `report.to_dict()` gives the whole report as data, for JSON:
```python
>>> report.count("differs"), report.ok, report.failed({"ill-formed", "not parsed"})
(1, False, False)
>>> [finding.verdict for finding in report]
['defines', 'holds', 'holds', 'holds', 'differs', 'relates']
>>> mistake = report.findings[4]
>>> mistake.location, mistake.text
('paper.tex:12:5', 'R_{22} = e^{-2\\beta}[r(\\partial_1\\alpha - \\partial_1\\beta) - 1] + 1')
>>> sorted(report.to_dict())
['context', 'counts', 'equations', 'file', 'findings', 'lines', 'ok', 'reasons', 'seconds', 'statements', 'warnings']
```
Each finding, as data, has its verdict, its file, line and column, the statement
as written, the reason, the hint and notes, the difference of the sides in each of
the forms results are shown in, and the `error` the statement raised, if it raised one,
as `error.to_dict()` gives it.
## Part of a document
`--lines FIRST:LAST`, or `lines=(first, last)` from Python, checks a passage. What
comes before it in its section still runs first, so that its definitions are known,
as a reader who opens a book at a page has read the pages before it; only the
statements in the lines are reported. An environment that reaches into the lines
counts, as the `eqnarray` above, which starts on line 7, does for its rows:
```python
>>> passage = Workbook().check(paper, lines=(9, 13))
>>> [(finding.line, finding.verdict) for finding in passage]
[(9, 'holds'), (9, 'holds'), (12, 'differs')]
>>> print(passage.describe().splitlines()[-1])
Also run, for their definitions, and not reported: 2 statements outside lines 9–13.
```
From Python, `lines` may also be one line, `lines=12`, or open at either end,
`lines=(9, None)`.
## How a document is read
- **Display equations**: `equation`, `eqnarray`, `align`, `gather`,
`multline`, `$$...$$` and `\[...\]`, including the shorthands authors define
for them, such as `\be ... \ee`.
- **Macros**: the document's `\newcommand`, `\def` (with arguments),
`\DeclareMathOperator` and `\let` are expanded, as are those of its local
packages and the files it includes.
- **Order and scope**: equations run in order, so definitions carry forward.
Each `\section` or `\chapter` starts afresh, because texts reuse symbols:
Ω is a solid angle in one chapter and a density in the next.
- **Positions**: findings give the file's own line numbers.
## Reading physics as it is written
Texts leave a great deal implicit, and RelativisticPy reads it the way a
physicist does:
- **A line element names its coordinates**: `-dt^2 + dr^2 + r^2 d\Omega^2` is
in t, r, θ and φ, unless coordinates were declared.
- **A function written once with its arguments**, `\alpha(t, r)`, is that
function wherever `\alpha` appears afterwards.
- **Numbered indices are components**: `\Gamma^0_{00}`, `R^1{}_{212}`,
`\partial_0 \alpha`. `\partial_0^2 \beta` is `\partial_0 \partial_0 \beta`.
- **Derivations are chains**: `a = b = c`, and rows that continue with `&=&`,
give one claim per link.
- **Letters are symbols**: `re^{-2\beta}` is \(r\,e^{-2\beta}\), `2Gm(r)` is
\(2G\,m(r)\), and with r a coordinate, `r(\partial_1\beta - 1)` is a product.
- **Sentences around equations**: closing punctuation is ignored, while commas,
`\quad`, `\qquad` and `\Rightarrow` separate equations.
The [LaTeX page](latex.md#notation-from-papers) lists the notation in full.
## Carroll's lecture notes
Sean Carroll's *Lecture Notes on General Relativity*
([arXiv:gr-qc/9712019](https://arxiv.org/abs/gr-qc/9712019)) are the
benchmark for this feature. Of their 797 display equations, 786 (98.6%)
parse. The other eleven are words laid out as matrices, integrals over
\(d^n\eta\) or with their differential on another line, `<<` for "much less
than", a primed index, and \(\exp_p\). Checked from end to end, in about seventeen
seconds, 139 statements hold, 98 of them with sides that are not both zero.
The notes' chapter on the Schwarzschild solution makes 25 claims about the
general spherically symmetric metric: twelve Christoffel symbols, eight
components of the Riemann tensor and five of the Ricci tensor, in equations
(7.14) to (7.16). RelativisticPy confirms 24 of them. The 25th is an error in
the notes. In R₀₀, the bracket of time derivatives
\(\partial_0^2\beta + (\partial_0\beta)^2 - \partial_0\alpha\,\partial_0\beta\)
should carry a minus sign. A calculation from first principles, independent of
RelativisticPy's own curvature code, agrees. The slip is harmless: the notes
show next that \(\partial_0\beta = 0\), which removes the bracket.
A few pages later, (7.30) gives the Kretschmann scalar of the Schwarzschild
metric as \(12G^2M^2/r^6\). The check finds \(48G^2M^2/r^6\), the established
value. The conclusion drawn from it, that \(r = 0\) is a true singularity,
stands.
Both findings take four commands to reproduce. Download the LaTeX source of the notes
from arXiv, unpack `grnotes.tex`, and check two passages of it:
```bash
curl -L -o carroll.tar.gz https://arxiv.org/e-print/gr-qc/9712019
tar -xzf carroll.tar.gz grnotes.tex
relativisticpy check grnotes.tex --lines 9058:9112 # equations (7.13) to (7.16)
relativisticpy check grnotes.tex --lines 9284:9287 # equation (7.30)
```
The first passage takes about a second: 24 statements hold, and R₀₀, on line 9102,
differs. In the second, the left side of (7.30) minus its right is
\(36G^2M^2/r^6\). Each check runs what comes before its lines in their section, for
its definitions, and reports only the lines.
In all, 6 statements differ. Besides these two, (7.21), on line 9161, is a chain
of two links. The first, \(0 = e^{2(\beta-\alpha)}R_{00} + R_{11}\), is the
vacuum condition, which the prose states in words, "both \(R_{00}\) and \(R_{11}\)
vanish": no check of the equation alone can tell it from an identity that fails. The
second holds for the metric \(e^{2\beta(r)}\,dr^2\) of (7.13), but not for (7.20)
just before it, which writes \(e^{\beta(r)}\,dr^2\): another slip. The last two are
(3.77), on line 4413, the Riemann tensor in Riemann normal coordinates. It holds
at the point where those coordinates are set up, where the Christoffel symbols
vanish, and the check takes it over the metric in force, the plane in polar
coordinates, where they do not.
Of the 210 statements that relate, most relate quantities the notes never define, as
laws, equations of motion and the interval \(s^2 = (\Delta x)^2 + (\Delta y)^2\) do.
The steps the notes derive from \(R_{\mu\nu} = 0\), as \(\partial_0\beta = 0\) and
\(\alpha = -\beta\), relate too: each is an equation for the functions the metric is
written with, and the check reads it so. One equation is ill-formed: (1.56) writes
\(\eta_{\rho\nu}\eta^{\nu\mu} = \delta^\rho_\mu\), whose free indices call for
\(\delta^\mu_\rho\).
Most of the notes concern tensors on general manifolds, without components.
Their equations are read as [index notation](notation.md), and those that are
identities are verified as such: four, among them
\(g^{\mu\nu} g_{\nu\sigma} = \delta^\mu_\sigma\) and the definition of the
Einstein tensor. Laws, such as Einstein's equation, are read but are not
identities: they relate tensors, such as the stress–energy tensor, that nothing
defines. Many more statements take derivatives of tensors without
components, which index notation does not take yet, and so are not understood.
Two conventions that would let more of them be checked are not read yet either:
\(x^\mu\) as the coordinates themselves, and coordinates as functions along a
curve, \(x^\mu(\lambda)\), in the geodesic equation.
## The corpus
`benchmarks/corpus.py` measures all this. It fetches papers from arXiv by their
identifiers and reports, for each, how many equations parse and what checking
them finds. The papers themselves are never stored in the repository.
```bash
uv run python benchmarks/corpus.py
```
| Paper | Equations | Parse | Hold | Differ | Relate | Ill-formed |
|---|---:|---:|---:|---:|---:|---:|
| Carroll, *Lecture Notes on General Relativity* | 797 | 98.6% | 139 | 6 | 210 | 1 |
| gr-qc 2611.26560 | 31 | 77.4% | 1 | 0 | 8 | 0 |
| gr-qc 2611.26576 | 305 | 48.9% | 0 | 0 | 50 | 0 |
| gr-qc 2611.26585 | 270 | 64.4% | 0 | 0 | 24 | 0 |
| gr-qc 2611.26591 | 27 | 100.0% | 0 | 0 | 3 | 0 |
| gr-qc 2611.26594 | 63 | 87.3% | 1 | 0 | 6 | 0 |
| gr-qc 2611.26620 | 47 | 78.7% | 0 | 0 | 15 | 0 |
Most of what the recent papers write between quantities they introduce relates
them, as a paper's results do; few of their equations involve only what is
defined. They lean on their own notation, from physics packages to macros built on
TeX internals, so they are where the language grows next.
**Next:** [Solving tensor equations](notation.md), for how equations between tensors
without components are verified, or the [verdicts](reference.md#verdicts-of-a-check) in
the language reference.
# Beyond spacetime
> **For:** anyone with data in NumPy or pandas; no General Relativity needed. **You will
> learn:** how data is bound to tensors, what spaces and indices are, and how to write
> statistics and linear algebra in index notation.
> **Before this:** [Getting started](getting-started.md), with the `data` extra.
Index notation never needed spacetime. An index ranges over a **space**: the four
coordinates of a metric, 500 assets, 2,520 trading days, the two states of a qubit.
A tensor is an array whose axes range over spaces, and RelativisticPy reads the same
notation in every case. It computes symbolic components with SymPy and numerical ones
with NumPy, SciPy and scikit-learn.
```python
>>> import numpy as np
>>> from relativisticpy import Workbook
>>> wb = Workbook()
>>> wb["R_{ta}"] = np.array([[0.01, 0.02, -0.01],
... [0.03, -0.01, 0.00],
... [-0.02, 0.01, 0.02],
... [0.00, 0.02, 0.03]]) # 4 days of returns on 3 assets
>>> wb.exe(r"""
... \mu_a := \mathbb{E}_t[R_{ta}]
... \Sigma_{ab} := \mathbb{E}_t[(R_{ta} - \mu_a)(R_{tb} - \mu_b)]
... """)
[]
>>> wb["mu"].to_numpy().round(4).tolist()
[0.005, 0.01, 0.01]
>>> wb["Sigma"].to_numpy().round(5).tolist()[0]
[0.00032, -0.00012, -0.00018]
```
## Five words
- **Index.** A letter written on a tensor, as `t` and `a` are on `R_{ta}`, which counts
along one of its axes: here `t` counts the days and `a` the assets.
- **Space.** What an index counts over: the days, the assets. Data brings its own
spaces, and a space can be declared.
- **Upper and lower.** An index is written up, as in `w^a`, or down, as in `\mu_a`.
Upper indices are vectors, such as the weights of a portfolio; lower ones are
covectors, such as the returns that weights are weighed against.
- **Contraction.** An index written twice in a term, once up and once down, is summed
over: `w^a \mu_a` is the sum of each weight times its expected return. This is
Einstein's convention, and it is how every product of tensors is written.
- **Metric.** A tensor `g_{ab}` that turns upper indices into lower ones,
`w_a = g_{ab} w^b`, and so measures lengths. Until a space is given one, its metric is
the identity, and an index may be summed in any position.
## Spaces
A space is declared in the notation, with its dimension, and the index labels that
range over it are declared with `\in`:
```python
>>> spins = Workbook()
>>> spins.exe(r"""
... \mathcal{H} := \mathbb{C}^{2}
... i, j \in \mathcal{H}
... \sigma^{i}{}_{j} := [[0, 1], [1, 0]]
... """)
[]
>>> spins["sigma"].spaces[0]
Space(name='H', dim=2, basis=None, field='complex', spacetime=False)
```
Data brings its own spaces, by these rules:
1. **Binding names the axes.** `wb["R_{ta}"] = returns` says that `t` ranges over the
rows of `returns` and `a` over its columns.
2. **A label written on a tensor takes that tensor's space** for the rest of the
statement, so it need not be declared: in `\mathbb{E}_t[R_{ta}]`, `t` counts days.
3. **Binding declares nothing else**, so `t` can still be a coordinate elsewhere, as in
`\Gamma^{t}{}_{tr}`.
4. **Data bound later shares a space** with the same index of a tensor already bound,
if it has as many components: `w^a`, bound after `R_{ta}`, ranges over its assets.
5. **Like indices of one tensor share one space**, as the two of a covariance
`\Sigma_{ab}` do. `t` and `a` are not alike, even when there are as many days as
assets.
6. **pandas names spaces and their bases.** An axis's name names its space, and its
labels the space's basis, by which components can be taken, as coordinates name the
components of a metric. Labelled data meets the space whose elements its labels are,
whatever its axis is named, and is aligned with that space's basis by label, never by
position; it is refused where its labels are not the space's:
```python
>>> import pandas as pd
>>> prices = pd.Series([0.5, 0.3, 0.2], index=pd.Index(["AAPL", "MSFT", "NVDA"], name="assets"))
>>> book = Workbook()
>>> book["w^a"] = prices
>>> book.expr(r"w^{a:MSFT}")
0.3
```
An index ranges over one space, and RelativisticPy says so when it does not:
```python
>>> wb.expr(r"R_{ta} R_{at}")
Traceback (most recent call last):
...
relativisticpy.errors.IndexNotationError: the index a ranges over the space of a, but is written here on an axis over the space of t
--> :1:8
|
1 | R_{ta} R_{at}
| ^^^^^^
```
## Data in, results out
`wb["R_{ta}"] = data` binds a NumPy array, a pandas DataFrame or Series, a SciPy
sparse matrix, a SymPy array or nested lists. A name without braces works too:
binding to `y_t` binds the tensor `y` with the index `t`. Results are
[`Tensor`](python.md#tensor) values with `to_numpy()` and `to_pandas()`; numbers
are Python numbers. What was bound reads back as it was written, `wb["R_{ta}"]`,
and `"R" in wb` says whether it was. Data that cannot be bound is refused with a
`DataError`, which is also a `ValueError`, saying why:
```python
>>> wb["v^a"] = [0.5, 0.25, [0.25]]
Traceback (most recent call last):
...
relativisticpy.errors.DataError: the data for v^a is ragged: entry 3 is a list, the others are numbers
```
A name takes a number, `wb["J"] = 1.5`, or text, which is read as a program reads
it, never run as Python: `wb["J"] = "x^2 + 1"`.
## Python objects, by name
Python reads the files, in its own cells, with any library there is, and the language
reads the objects by name. `\texttt{prices}` is the object called `prices` in the scope
the workbook is given, and attributes, keys and positions follow, as in
`\texttt{table.x}`, `\texttt{prices["NVDA"]}` and `\texttt{data[0]}`. The scope is a
mapping, as `globals()` or a dict, or a module or any object whose attributes are read:
```python
>>> import pandas as pd
>>> prices = pd.DataFrame(
... {"AAPL": [231.5, 233.0, 229.75], "NVDA": [141.2, 143.8, 140.1]},
... index=pd.Index(["2026-11-16", "2026-11-17", "2026-11-18"], name="date"),
... )
>>> weights = pd.Series([0.25, 0.75], index=pd.Index(["NVDA", "AAPL"], name="asset"))
>>> market = Workbook(scope={"prices": prices, "weights": weights})
>>> market.exe(r"""
... P_{ta} := \texttt{prices}
... w^a := \texttt{weights}
... x_t := \texttt{prices["NVDA"]}
... """)
[]
>>> market.expr(r"P_{ta} w^a").to_numpy().round(2).tolist() # each asset by its own weight
[208.92, 210.7, 207.34]
>>> market.expr(r"\mathbb{E}_t[x_t]")
141.7
```
What an object becomes depends on its type, as an object integration of
`relativisticpy.integrations` declares it:
- **A number** is a scalar, exact where Python's is: an integer or a fraction stays one.
- **An array**, from NumPy, or anything with `__array__` or the array API, as a JAX or
PyTorch array, is data, each axis over a space of its size.
- **A pandas DataFrame or Series** is labelled data. Defined with indices, as
`P_{ta} := \texttt{prices}`, it is bound as `wb["P_{ta}"] = prices` binds it: its index
and columns are the bases of spaces, named after its axes.
- **A SciPy sparse matrix** is sparse data, and **an xarray DataArray** data over its
named dimensions, labelled by their coordinates.
- **A SymPy expression**, or anything with `_sympy_`, is an expression, its symbols the
program's by name, and a SymPy matrix is a matrix.
- **A list or tuple of numbers** is a vector or a matrix, as `[1, 2]` is.
- **A function**, or anything else Python calls, is called: on numbers, and on data
elementwise. One written with NumPy is given whole arrays; any other, one number at a
time.
Data from two objects meets by label, never by position: above, `weights` lists the
assets in another order than `prices`, and each asset is weighed by its own weight.
Labels that are not the same elements are refused where they meet. Written with indices,
as `\texttt{signal}_t`, an object is data with those indices, without a definition. A
function and an expression are used as the program's own:
```python
>>> import numpy as np
>>> import sympy
>>> def hann(n, N):
... return 0.5 - 0.5 * np.cos(2 * np.pi * n / (N - 1))
>>> windowed = Workbook(scope={"hann": hann, "signal": np.array([4.0, 2.0, 6.0, 8.0])})
>>> windowed.expr(r"\mathbb{E}_t[\texttt{signal}_t]")
5.0
>>> windowed.expr(r"\texttt{hann}(\texttt{signal}_t, 9)").to_numpy().round(3).tolist()
[1.0, 0.5, 0.5, 0.0]
>>> x = sympy.Symbol("x")
>>> Workbook(scope={"f": sympy.sin(x) ** 2}).expr(r"\frac{d}{dx} \texttt{f}")
2*sin(x)*cos(x)
```
A reference is read by a grammar of its own, a name, then attributes, keys in quotes and
positions, and is never Python to run: anything else is refused, saying what may be
written. An object is read anew each time a program names it, and what it becomes is
the workbook's own, so that changing the object afterwards changes nothing already read.
A workbook given no scope reaches nothing in Python, nor does a document checked with
`relativisticpy check`, nor a program sent to the [MCP server](mcp.md):
```python
>>> Workbook().expr(r"\texttt{prices}")
Traceback (most recent call last):
...
relativisticpy.errors.CompileError: \texttt{prices} names a Python object, but no Python scope was given to read it from
--> :1:1
|
1 | \texttt{prices}
| ^^^^^^^^^^^^^^^
note: a document checked with relativisticpy check, and a program sent to the MCP server, are given no Python scope, so that they never reach into Python
hint: give the workbook one, as Workbook(scope=globals()), or the object to show, as show(source, prices=prices)
```
In a notebook, `show(source, prices=prices)` gives a program its objects, and the editor
takes a scope: see [Live mathematics](live.md#python-objects).
## Positions, metrics and duals
Upper indices are vectors and lower ones covectors, in every domain. In a space whose
metric is the identity, as is every space until it is given another, an index may be
summed in any position, as in Euclidean tensor calculus. Its Kronecker delta and the
covector of ones, `1_a` or `\mathbb{1}_a`, are written as usual:
```python
>>> wb["w^a"] = np.array([0.5, 0.25, 0.25])
>>> wb.expr(r"1_a w^a")
1.0
>>> wb.expr(r"w^a w^b \delta_{ab}")
0.375
```
Any symmetric positive definite tensor can be made a space's metric, as the line
element makes `g_{\mu\nu}` spacetime's; anything else is refused where it is first
used. Then indices pair up, and raising and lowering use it. With the covariance as
the metric of the assets, portfolio theory is geometry: `w_a` is each asset's
marginal risk, `w^a w_a` the variance of the portfolio, and `\mu^a` the direction of
Markowitz's portfolios:
```python
>>> wb.exe(r"g_{ab} := \Sigma_{ab}")
[]
>>> round(wb.expr(r"w^a w_a"), 8) == round(wb.expr(r"w^a \Sigma_{ab} w^b"), 8)
True
>>> wb.expr(r"w_{a} w_{a}")
Traceback (most recent call last):
...
relativisticpy.errors.IndexNotationError: index a appears twice as a lower index; a summed index must appear once up and once down
--> :1:1
|
1 | w_{a} w_{a}
| ^^^^^^^^^^^
```
## Statistics
`\mathbb{E}_t[\ldots]` binds `t` as a sum does: inside it every factor shares `t`, and
a term without `t`, such as `\mu_a` in `R_{ta} - \mu_a`, is constant in it. It is a
contraction with the measure of `t`'s space, uniform unless `wb.space(...,
measure=weights)` gives it weights, and RelativisticPy computes it as one contraction
with whatever it multiplies, never forming the product of everything averaged. With
2,520 days and 500 assets, that product would take 5 GB.
| Statistic | Meaning |
|---|---|
| `\mathbb{E}_t[X]` | the expectation over `t` |
| `\operatorname{Var}_t(X)` | the variance of each component, of \(\lvert X - \mathbb{E}_t X \rvert^2\) for complex data |
| `\operatorname{Cov}_t(X, Y)` | the covariance, with the free indices of both; of complex data, with \(Y\) conjugated, as NumPy's |
| `\operatorname{LedoitWolf}_t(R_{ta})` | the Ledoit–Wolf shrinkage estimate of a covariance, from scikit-learn, which weighs every sample alike |
Without an index, `\mathbb{E}[X]`, `\operatorname{Var}(X)` and `\operatorname{Cov}(X, Y)`
are of random variables, declared as [Random variables](probability.md) says; of
data they are refused, saying which index to write.
```python
>>> np.allclose(wb["Sigma"].to_numpy(), wb.expr(r"\operatorname{Cov}_t(R_{ta}, R_{tb})").to_numpy())
True
```
## Linear algebra
| Written | Meaning |
|---|---|
| `(\Sigma^{-1})^{ab}` | the inverse of a two-index tensor: of a form, its indices in the other position; of a map, a map, `(A^{-1})^a{}_b` |
| `\operatorname{eig}(A^a{}_b)` | eigenvalues and eigenvectors: `\lambda_k, v^a{}_k := \operatorname{eig}(A^a{}_b)` |
| `\operatorname{spec}(A)` | the eigenvalues; with a second argument `n`, the `n` largest, or smallest if negative, as for a large sparse matrix |
| `\operatorname{svd}(X_{ta})` | `U_{tk}, s_k, V_{ak} := \operatorname{svd}(X_{ta})`, so that \(X_{ta} = U_{tk} \operatorname{diag}(s)_{kl} V_{al}\) |
| `\det`, `\operatorname{tr}` | of a map, or of a matrix of components |
| `\operatorname{rank}`, `\rho`, `\lambda_{\max}`, `\kappa`, `expm`, `norm` | the [functions of a matrix](matrices.md), of a map's matrix of components: a number, or a map of the same space |
| `\|v\|` | the length of a vector, with the metric of its space: \(\sqrt{g_{ab} \bar v^a v^b}\) |
| `\operatorname{diag}(d)_{ab}` | the diagonal matrix of a vector |
| `A_{ta} \odot B_{ta}` | the elementwise product, which index notation has no other way to write |
| `\exp(H)`, `\sqrt{\Sigma}`, `\log` | functions of a matrix, for a tensor named without indices: `\exp(-i H t)` |
An inverse multiplied by what it acts on is never formed: it is solved for, by a
Cholesky factorisation when the matrix is symmetric positive definite. The tangency
portfolio is written as in a textbook and computed with two solves:
```python
>>> m = wb.expr(r"\frac{(\Sigma^{-1})^{ab} \mu_b}{1_c (\Sigma^{-1})^{cd} \mu_d}")
>>> round(float(m.to_numpy().sum()), 10)
1.0
>>> "solve" in wb.ir(r"(\Sigma^{-1})^{ab} \mu_b")
True
```
A map, or linear operator, has one index up and one down, `A^a{}_b`: it takes a vector
`v^b` to the vector `A^a{}_b v^b`. Its eigenvalues come with a new index, over a space
of their own. A bilinear form, with both indices down, has eigenvalues only relative to
a metric: \(S_{ab} v^b = \lambda g_{ab} v^b\). They are computed relative to the metric
of the form's space. Symbolic components give exact results:
```python
>>> spins.exe(r"H^{i}{}_{j} := [[\epsilon, \Delta], [\Delta, -\epsilon]]")
[]
>>> spins.expr(r"\operatorname{spec}(H^i{}_j)")
spec(H^i{}_j) over eigenvectors of H^i{}_j: 2 components non-zero
(spec(H^i{}_j))_0 = −√(Δ² + ε²)
(spec(H^i{}_j))_1 = √(Δ² + ε²)
```
## Grids and the Fourier transform
A range written beside a definition declares the space of its index, of one element for
each value, labelled by it, and the definition is made for each value: `n`, used as a
number, is the value. A sum whose body writes its index on data runs over the whole of
the data's space, from its lower limit, and binds the index, as a statistic does:
```python
>>> grid = Workbook()
>>> grid.exe(r"""
... N := 8
... h := \frac{1}{N}
... x_n := n\,h, \quad n = 0, \ldots, N-1
... """)
[]
>>> grid["x"].spaces[0].basis
('0', '1', '2', '3', '4', '5', '6', '7')
>>> grid.expr(r"\sum_n x_n")
7/2
```
`\operatorname{fft}` is the discrete Fourier transform, \(X_k = \sum_n x_n e^{-2\pi i k
n/N}\), by the fast algorithm, with NumPy, or JAX. Of data over an index, it gives data
over a new space, the frequencies of the index, labelled by their bins, k = 0, …, N − 1,
as X_k is written: bin k holds the frequency k/(N d), for samples d apart, and (k − N)/(N d)
from N/2 on. `\operatorname{ifft}` gives back data over the samples' own space:
```python
>>> signal = Workbook()
>>> signal["y_t"] = np.array([1.0, 2.0, 0.0, -1.0])
>>> spectrum = signal.expr(r"\operatorname{fft}(y_t)")
>>> spectrum.spaces[0].basis
('0', '1', '2', '3')
>>> spectrum.to_numpy().round(10).tolist()
[(2+0j), (1-3j), 0j, (1+3j)]
>>> signal.expr(r"\operatorname{ifft}(\operatorname{fft}(y_t))").spaces == signal["y"].spaces
True
```
The transform written as its sum is computed as an FFT too: a rewrite, which gives the
numbers the sum gives, in \(N \log N\) steps rather than \(N^2\):
```python
>>> grid.exe(r"X_k := \sum_{n=0}^{N-1} x_n e^{-2\pi i k n/N}, \quad k = 0, \ldots, N-1")
[]
>>> "call fft" in grid.ir("X_k")
True
```
## Optima over an index
An optimum over an index of data binds the index, as a sum does, and is the greatest or the
least value along it, for each value of any other index; `\arg\max` and `\arg\min` give the
label of the element where it is, a number where the label is one, or else its position.
Where several elements share it, the first is given, and a note says so. An optimum over
variables is found by the optimizers (see [Optima](optima.md)):
```python
>>> signal.exe(r"""
... \max_t y_t
... \arg\min_t y_t
... """)
[2.0, 3]
>>> grid.expr(r"\arg\max_n \sin(\pi x_n)")
4
>>> assets = Workbook()
>>> assets["R_{ta}"] = np.array([[0.01, 0.02, -0.01], [0.03, -0.02, 0.0]])
>>> assets.expr(r"\max_t R_{ta}").to_numpy().tolist()
[0.03, 0.02, 0.0]
```
## Domains
**Portfolios**: expected returns, covariances, the tangency portfolio, risk as a metric,
and the spectrum of the correlation matrix against the Marchenko–Pastur law of random
matrices, which tells real factors from noise: see the
[portfolio of 500 assets](examples.md#a-portfolio-of-500-assets-in-index-notation).
**Quantum systems**: an operator on two spins is a tensor with two indices of each kind,
\(H^{ik}{}_{jl}\) on \(\mathcal{H} \otimes \mathcal{H}\): see
[two spins](examples.md#two-spins).
**Graphs**: a graph of six nodes, two triangles joined by one edge, has the adjacency
matrix `A_{ij}`. Its degrees are `k_i = A_{ij} 1^j`, its Laplacian is
`L_{ij} = \operatorname{diag}(k)_{ij} - A_{ij}`, and the eigenvector of its second
eigenvalue, Fiedler's vector, cuts the graph in two where it is thinnest:
```python
>>> A = np.zeros((6, 6))
>>> for i, j in [(0, 1), (1, 2), (0, 2), (3, 4), (4, 5), (3, 5), (2, 3)]:
... A[i, j] = A[j, i] = 1.0
>>> graph = Workbook()
>>> graph["A_{ij}"] = A
>>> graph.exe(r"""
... k_i := A_{ij} 1^j
... L_{ij} := \operatorname{diag}(k)_{ij} - A_{ij}
... \lambda_n, v^i{}_n := \operatorname{eig}(L^i{}_j)
... """)
[]
>>> round(float(graph["lambda"].to_numpy()[1]), 4) # the second eigenvalue
0.4384
>>> fiedler = graph["v"].to_numpy()[:, 1]
>>> (np.sign(fiedler) == np.sign(fiedler[0])).tolist() # each node's side of the cut
[True, True, True, False, False, False]
```
**Regression**: least squares is the normal equations as they are written,
\(\beta^k = (G^{-1})^{kl} X_{tl} y_t\) with \(G_{kl} = X_{tk} X_{tl}\), and the inverse is
solved for, never formed. Define `G` with `:=`, since `G_{kl}` with two indices is
otherwise the Einstein tensor:
```python
>>> fit = Workbook()
>>> fit["X_{tk}"] = np.column_stack([np.ones(5), np.arange(5.0)]) # a constant, and t
>>> fit["y_t"] = np.array([1.0, 3.0, 5.0, 7.0, 9.0])
>>> fit.exe(r"""
... G_{kl} := X_{tk} X_{tl}
... \beta^k := (G^{-1})^{kl} X_{tl} y_t
... """)
[]
>>> fit["beta"].to_numpy().round(10).tolist() # y = 1 + 2t
[1.0, 2.0]
```
## Scale
- **Planning.** Contractions are ordered by cost with `numpy.einsum`'s optimiser,
and the plan is kept for the next contraction of the same shapes.
- **Memory.** A contraction whose operands are too large to hold at once is done in
slices along an index it sums over, and the slices added.
- **Sparse data.** A SciPy sparse matrix is a tensor like any other, and is never
densified: it multiplies vectors, dense matrices and other sparse matrices as a
matrix, its products with sparse matrices stay sparse, and its few largest or
smallest eigenvalues come from an iterative solver:
`\operatorname{spec}(L^i{}_j, -6)`. Without a count, a sparse matrix of up to 4,096
rows has its whole spectrum computed as a dense one.
- **JAX.** `Workbook(backend="jax")` keeps bound data as JAX arrays, computed with JAX,
on a GPU if there is one; a sparse matrix stays SciPy's, and multiplies JAX arrays
as one of JAX's. Statistics need 64-bit numbers, so it turns on JAX's
`jax_enable_x64` for the whole process. `wb.grad(expression, "w")` differentiates
any scalar expression with respect to bound data, through contractions, sparse
matrices and linear solves:
```python
>>> grad = Workbook()
>>> grad["w^a"] = np.array([1.0, 2.0])
>>> grad["S_{ab}"] = np.array([[2.0, 0.0], [0.0, 3.0]])
>>> grad.grad(r"w^a S_{ab} w^b", "w").to_numpy()
array([ 4., 12.])
```
Numerical work needs `pip install "relativisticpy[numeric]"`; pandas and
scikit-learn come with `relativisticpy[data]`, and JAX with `relativisticpy[jax]`.
**Next:** [Python API](python.md#tensor), for every method of a tensor and of its data,
or the [examples](examples.md), worked through.
# Numerics
> **For:** physicists who want numbers: values, plots, orbits and light rays. **You
> will learn:** how to compile a result into a NumPy function, evaluate it at a point,
> and integrate geodesics of particles and light with SciPy. **Before this:**
> [Tensors and geometry](tensors.md).
The symbolic results of RelativisticPy become numbers through
`relativisticpy.numeric`, which compiles expressions and tensors into NumPy
functions and integrates geodesics with SciPy. It needs the `numeric` extra (see
[Getting started](getting-started.md#install)), which installs NumPy and SciPy.
## NumPy functions
`lambdify` compiles a scalar or a tensor into a vectorised NumPy function of
the variables you name; every other symbol is given a value:
```python
>>> import numpy as np
>>> from relativisticpy import spacetimes
>>> from relativisticpy.numeric import evaluate, lambdify
>>> g = spacetimes.schwarzschild()
>>> kretschmann = lambdify(g.kretschmann, ["r"], M=1)
>>> kretschmann(np.array([2.0, 3.0, 6.0])).round(5)
array([0.75 , 0.06584, 0.00103])
```
A tensor compiles to a function returning an array of its components'
shape, with the variables' shape appended when they are arrays:
```python
>>> metric = lambdify(g, g.coordinates, M=1)
>>> metric(0.0, np.linspace(3, 10, 50), np.pi / 2, 0.0).shape
(4, 4, 50)
```
`evaluate` gives the value at one point, and names any value you forgot:
```python
>>> float(evaluate(g.christoffel, r=10, theta=np.pi / 2, M=1)[1, 0, 0])
0.008
>>> evaluate(g.christoffel, r=10, M=1)
Traceback (most recent call last):
...
ValueError: give a value for theta
```
Values are matched to symbols by name, whether you give them by name or by
symbol, so they also reach a symbol with assumptions, such as a positive `M`.
`lambdify` and `geodesic` name a forgotten value in the same way. An undefined
function has no value to give, such as the scale factor \(a(t)\) of
`spacetimes.flrw()`; give the spacetime an expression for it instead:
```python
>>> evaluate(spacetimes.flrw().ricci_scalar, t=1, r=0.5, k=0)
Traceback (most recent call last):
...
ValueError: replace the undefined function a with an expression
>>> import sympy
>>> evaluate(spacetimes.flrw(0, sympy.Symbol("t") ** 2).ricci_scalar, t=1)
36.0
```
## Geodesics
`geodesic` integrates the geodesic equation
\(\ddot x^a = -\Gamma^a{}_{bc}\,\dot x^b \dot x^c\) with
`scipy.integrate.solve_ivp`, from an initial position and four-velocity.
`four_velocity` completes a four-velocity from its spatial components, so
that \(g_{\mu\nu} u^\mu u^\nu = -1\) for a particle (or \(0\) for light).
A circular orbit stays circular:
```python
>>> from relativisticpy.numeric import four_velocity, geodesic
>>> start = [0, 10, np.pi / 2, 0] # t, r, θ, φ
>>> u = four_velocity(g, start, [0, 0, (1 / 700) ** 0.5], M=1)
>>> orbit = geodesic(g, start, u, (0, 1000), M=1)
>>> print(orbit["r"].min().round(6), orbit["r"].max().round(6))
10.0 10.0
```
An eccentric orbit precesses. Far from the black hole the advance of the
periapsis per orbit approaches the famous \(6\pi M / a(1 - e^2)\), which
accounts for Mercury's anomalous precession:
```python
>>> start = [0, 500, np.pi / 2, 0] # start at apoapsis
>>> circular = (1 / (500**2 * 497)) ** 0.5
>>> u = four_velocity(g, start, [0, 0, 0.9 * circular], M=1)
>>> orbit = geodesic(g, start, u, (0, 120000), M=1, samples=400001)
>>> r, phi = orbit["r"], orbit["phi"]
>>> apoapsis = np.where((r[1:-1] > r[:-2]) & (r[1:-1] > r[2:]))[0][0] + 1
>>> advance = phi[apoapsis] - 2 * np.pi
>>> a, e = (r.max() + r.min()) / 2, (r.max() - r.min()) / (r.max() + r.min())
>>> print(f"{advance:.3f} rad per orbit, {advance / (6 * np.pi / (a * (1 - e**2))):.2f} of the formula")
0.047 rad per orbit, 1.01 of the formula
```
The remaining percent is the higher-order correction the formula leaves out.
The four-velocity's norm is conserved along the orbit, a check on the
integration:
```python
>>> norms = [orbit.u[:, i] @ metric(*orbit.x[:, i]) @ orbit.u[:, i] for i in (0, 200000, 400000)]
>>> np.allclose(norms, -1)
True
```
`geodesic` returns a `Geodesic` with `tau`, the coordinates `x` and velocities
`u` (one row per coordinate), access by coordinate name (`orbit["r"]`), and
SciPy's full `solution`. `method`, `rtol` and `atol` go to `solve_ivp`; every
other keyword argument is a parameter of the metric, such as `M=1`.
`four_velocity` takes the future-directed solution, with \(u^t > 0\), and says
when there is none. Inside the ergoregion of a spinning black hole, where
\(g_{tt} > 0\), nothing can rotate against the hole. Where a co-rotating particle
has two future-directed solutions, it takes the smaller \(u^t\), which continues
the solution from outside:
```python
>>> kerr = spacetimes.kerr()
>>> inside = [0, 1.9, np.pi / 2, 0] # within r = 2M, for a = 0.9M
>>> four_velocity(kerr, inside, [0, 0, 0.3], M=1, a=0.9).round(4)
array([4.3305, 0. , 0. , 0.3 ])
>>> four_velocity(kerr, inside, [0, 0, -0.3], M=1, a=0.9)
Traceback (most recent call last):
...
ValueError: no future-directed four-velocity (u^t > 0) has these spatial components
```
## Light
Light follows null geodesics, with `four_velocity(..., kind="null")`. A ray
aimed closer than \(b = 3\sqrt{3}\,M\) to a black hole falls in. `stop` ends
an integration where a function of the position and velocity crosses zero, here
once the ray is inside the photon sphere at \(r = 3M\), and `stopped` says
whether that happened:
```python
>>> def ray(b, r0=1000.0):
... start = [0, r0, np.pi / 2, 0]
... inward = -(1 - (1 - 2 / r0) * b**2 / r0**2) ** 0.5
... u = four_velocity(g, start, [inward, 0, b / r0**2], kind="null", M=1)
... return geodesic(g, start, u, (0, 3000), M=1, stop=lambda x, u: x[1] - 2.5)
>>> ray(5.1).stopped, ray(5.3).stopped
(True, False)
```
The example [light near a black hole](examples.md#light-near-a-black-hole) finds the
critical impact parameter this way, and measures the bending of starlight.
## Results from a workbook
Anything a workbook computes can go the same way: `wb.metric` is the metric in
force as a `Metric`, and tensor results are `Tensor` values.
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook()
>>> wb.expr(r"g_{\mu\nu} := ReissnerNordstrom(M, Q)")
>>> horizon = wb.expr(r"solve(g_{tt} = 0, r)")
>>> horizon
[M - sqrt((M - Q)*(M + Q)), M + sqrt((M - Q)*(M + Q))]
>>> [round(evaluate(root, M=1, Q=0.5), 4) for root in horizon]
[0.134, 1.866]
```
**Next:** the [examples](examples.md), for light bent by a black hole and more, or
[Jupyter and notebooks](jupyter.md), to plot what you compute.
# The language reference
> **For:** anyone, person or agent, who needs to know what the language accepts. **You will learn:** every statement, command, environment, constant, verdict and error, and every function by name.
This page is generated from the tables the language is read with and from what its integrations declare. `relativisticpy help reference` prints it offline, and `relativisticpy help NAME` one function in full, as `relativisticpy help besselj`: its forms, its arguments, its examples with their answers, and what computes it. The guides explain each part: [The language](language.md) and the page of [each field](language.md#fields), [LaTeX](latex.md), [Tensors and geometry](tensors.md) and [Beyond spacetime](spaces.md).
## Statements
A program is a sequence of statements, one to a line; a semicolon, `\\` and `\linebreak \newline` also end one. `#` and `%` start a comment, so `%` is not a remainder. A statement goes on to the next line while a bracket is open, after a line that ends with an operator, and before a line that starts with one such as `+` or `=`; a line that starts with `-` goes on only if it is indented further.
`:=` defines, as do `\coloneq` `\coloneqq` `\defeq` `\equiv` `\triangleq` and `≡` `≔`; between two sides neither of which can be defined, `\equiv` states that they are equal. `=` defines only what has no meaning yet; otherwise it states an equation, or a claim, which is checked.
| Statement | Meaning |
|---|---|
| `x := 2` | defines x, or gives it a new value |
| `x = 2`, where x is new | defines x; so do `f(x) = x^2` and a new tensor `T_{ab} = ...` |
| `x = 3`, where x has a value | a claim, checked: does x equal 3? `x := 3` gives x a new value |
| `ds^2 = ...` | a line element: the metric, and the coordinates if none are declared |
| `R = 0`, `g_{tt} = -1` | with a metric in force, a claim about a built-in or a component |
| `t = 0`, where t is a coordinate | a condition: read, not computed |
| `x^2 + y^2 = 1` | an equation, to `solve`; `a = b = c` is a claim for each link |
| `f(x) := x^2` | a function; `f : (x) -> { ... }` is one with a block of statements |
| `\mathcal{H} := \mathbb{C}^{2}` | a space, complex, of 2 dimensions; `\mathbb{R}^{n}` is real |
| `i, j \in \mathcal{H}` | index labels that range over a space |
| `x_n := n h, \quad n = 0, \ldots, N-1` | a grid: n ranges over its N values, and x is made for each |
| `a > 0`, `0 < x < 1`, `a, b > 0`, `x \in \mathbb{R}`, `n \in \mathbb{N}` | an assumption about names nothing defines, from then on |
| `Coordinates := [t, r, \theta, \phi]` | the coordinates, in order |
| `Constants` `Reals` `Integers` `Complex` `Positive` `:= [a, b]` | declare a and b constants, real, integers, complex or positive, before they are used |
A renaming statement gives a built-in another name: `MetricSymbol := G` makes the metric `G`. They are, with the names they change: `MetricSymbol` (`g`), `ConnectionSymbol` (`C`), `RiemannSymbol` (`R`), `RicciSymbol` (`Ric`), `EinsteinSymbol` (`G`), `EinsteinTensorSymbol` (`G`), `WeylSymbol` (`W`), `DerivativeSymbol` (`d`), `CovariantDerivativeSymbol` (`D`).
## Names and numbers
- A name that nothing defines is a symbol. `theta`, `\theta` and `θ` are one symbol, as is every spelling of a Greek letter.
- In LaTeX, a run of letters is a product of one symbol for each letter: `\frac{2GM}{r}` is 2·G·M/r. Greek names, defined names and builtins stay whole, and `\mathrm{GM}` or `\text{GM}` is one name. In plain text, `GM` is one name, with a note where its letters are written alone too.
- Plain text and Unicode write LaTeX's functions and operators in letters, as AsciiMath does, and read as the commands they spell: `sin 2x` and `sin²x` are `\sin 2x` and `\sin^2 x`, and `log_2 8`, `int_0^1 x^2 dx`, `lim_(x->0) f(x)` and `sum_(n=1)^oo 1/n^2` are `\log_2 8`, `\int_0^1 x^2\,dx`, `\lim_{x \to 0} f(x)` and `\sum_{n=1}^{\infty} 1/n^2`; `oo` is `\infty`. A solidus between differentials is Leibniz's fraction: `d/dx f`, `dy/dx`, `d(x^3)/dx`, `∂f/∂x`. `sum(f, (n, a, b))` and `product(f, (k, a, b))` are `\sum` and `\prod`. A name that runs a function into its argument, as `sinx`, is one name with a note in plain text, and refused in LaTeX and Unicode.
- A subscript on a symbol makes another symbol: `r_s` and `r_{s}` are both `r_s`. On a tensor, it is an index.
- A name followed by a bracket, with no space, is a call: `f(x)`. A function nothing defines is unknown, as `A(r)` in a metric. A function written as a command takes what follows it: `\sin x`, `\sin^2\theta`.
- Arithmetic is exact: `1/2` is a half, and a decimal stays a decimal. `^` and `**` are powers, a space between factors multiplies, and `299\,792\,458` is one number.
- `[1, 2]` is a list, which is a vector in arithmetic; a list of rows, or a matrix environment, is a matrix.
- A bar with values, as in `x^2 |_{x=2}`, puts the values in.
| Constant | Value |
|---|---|
| `pi` | π |
| `e` | Euler's number |
| `i` | the imaginary unit |
| `oo` | infinity |
| `infty` | infinity, as `\infty` |
| `True` | true |
| `False` | false |
## Index notation
- `^{...}` holds upper indices and `_{...}` lower ones. In braces each letter is an index and a Greek name is one: `_{ab}` is a, b and `_{\mu\nu}` (or `_{mu nu}`) is μ, ν. A script without braces is one letter, command or number, as in TeX: `R^a_b` is `R^{a}_{b}`. `{}` staggers indices: `R^{a}{}_{bcd}`.
- An index once up and once down in a term is summed; the others are free, and are the same in every term and on both sides. These rules are checked before anything is computed.
- With a metric in force, it raises and lowers indices: write a tensor with its indices where you want them.
- A component is chosen by number, `g_{01}`, by a coordinate's name, `\Gamma^{r}_{\theta\theta}`, or with `=` or `:`, as in `A^{\mu=0}` and `w^{a:MSFT}`.
- `\partial_\mu`, or `d_{a}`, and `\nabla_\mu`, or `D_{a}`, are the partial and the covariant derivative of the factor after them; `T^{\mu\nu}{}_{,\nu}` and `T^{\mu\nu}{}_{;\nu}` mean the same.
- `T_{(ab)}` symmetrises and `F_{[ab]}` antisymmetrises, also across tensors.
- An equation between tensors with components stands for one equation for each component. One between tensors without components, as `T_{\mu\nu}` before it is defined, is kept as an equation of notation.
### Built-in tensors
With a metric in force, these names mean the tensors of its geometry, by name and number of indices. The conventions are those of Misner, Thorne and Wheeler, and of Carroll.
| Name | Indices | Meaning |
|---|---|---|
| `g` | 2 | the metric, `g_{\mu\nu}`, and its inverse, `g^{\mu\nu}` |
| `C` `\Gamma` | 3 | the Christoffel symbols, `\Gamma^a{}_{bc}` |
| `R` | 4 | the Riemann tensor, `R^a{}_{bcd}` |
| `Ric` `R` | 2 | the Ricci tensor, `R_{ab}` |
| `G` | 2 | the Einstein tensor, `G_{ab}` |
| `W` `C` | 4 | the Weyl tensor, `C_{abcd}` |
| `\delta` | 2 | the Kronecker delta, `\delta^a{}_b` |
| `g` | 0 | the determinant of the metric |
| `Ric` `R` | 0 | the Ricci scalar |
| `Kretschmann` | 0 | the Kretschmann scalar, `R_{abcd} R^{abcd}` |
| `geodesic_equations(\tau)` | | the geodesic equations, in the parameter `\tau` |
`R` and `g` stay symbols where the metric is written with them, as the radius R of a sphere is; `Ric` is always the Ricci scalar. In a line element, `d\Omega^2` is `d\theta^2 + \sin^2\theta\, d\phi^2`.
### Equations between tensors without components
| Operation | Meaning |
|---|---|
| `LHS` | its left side |
| `RHS` | its right side |
| `simplify` | its canonical form, with the identities of General Relativity |
| `solve` | `solve(E, T_{\mu\nu})`, for a tensor, with its indices up or down |
| `subs` | `subs(E, rule)`: a definition, a contraction, or a value such as `\Lambda = 0` |
| `trace` | contracts its two free indices with the metric |
## Vectors
- A list, a tuple or a column of numbers is a vector, as `\mathbf{v} := (1, 2, 3)`. Between vectors `\cdot` is the dot product and `\times` the cross product; between numbers both multiply. `|\mathbf{v}|` is its length, and `\mathbf{p}^2` is `\mathbf{p} \cdot \mathbf{p}`.
- A vector's derivatives, integrals, evaluation bars and limits are each component's; `\mathbf{v}(\mathbf{r}(t))` is a field at a point.
- `\hat{\mathbf{x}}`, `\hat{x}`, `\hat{\imath}` and `\mathbf{i}`, `\mathbf{j}`, `\mathbf{k}`, which nothing defines, are Cartesian unit vectors; `\hat{\mathbf{r}}` and `\mathbf{e}_r` are those of the coordinates in force.
- `\nabla f`, `\nabla \cdot \mathbf{v}`, `\nabla \times \mathbf{v}`, `\nabla^2 f` and `\Delta f` are of the coordinates in force, whose scale factors a line element gives, or the Cartesian coordinates written in them, or their names; without coordinates they are of x, y and z. `(\mathbf{u} \cdot \nabla)` acts on what follows it. Of a function at a point, `\nabla f(\mathbf{a})` is its gradient there and `\nabla^2 f(\mathbf{a})` its Hessian.
- An equation between vectors holds component by component; `\mathbf{0}` is the zero vector. `\iint_{x^2 + y^2 \le 1} f\,dA` is over the disk, `\iiint_{[0, 1]^3} f\,dV` over the cube, and `\oint_C \mathbf{F} \cdot d\mathbf{r}` along a curve `C(t) := ...` whose parameter's range is stated.
- Where the metric is written as the identity, `ds^2 = dx^2 + dy^2 + dz^2`, or a space is `\mathbb{R}^n`, an index repeated in any position is summed, and `\epsilon_{ijk}` is the Levi-Civita symbol.
## Spacetimes
Each is a function that gives a metric, as in `g_{\mu\nu} := Schwarzschild(M)`. Parameters are names or numbers, and units are geometric, G = c = 1, unless `G` and `c` follow the spacetime's own parameters: `Minkowski(coordinates, G, c)`, `Schwarzschild(M, G, c)`, `ReissnerNordstrom(M, Q, G, c)`, `Kerr(M, a, G, c)`, `KerrNewman(M, a, Q, G, c)`, `FLRW(k, a, G, c)`, `DeSitter(L, G, c)`, `AntiDeSitter(L, G, c)`.
## Functions
A function is called by its name, `simplify(x)`, or, if LaTeX has it, as a command, `\sin x`, or as books write it, `\Gamma(x)`: a definition of the name in the program comes first. Most apply to each component of a tensor: `simplify(R_{abcd})` simplifies every component. Each is a capability of an integration, a module of `relativisticpy.integrations` ([Integrations](integrations.md)), listed here by family, with every name and the forms books write it in; `relativisticpy help NAME` describes one in full.
- **Activation functions of neural networks:** `ReLU` `\operatorname{ReLU}(x)`, `softplus` `\operatorname{softplus}(x)`
- **Algebra and calculus:** `simplify` `tsimplify`, `expand`, `factor`, `collect`, `cancel`, `apart`, `together`, `trigsimp`, `powsimp`, `expand_trig`, `nsimplify`, `diff`, `integrate`, `limit` `lim`, `series`, `subs`, `N` `numerical` `evalf`, `doit`
- **Bessel and Airy functions:** `besselj` `J_{\nu}(x)`, `bessely` `Y_{\nu}(x)`, `besseli` `I_{\nu}(x)`, `besselk` `K_{\nu}(x)`, `jn` `j_n(x)`, `yn` `y_n(x)`, `airyai` `\operatorname{Ai}(x)`, `airybi` `\operatorname{Bi}(x)`
- **The notation of chemistry:** `colog` `\mathrm{p}X` `\mathrm{p}(X)`
- **Combinatorics:** `stirling2`, `stirling1`, `catalan`, `fibonacci`, `bell`, `bernoulli` `B_n`, `harmonic` `H_n`, `partition` `p(n)`, `multinomial`
- **Elementary functions:** `sin`, `cos`, `tan`, `cot`, `sec`, `csc`, `asin` `arcsin`, `acos` `arccos`, `atan` `arctan`, `acot`, `asec`, `acsc`, `sinh`, `cosh`, `tanh`, `coth`, `sech`, `csch`, `asinh` `arsinh`, `acosh` `arcosh`, `atanh` `artanh`, `acoth` `arcoth`, `asech` `arsech`, `acsch` `arcsch`, `exp`, `ln`, `sqrt`, `abs` `Abs`, `sign`, `floor`, `ceiling`, `factorial`, `factorial2`, `gamma` `\Gamma(x)`, `re` `Re`, `im` `Im`, `conjugate` `conj`, `arg`, `erf`
- **Equations:** `solve`, `dsolve`, `RHS` `rhs`, `LHS` `lhs`, `Eq`, `symbols`, `latex`
- **The discrete Fourier transform:** `fft` `\operatorname{fft}(x)`, `ifft` `\operatorname{ifft}(X)`
- **Matrices:** `diag`, `det`, `inverse` `inv`, `pinv`, `transpose`, `ctranspose`, `trace` `tr` `Tr` `\operatorname{tr} A` `\operatorname{tr}(A)` `\operatorname{Tr} A` `\operatorname{Tr}(A)`, `rank` `\operatorname{rank} A` `\operatorname{rank}(A)`, `adjugate` `adj` `\operatorname{adj} A` `\operatorname{adj}(A)`, `null` `\operatorname{null} A` `\operatorname{null}(A)`, `dim`, `vec` `\operatorname{vec} A` `\operatorname{vec}(A)`, `norm`, `cond` `\kappa(A)` `\kappa_p(A)`, `spectral_radius` `\rho(A)`, `lambda_max` `\lambda_{\max}(A)` `\lambda_{\max} A`, `lambda_min` `\lambda_{\min}(A)` `\lambda_{\min} A`, `eigenvalue` `\lambda_k(A)`, `spec` `\operatorname{spec}(A)` `\sigma(A)`, `expm`, `logm`, `sqrtm`, `matrix_power`, `kron`, `dot`, `cross`, `direct_sum`
- **Number theory:** `mod` `Mod`, `totient` `\varphi(n)` `\phi(n)`, `mobius` `\mu(n)`, `primepi` `\pi(x)`, `divisor_sigma` `\sigma_k(n)`, `divisor_count` `d(n)`, `primenu` `\omega(n)`, `primeomega` `\Omega(n)`, `mangoldt` `\Lambda(n)`
- **Numbers:** `log`, `root`, `binomial`, `atan2`, `min` `Min`, `max` `Max`, `gcd`, `lcm`
- **Orthogonal polynomials and spherical harmonics:** `legendre` `P_n(x)`, `assoc_legendre` `P_{\ell}^m(x)`, `hermite` `H_n(x)`, `laguerre` `L_n(x)`, `assoc_laguerre` `L_n^{(\alpha)}(x)`, `chebyshevt` `T_n(x)`, `chebyshevu` `U_n(x)`, `Ynm` `Y_{\ell}^m(\theta, \phi)`
- **Sequences, as signal processing writes them:** `impulse` `\delta[n]`, `step` `u[n]`, `poles`, `zeros`
- **Special functions:** `beta` `\mathrm{B}(a, b)`, `zeta` `\zeta(s)`, `Log`, `erfc`, `erfi`, `Ei`, `Si`, `Ci`, `LambertW` `W_k(x)`, `elliptic_k` `\operatorname{K}(m)`, `elliptic_e` `\operatorname{E}(m)`, `hyper` `{}_pF_q(a; b; z)`, `rf` `RisingFactorial` `(a)_n`, `normcdf` `\Phi(x)`, `Heaviside` `u_c(t)`, `DiracDelta` `\operatorname{DiracDelta}(x)` `\delta(x)`
- **Integral transforms:** `LaplaceTransform` `laplace_transform` `\mathcal{L}\{f\}(s)` `\mathcal{L}\{f\}`, `InverseLaplaceTransform` `inverse_laplace_transform` `\mathcal{L}^{-1}\{F\}(t)` `\mathcal{L}^{-1}\{F\}`, `FourierTransform` `fourier_transform` `\mathcal{F}\{f\}(s)` `\mathcal{F}\{f\}`, `InverseFourierTransform` `inverse_fourier_transform` `\mathcal{F}^{-1}\{F\}(x)` `\mathcal{F}^{-1}\{F\}`, `ZTransform` `z_transform` `\mathcal{Z}\{x\}(z)` `\mathcal{Z}\{x\}`, `InverseZTransform` `inverse_z_transform` `\mathcal{Z}^{-1}\{X\}(n)` `\mathcal{Z}^{-1}\{X\}`
- **Rewrites,** what a program writes, computed faster by another capability, to the same numbers: `dft_sum` `\sum_{n=0}^{N-1} x_n e^{-2\pi i k n/N}`, by `fft`
### Optimizers
An optimum, `\min_{x} f(x)`, `\arg\max_{x, y} u \quad \text{subject to} \quad g = 0` or `\sup_{0 \le x < 1} f(x)`, is found by the optimizers, in this order: those that compute exactly, `extrema`, `kkt`, `simplex`, `enumeration`; then, where it has no parameters, those that compute numerically, `linprog`, `quadratic`, `minimize`, which take first one written with decimals, as data is. A note says which found it, how, and whether it is global. Over an index of data, `\max_t x_t` is the greatest value along it, and `\arg\max_t x_t` its label.
### Book names not supported yet
A name books write for a function no integration provides is refused, saying what it is, never read as an unknown function or a symbol: `\operatorname{Res}_{z=a} f`, the residue of a function at a point; `\epsilon_{ijk}`, the Levi-Civita symbol.
## Data, statistics and linear algebra
Data is bound from Python, `wb["R_{ta}"] = array`, and computed with NumPy: `pip install "relativisticpy[numeric]"`, or `[data]` for pandas and scikit-learn. An index ranges over a space: of coordinates, assets, days or states. `1_a` is the covector of ones, `A_{ta} \odot B_{ta}` the elementwise product and `\|v\|` the length of a vector.
### Statistics
A statistic binds its index, as a sum does: inside it, every factor shares t.
| Statistic | Meaning |
|---|---|
| `\mathbb{E}_t[X]` | the expectation over t, a contraction with its measure; named `𝔼` |
| `\operatorname{Var}_t(X)` | the variance over t of each component; named `Var`, `var` |
| `\operatorname{Cov}_t(X, Y)` | the covariance over t, with the free indices of both; named `Cov`, `cov` |
| `\operatorname{LedoitWolf}_t(R_{ta})` | the Ledoit–Wolf estimate of a covariance, with scikit-learn; named `LedoitWolf` |
### Linear algebra
Given a tensor, these functions are linear algebra. They are written `\operatorname{eig}`, or as a command where LaTeX has one, `\det`.
| Function | Meaning |
|---|---|
| `det` | the determinant of a map |
| `diag` | `\operatorname{diag}(d)_{ab}`, the diagonal matrix of a vector |
| `eig` | `\lambda_k, v^a{}_k := \operatorname{eig}(A^a{}_b)`: eigenvalues and eigenvectors; `eig(A)` of a matrix written without indices, its eigenvalues, as MATLAB gives them |
| `exp` | the exponential of a tensor named without indices: `\exp(-i H t)` |
| `inv` | the inverse; `(\Sigma^{-1})^{ab}` is written as on paper, and solved for, not formed |
| `log` | the logarithm of a matrix |
| `spec` | `\operatorname{spec}(A^a{}_b)`, the eigenvalues; with a second argument n, the n largest, or smallest if n is negative |
| `sqrt` | the square root of a matrix, `\sqrt{\Sigma}` |
| `svd` | `U_{tk}, s_k, V_{ak} := \operatorname{svd}(X_{ta})`: the singular values and vectors |
| `tr` `trace` | the trace of a map |
### Python objects
`\texttt{prices}` is the object called prices in the Python scope a workbook is given, `Workbook(scope=globals())`, or of the objects passed to `show`. Attributes, keys and positions follow, `\texttt{prices["NVDA"]}`, and are read, never run as Python. A document checked, and a program sent to the MCP server, have no scope. Defined with indices, `P_{ta} := \texttt{prices}`, data is bound as `wb["P_{ta}"] = prices` binds it, and meets other data by label; written with them, `\texttt{signal}_t`, it has them. What an object becomes, by the object integrations:
| Object | Becomes |
|---|---|
| `numpy.ndarray` `numpy.generic` `anything with __array__` `anything with __array_namespace__` `anything with __dlpack__` | an array, or anything NumPy reads: data, each axis over a space of its size; a NumPy number is a scalar |
| `pandas.DataFrame` `pandas.Series` | a DataFrame or Series: labelled data, its index and columns the bases of spaces named after its axes |
| `int` `float` `complex` `bool` `fractions.Fraction` `decimal.Decimal` `numbers.Number` | a number: a scalar, exact where Python's is, as an integer or a fraction |
| `list` `tuple` | a list or tuple of numbers, or of lists of them: a vector or a matrix, as the language's own lists are |
| `anything callable` | a function, or anything called: called in a program, on numbers, and on data elementwise |
| `scipy.sparse.spmatrix` `scipy.sparse.sparray` | a SciPy sparse matrix or array: sparse data, never made dense |
| `sympy.Basic` `sympy.matrices.MatrixBase` `sympy.NDimArray` `anything with _sympy_` | a SymPy expression, or anything with _sympy_: an expression, its symbols the program's by name; a SymPy matrix is a matrix |
| `xarray.DataArray` | a DataArray: data over its named dimensions, labelled by their coordinates |
## Random variables
`X \sim D` declares a random variable, `X, Y \overset{\text{iid}}{\sim} D` independent ones, `X_1, \ldots, X_n \overset{\text{iid}}{\sim} D` a sample, and `X \mid N \sim D` one given another. A distribution is written as books write it, or called by its name with its parameters as SymPy takes them: `Normal(mu, sigma)` `\mathcal{N}(\mu, \sigma^2)` `N(\mu, \sigma^2)`, `Poisson(rate)` `\operatorname{Poisson}(\lambda)` `\operatorname{Pois}(\lambda)`, `Binomial(n, p)` `\operatorname{Bin}(n, p)` `\operatorname{Binom}(n, p)`, `Bernoulli(p)` `\operatorname{Bernoulli}(p)` `\operatorname{Ber}(p)` `\operatorname{Bern}(p)`, `Uniform(a, b)` `U(a, b)` `\mathcal{U}(a, b)` `\operatorname{Unif}(a, b)`, `Exponential(rate)` `\operatorname{Exp}(\lambda)`, `GammaDistribution(k, theta)` `\Gamma(k, \theta)`, `ChiSquared(k)` `\chi^2_k` `\chi_k^2` `\chi^2(k)`, `StudentT(nu)` `t_\nu` `t(\nu)`, `BetaDistribution(alpha, beta)` `\operatorname{Beta}(\alpha, \beta)`, `Geometric(p)` `\operatorname{Geom}(p)`.
`\Pr(X > 1)`, `\mathbb{P}(A)`, `P(X = 2)`, `\mathbb{E}[X]`, `\operatorname{Var}(X)` and `\operatorname{Cov}(X, Y)` are computed, with `\mid` the conditional bar; `f_X(x)`, `F_X(x)`, `F_X^{-1}(q)`, `M_X(t)` and `\varphi_X(t)` are X's density, distribution function, quantile and generating functions: exactly by SymPy, or by SciPy where SymPy finds no closed form in 5 s and there are no parameters. `\Pr(A) := 0.3` gives an event's probability, and a capital letter nothing defines is a random variable of any law.
## LaTeX
Typesetting is ignored: spacing, sizes, `\label`, `\tag`, `$`, `$$`, `\[ \]` and the `&` of alignments. Every statement inside a display is LaTeX, however it is written. An unknown command is an error that suggests the closest one.
### Commands
| Command | Meaning |
|---|---|
| `\alpha \beta \chi \Delta \delta \epsilon \eta \Gamma \gamma \iota \kappa \Lambda \lambda \mu \nu \Omega \omega \omicron \Phi \phi \Pi \pi \Psi \psi \rho \Sigma \sigma \tau \Theta \theta \Upsilon \upsilon \Xi \xi \zeta` | Greek letters, each one symbol |
| `\varDelta \varepsilon \varGamma \varkappa \varLambda \varOmega \varPhi \varphi \varPi \varPsi \varrho \varSigma \varsigma \varTheta \vartheta \varUpsilon \varXi` | variant letterforms: each the letter after `var` |
| `\dagger \ell \hbar \imath \infty \intercal \jmath \odot \oplus \star \top \varpi` | symbols; `\odot` is the Sun, as in `M_\odot`, and between tensors the elementwise product; `\oplus` between matrices is their direct sum, `A^\top`, `A^\intercal` and `A^\dagger` of a matrix its transpose and its conjugate transpose, and `\imath` and `\jmath` are i and j, under a hat unit vectors |
| `\arccos \arccot \arcsin \arctan \arg \cos \cosh \cot \coth \csc \csch \det \dim \exp \gcd \Im \ker \ln \log \max \min \Pr \Re \sec \sech \sgn \sin \sinh \tan \tanh` | functions, each calling the builtin of its name, except that `\arccos` calls `acos`, `\arccot` calls `acot`, `\arcsin` calls `asin`, `\arctan` calls `atan`, `\Im` calls `im`, `\ker` calls `null`, `\Re` calls `re`, `\sgn` calls `sign`; `\sin^{-1}` is the inverse, and only `\log` takes a subscript, its base; `\Pr` is a probability |
| `\bar \breve \check \ddot \dot \hat \overline \tilde \vec \widehat \widetilde` | accents: `\dot{a}` and `\ddot{a}` are time derivatives of a function of one variable, `\hat{x}` on a coordinate a unit vector (see Vectors); the others name a new symbol |
| `\ast \cdot \otimes \times` | multiplication, `*`; between tensors, their product, `\otimes` between matrices their Kronecker product, and `\cdot` and `\times` between vectors their dot and cross products |
| `\div` | division, `/` |
| `\lt \gt \le \leq \leqslant \ge \geq \geqslant \ne \neq` | comparisons, in this order: `<`, `>`, `<=` (three spellings), `>=` (three), `!=` (two) |
| `\longrightarrow \mapsto \rightarrow \to` | an arrow, as in `\lim_{x \to 0}` |
| `\coloneq \coloneqq \defeq \equiv \triangleq` | a definition, `:=` |
| `\Vert \lVert \lvert \mid \rVert \rvert \vert` | a bar: absolute values, norms, evaluation bars, and the bar of a bra or a ket |
| `\langle \rangle` | angle brackets: Dirac's notation, with the bar of a bra or a ket; without a bar, an expectation value, `\langle x \rangle`, or an inner product, `\langle u, v \rangle` |
| `\pm \mp` | both signs, so two values |
| `\wedge` | the wedge product |
| `\circ` | composition: read, not computed |
| `\approx \asymp \cong \doteq \gg \in \leftrightarrow \ll \longleftrightarrow \notin \prec \preceq \propto \sim \simeq \subset \subseteq \succ \succeq \supset \supseteq` | relations, read so that the equations around them run, but not computed; `\in` also declares index labels |
| `\iff \implies \Leftrightarrow \Longleftrightarrow \Longrightarrow \Rightarrow` | between equations, each side a statement |
| `\cdots \ddots \dots \dotsb \dotsc \dotsi \dotsm \dotso \ldots \vdots` | terms not written: read, not computed |
| `\hbox \mbox \operatorname \text \textbf \textit \textnormal \textrm \textsf \textup` | text: one name, as `\text{otherwise}`; `\operatorname{name}` names a function |
| `\texttt` | a Python object, read by name from the workbook's scope: `\texttt{prices}` (see Python objects) |
| `\bm \boldsymbol \lefteqn \mathbb \mathbf \mathbin \mathcal \mathclose \mathfrak \mathinner \mathit \mathnormal \mathop \mathopen \mathord \mathpunct \mathrel \mathrm \mathscr \mathsf \mathtt \pmb \substack` | typefaces: what they hold is read as it is, so `\mathrm{d}x` is `d x`; bold, calligraphic, script, Fraktur and sans serif make a name of its own where the program defines it in two |
| `\bf \bfseries \boldmath \cal \em \it \itshape \mdseries \mit \normalfont \rm \rmfamily \sc \sf \sl \tt \upshape` | plain TeX's typefaces, for the rest of the group: `{\rm d}x` |
| `\aftergroup \allowbreak \centering \displaybreak \displaystyle \enspace \hfill \hline \hphantom \hspace \label \limits \medspace \negmedspace \negthickspace \negthinspace \noindent \nolimits \nonumber \notag \phantom \qquad \quad \scriptscriptstyle \scriptstyle \tag \textstyle \thickspace \thinspace \vphantom \vspace` | layout, ignored; `\quad` and `\qquad` also separate equations |
| `\Big \Bigg \Biggl \Biggm \Biggr \Bigl \Bigm \Bigr \big \bigg \biggl \biggm \biggr \bigl \bigm \bigr` | delimiter sizes, ignored |
| `\linebreak \newline` | end a statement, as `\\` does |
| `\cases \matrix \pmatrix` | plain TeX's matrices and cases: `\matrix{a & b \cr c & d}` |
| `\cfrac \dfrac \frac \over \tfrac` | fractions, `\frac{a}{b}` and plain TeX's `{a \over b}`; `\frac{d}{dx}` and `\frac{\partial f}{\partial x}` are derivatives |
| `\sqrt` | roots, `\sqrt{x}` and `\sqrt[n]{x}` |
| `\binom \choose \dbinom \tbinom` | binomial coefficients, `\binom{n}{k}` and `{n \choose k}` |
| `\brace \brack` | the Stirling numbers in Karamata's brackets, `{n \brace k}` and `{n \brack k}` |
| `\bmod \mod \pmod` | the remainder, `a \bmod m`, and a congruence, `a \equiv b \pmod{m}` |
| `\circledast` | the circular convolution of sequences, `(x \circledast h)[n]`, of length N with `\circledast_N` |
| `\prod \sum` | a sum, `\sum_{n=1}^{N}`, and a product, in closed form where SymPy finds one |
| `\iiint \iint \int \oint` | integrals, single, double and triple, which end at their differentials: `\int_0^1 f \, dx` |
| `\lim` | a limit, `\lim_{x \to 0}`, or from one side, `\lim_{x \to 0^+}` |
| `\inf \sup \underset` | the supremum and the infimum over a variable, `\sup_{0 \le x < 1} x^n`, as `\max_x` and `\arg\min_w` are optima; `\underset{x}{\min}` sets the variable beneath |
| `\nabla \partial` | the partial and the covariant derivative, `\partial_\mu` and `\nabla_\mu`; `\partial_t^2` is the second derivative, and `\nabla` alone vector calculus's |
| `\Box \square` | the d'Alembertian, `\nabla^\mu \nabla_\mu`, as is `\nabla^2` with a metric in force; without one, `\nabla^2` is the Laplacian |
| `\pounds` | the Lie derivative, `\pounds_V T_{ab}` |
| `\dv \pdv` | the physics package's derivatives: `\pdv{f}{x}`, `\pdv[2]{f}{x}`, `\dv{f}{x}` |
| `\bra \braket \expval \ket \ketbra \mel` | Dirac's notation as the physics and braket packages write it: `\ket{\psi}`, `\bra{\phi}`, `\braket{\phi}{\psi}`, `\ketbra{a}{b}`, `\expval{A}` and `\mel{\phi}{A}{\psi}` |
| `\lceil \lfloor \rceil \rfloor` | the floor `\lfloor x \rfloor` and the ceiling |
| `\left \middle \right` | `\left( ... \right)` groups, with any delimiters; between bars it is an absolute value, from `\left.` to a bar with `_{x=a}` an evaluation bar, and between angle brackets, with `\middle` before the bar, Dirac's notation |
| `\begin \end` | an environment, `\begin{pmatrix} ... \end{pmatrix}` |
| `\bgroup \egroup` | plain TeX's braces |
| `\cr` | ends a row of plain TeX's `\matrix` and `\cases` |
| `\overset \stackrel` | a label over a relation: `X_1, \ldots, X_n \overset{\text{iid}}{\sim} \mathcal{N}(0, 1)` declares independent random variables |
| `\mathbb` | blackboard bold: `\mathbb{R}^{n}` and `\mathbb{C}^{n}` are spaces, `\mathbb{E}_t` an expectation and `\mathbb{1}_a` the covector of ones |
### Environments
| Environment | Meaning |
|---|---|
| `array`, `Bmatrix`, `bmatrix`, `matrix`, `pmatrix`, `smallmatrix`, `Vmatrix`, `vmatrix` | a matrix; `vmatrix` is its determinant |
| `cases`, `dcases` | a piecewise function, with `\text{if}` and `\text{otherwise}` |
| `align`, `align*`, `alignat`, `alignat*`, `aligned`, `alignedat`, `dgroup`, `dgroup*`, `dmath`, `dmath*`, `eqnarray`, `eqnarray*`, `equation`, `equation*`, `flalign`, `flalign*`, `gather`, `gather*`, `gathered`, `IEEEeqnarray`, `IEEEeqnarray*`, `math`, `multline`, `multline*`, `split` | statements, separated by `\\` |
- In `align`, `align*`, `alignat`, `alignat*`, `aligned`, `alignedat`, `flalign`, `flalign*`, each pair of columns is an equation; `multline`, `multline*` holds one equation, broken over rows.
- `alignat`, `alignat*`, `alignedat`, `array`, `IEEEeqnarray`, `IEEEeqnarray*` take an argument first, such as the columns of `array`.
- `relativisticpy check` reads the equation environments of a document as displays, with `displaymath`, `$$ ... $$` and `\[ ... \]`; it reads `aligned`, `alignedat`, `gathered`, `split` inside them.
### Not supported
These commands are LaTeX's, or a package's, but not the language's. Each is an error that says what to write instead:
- `\abs`: the physics package's absolute value; write `|x|`, or `\left| x \right|`.
- `\dd`: the physics package's differential; write `d x`, or `\mathrm{d} x`.
- `\def \let \newcommand \providecommand \renewcommand`: defines a macro, which a program cannot; write what it stands for; relativisticpy check reads the macros of a document.
- `\eval`: the physics package's evaluation bar; write `\left. f \right|_{x=0}`.
- `\exists`: the quantifier; write `\text{there is}`.
- `\forall`: the quantifier; write `\text{for all}`.
- `\liminf \limsup`: write `\lim_{x \to a}` for a limit.
- `\norm`: the physics package's norm; write `\| x \|`.
- `\not`: write `\neq` for not equal, or `\notin`.
- `\order`: the physics package's order; write the terms out, or `\mathcal{O}(x^2)` as a symbol.
- `\qty`: the physics package's brackets; write `\left( ... \right)`.
- `\Tr`: the physics package's trace; write `\operatorname{Tr}(A)`, or contract the indices: `A^{a}_{a}`.
- `\tr`: the physics package's trace; write `\operatorname{tr}(A)`, or contract the indices: `A^{a}_{a}`.
- `\va`: the physics package's vector arrow; write `\vec{v}`.
- `\vb`: the physics package's bold vector; write `\mathbf{v}`.
### Unicode
Unicode reads as the LaTeX it stands for. A Greek letter, `θ`, is its command, and so are ∂ `\partial`, ∇ `\nabla`, √ `\sqrt`, ∑ `\sum`, ∏ `\prod`, ∫ `\int`, ∬ `\iint`, ∭ `\iiint`, ∮ `\oint`, ⊛ `\circledast`, ⌊ `\lfloor`, ⌋ `\rfloor`, ⌈ `\lceil`, ⌉ `\rceil`. The operators · ⋅ ∗ × ÷ ⁄ − ≤ ≥ ≠ → ↦ ≡ ≔ ′ ± ∓ ∧ ∘ ⊗ ‖ ⟨ ⟩ 〈 〉 … ⋯ and the relations ∼ ≃ ≈ ≅ ∝ ≪ ≫ ∈ ∉ ⊂ ⊆ ↔ are LaTeX's. Superscripts and subscripts are scripts, letters too, so `r²` is `r^{2}`, `rₛ` is `r_{s}` and `Aᵀ` is `A^{T}`, † after a matrix is `^\dagger`, ⊕ is `\oplus`, and the double-struck letters, ℝ ℂ 𝔼 𝟙, are `\mathbb`'s. ∛ and ∜ are `\sqrt[3]` and `\sqrt[4]`, and a vulgar fraction, ½, and the fraction slash, `3⁄4`, are fractions. A combining accent, as in ȧ, is an error that names it: write the command, `\dot{a}`.
## Verdicts of a check
`relativisticpy check paper.tex`, or `wb.check(document)` in Python, runs the display equations of a document in order and gives each statement a verdict.
| Mark | Verdict | Meaning | Fails `--strict` |
|---|---|---|---|
| ✓ | holds | proven equal | no |
| ✗ | differs | of known quantities, whose sides are not equal: a mistake, or a condition | yes |
| ↔ | relates | relations between quantities nothing defines, not identities | no |
| ✗ | ill-formed | notation that breaks the rules of index notation | yes |
| = | defines | definitions | no |
| → | computes | expressions, computed | no |
| ~ | not computed | relations read but not decided, or over the time limit | over a time limit |
| ? | not understood | what RelativisticPy cannot do yet | no |
| ! | not parsed | not read | yes |
`--strict` also fails on a document in which no equation was found. A report lists the statements that are `differs` `ill-formed` `not parsed`, and counts the rest; `--all` lists every one. In Python, `report.failed(...)` takes the verdicts to fail on, and `time limit` and `empty` besides.
## Errors
Every error a user can cause is a `RelativisticPyError`. It says what is wrong, where, as `--> file:line:column` with the text underlined, why, in a `note:`, and how to fix it, in a `hint:`. `error.to_dict()` gives the same as data.
| Error | When |
|---|---|
| `ParseError` | the source text is not valid RelativisticPy (raised by the lexer and parser) |
| `CompileError` | a well-formed statement does not make sense: an unknown tensor, a function called with the wrong number of arguments, a metric without coordinates |
| `IndexNotationError` | tensor indices break the rules of index notation: mismatched free indices in a sum, an index repeated three times, two lower indices summed together |
| `NotComputedError` | a statement RelativisticPy reads but does not compute: a relation such as `≈`, `∝` or `→`, a condition on a coordinate, `\theta = \pi/2`, or a relation between differentials |
| `EvaluationError` | a computation failed while running: a degenerate metric, an equation SymPy cannot solve |
| `MetricError` | a metric that cannot be one: not square, not symmetric, or degenerate |
| `DataError` | data bound from Python, as by `wb["w^a"] = ...`, cannot be bound as written: it is ragged, it does not have an axis for each index, or its labels are not the elements of its space |
| `UnknownNameError` | a name looked up from Python, as in `wb["T"]`, that nothing defines |
| `UsageError` | a call from Python was given what it cannot take: `wb.exe(123)`, a backend that does not exist, a time limit of no seconds |
| `FileError` | a file cannot be read: it does not exist, or it is not UTF-8 text |
| `UndecidedError` | an equation was asked for a truth value it does not have, or a program claims one that is not decided: SymPy could not show its sides equal, nor numbers show that they differ |
| `InternalError` | a failure of RelativisticPy's own: never a mistake in the input |
# Integrations
> **For:** contributors and agents who add what the language can compute, from SymPy,
> SciPy or any other library. **You will learn:** what an integration is, how to write
> one step by step, and how the conformance suite checks it. **Before this:**
> [How it works](architecture.md).
Every function the language knows, from `sin` to `Schwarzschild`, is a *capability* that
an *integration* declares. An integration is a Python module in
`src/relativisticpy/integrations/`, named after what it integrates: `elementary.py`,
`algebra.py`, `spacetimes.py`. There is no configuration: no registry of strings and no
list to keep in sync. The package is scanned, so adding the module is enough, and the
conformance suite holds every capability to one pattern, saying in words what to fix.
## What a capability declares
A capability is a class whose methods compute it, decorated with its kind. The kind says
how the language treats it:
| Kind | What it is | Examples |
|---|---|---|
| `function` | scalar in, scalar out; applied to each component of a tensor, and to data | `sin`, `simplify`, `gamma` |
| `map_function` | a function of a matrix; given a map written with its indices, of its matrix of components | `det`, `rank`, `expm` |
| `solver` | equations in, solutions out | `solve`, `dsolve` |
| `constructor` | builds an object the language works with | `Schwarzschild`, `Eq`, `symbols` |
| `transform` | a function of a variable in, a function of another out; or data over an index in, data over a new space out | `LaplaceTransform`, `FourierTransform`, `fft` |
| `rewrite` | a faster computation of what a program writes, to the same numbers | the DFT written as its sum, computed by `fft` |
| `optimizer` | a problem of optimisation in, its optimum out, with how it was found and whether it is global | SymPy's stationary points and simplex method, SciPy's `linprog` and `minimize` |
| `distribution` | the law of a random variable, written after `\sim` | `\mathcal{N}(\mu, \sigma^2)`, `\operatorname{Poisson}(\lambda)`, `\chi^2_k` |
| `python_object` | what a Python object read by name, `\texttt{prices}`, becomes | NumPy arrays, pandas tables, SymPy expressions, functions |
The decorator takes, by name:
- `summary`: one phrase, with which `relativisticpy help NAME` begins its description;
- `examples`: two or more `Example(program, answer, source)`, each a program that uses the
capability and the value of its last output, known from *outside* the integration: a
closed form with its place in a book, `"DLMF 10.8.1"`, or the library called directly,
`"scipy.special.jv(0, 1.5)"`, which the tests run, and hold to the answer. One example
may say `"standard"` of an answer every book has, but not all of them;
- `requires`: the library it needs beyond SymPy, as pip installs it, if any;
- `aliases`: other names it is called by, as `arcsin` for `asin`;
- for a function, `points`: arguments it is checked at, where it has a value. Without
them, each argument takes 0.3, 0.7 and 1.6. And `lifts=False` for a function that takes
its arguments whole, as `min` does; and `integers`, the parameters of a function of
integers, as `n` of Euler's totient: a form written with a letter, `\varphi(n)`, reads
as it only where they are integers, and a call prints by its name where they are not.
And `gives_form=True` for one whose value is a form of its argument, as `factor`'s is:
it is shown as it is computed, never tidied into another form, and its examples are
held to the form of their answers;
- for a function of a matrix, `points` too, each matrix a list of its rows, as
`points=[([[2, 1], [1, 3]],)]`, and `scalar=True` where its value is a number, as a
trace's. It acts on a map written with its indices, `A^{a}{}_{b}`, unless `lifts=False`,
where its value is over other spaces, as a Kronecker product's is.
The class has an `exact` method, which computes with SymPy, and may have a `numeric`
method, which computes with arrays: `xp` is the array module of the data, NumPy's or
JAX's. The parameters of `exact` are the declaration of the arguments: how many a call
takes, and their names in the reference. A library is imported inside the methods, never
at the top of the module, so that the language runs without it; when it is missing, the
user is told what to install.
A `transform` of functions declares the `variables` it maps by convention, a pair for each
convention the letters choose, as ℱ takes `("x", "s")` or `("t", "omega")`; the transform
that undoes it, its `inverse`; and, as `points`, functions it is checked on. Its class has
an `exact(self, f, t=None, s=None)` method, and an `integral` method, which writes it as
the integral or the sum it stands for, unevaluated: the language names the variables and
reads the transform as books write it, `\mathcal{L}\{f\}(s)`, from its forms. A
transform of data has instead a `space(self, over)` method, which gives the space
its result is over, of the samples' frequencies for `fft`, and `numeric(self, xp, x)`,
which computes it along the first axis. The transforms of functions are declared in
`integrations/transforms.py`, and the FFT, with its rewrite, in `integrations/fft.py`.
A `rewrite` declares, in its `latex` form, the sum it stands for, and the capability that
`computes` it faster; its class has a `matches(self, kernel, n, k, size)` method, which,
given the kernel of a sum over data in the positions of its two indices, gives the factor
by which the sum is that computation, or `None`. The DFT written as its sum,
\(\sum_{n=0}^{N-1} x_n e^{-2\pi i k n/N}\), is so computed by `fft`.
An `optimizer` finds the optimum of a `Problem`: the greatest or least value of an
objective, a SymPy expression of its variables, real or whole numbers, subject to
equalities, each 0 where it holds, and inequalities, each at least 0. Its class has a
`takes(self, problem)` method, which says whether it solves a problem, and an
`optimum(self, problem)` method, which gives a `Found`, the value, the point, how it was
found and whether it is proven global, or `None`, so that the next optimizer is asked. It
declares `problems` it is checked at, and `numerical=True` where its answers are numbers
found numerically. An optimum a program writes, `\min_{x} f(x)`, is never a call: the
optimizers are asked in turn as it runs, the exact ones first. SymPy's are in
`integrations/sympy_optima.py`, and SciPy's in `integrations/scipy_optimize.py`:
```python
>>> import sympy
>>> from relativisticpy import integrations
>>> from relativisticpy.integrations import Example, Found, Problem, optimizer
>>> x = sympy.Symbol("x", real=True)
>>> @optimizer(
... "vertex",
... summary="the vertex of a parabola, at -b/2a",
... problems=[Problem("min", x**2 - 4*x + 7, (x,))],
... examples=[
... Example(r"\min_{x} \left(x^2 - 4x + 7\right)", 3, "standard: (x - 2)^2 + 3"),
... Example(r"\arg\min_{x} \left(x^2 - 2x\right)", 1, "standard: (x - 1)^2 - 1"),
... ],
... )
... class Vertex:
... def takes(self, problem):
... return problem.degree() == 2 and len(problem.variables) == 1
...
... def optimum(self, problem):
... (v,) = problem.variables
... a, b = sympy.Poly(problem.objective, v).all_coeffs()[:2]
... point = -b / (2 * a)
... return Found(problem.at((point,)), (point,), "at -b/2a", proven=bool(a > 0))
>>> integrations.check(Vertex, ["feasibility", "optimality"])
{'feasibility': [], 'optimality': []}
```
A `distribution` is the law a random variable is declared with, `X \sim
\mathcal{N}(\mu, \sigma^2)` (see [Random variables](probability.md)). Its `exact`
gives SymPy's law of its parameters, and its `numeric` SciPy's frozen law; its class has
`mean` and `variance` methods, the closed forms of its moments, whose source it declares as
`moments`, and may have `mgf(t, ...)`, its moment-generating function, where SymPy's law has
none. Its forms are read after `\sim` alone, so that `\Gamma(k, \theta)` never takes the
place of a function written `\Gamma(a, x)`, and their variables are its parameters in order:
`\sigma^2` in `\mathcal{N}(\mu, \sigma^2)` says that the second argument is the square of
the second parameter. The distributions are in `integrations/sympy_stats.py`:
```python
>>> from relativisticpy.integrations import distribution
>>> @distribution(
... "Laplace",
... latex=r"\operatorname{Laplace}(\mu, b)",
... summary="the Laplace distribution, of mean μ and scale b",
... requires="scipy",
... moments="Johnson, Kotz and Balakrishnan (1995), chapter 24",
... examples=[
... Example("X \\sim \\operatorname{Laplace}(0, 1)\n\\operatorname{Var}(X)", 2,
... "scipy.stats.laplace.var()"),
... Example("X \\sim \\operatorname{Laplace}(0, 1)\n\\Pr(X > 1)", 0.18393972058572117,
... "scipy.stats.laplace.sf(1)"),
... ],
... points=[(0, 1), (1, 2)],
... )
... class Laplace:
... def exact(self, mu, b):
... from sympy.stats.crv_types import LaplaceDistribution
...
... return LaplaceDistribution(mu, b)
...
... def numeric(self, xp, mu, b):
... from scipy.stats import laplace
...
... return laplace(mu, b)
...
... def mean(self, mu, b):
... return mu
...
... def variance(self, mu, b):
... return 2 * b**2
>>> integrations.check(Laplace, ["examples", "agreement", "density", "moments"])
{'examples': [], 'agreement': [], 'density': [], 'moments': []}
```
## Written forms
A capability is called by its name in plain text, `gamma(x)`, and is written in books in
forms of its own, which it declares in the language itself: `latex=r"\Gamma(x)"` and
`unicode="Γ(x)"`. Each form is parsed once, by the language's own parser, into a pattern:
the name it is written with and how that name is set, its scripts, and its arguments,
each named after a parameter of `exact`. A program that writes the same shape is read as
the capability, and a result prints in the first form, so that it reads back:
```python
>>> from relativisticpy import Workbook, display
>>> wb = Workbook()
>>> wb.expr(r"\Gamma\left(\tfrac{1}{2}\right)")
sqrt(pi)
>>> display.latex(wb.expr(r"\Gamma(x)"))
'\\Gamma\\left(x\\right)'
```
The reader follows the notation decisions of the project (`design/notation.md`, 15): a
definition in the program always wins, a script that is an index label is an index, so
that `\Gamma^{\lambda}_{\mu\nu}` stays the Christoffel symbol, and a name of one letter
called with the coordinates, as the lapse `N(t)` in a metric, is a function of them.
`Workbook.explain` shows each reading, and a note says where a name of one letter could
have meant a function of the program's own. A function of a matrix written with one letter,
as the spectral radius `\rho(A)`, is read so only where its argument is written as a
matrix, so that `\rho(1 + 3w)` stays a density's; and a form may write the name of a
function as its command, as the `\max` of `\lambda_{\max}(A)`, which a call writes as it
is. The notation of matrices that is no call, as `A^T` and `e^{A t}`, is read in
`reading/matrices.py`, by its operands.
A name books write for a function no integration provides yet is *reserved* in
`integrations/book_names.py`, with what it is: a program that writes it is refused,
saying so, rather than reading it as an unknown function. A capability of the same name
retires the reservation.
## Adding one, step by step
1. **Find the gap.** `uv run python benchmarks/curriculum.py --failures` names what the
language cannot do yet: an unknown function, a notation it does not read.
2. **Write the capability,** in the integration of its library, following a capability of
the same kind: `bessel.py`, `polynomials.py` and `special_functions.py` are functions
written as books write them, exact with SymPy and numeric with SciPy. Here is a complete
one, the logistic function:
```python
>>> import sympy
>>> from relativisticpy.integrations import Example, function
>>> @function(
... "expit",
... summary="the logistic function, 1/(1 + e^{-x})",
... requires="scipy",
... examples=[
... Example("expit(0)", sympy.Rational(1, 2), "standard"),
... Example("expit(2)", 0.8807970779778823, "scipy.special.expit(2.0)"),
... ],
... )
... class Logistic:
... def exact(self, x):
... return 1 / (1 + sympy.exp(-x))
...
... def numeric(self, xp, x):
... from scipy.special import expit
...
... return expit(x)
```
3. **Check it.** `relativisticpy.integrations.check` runs the conformance suite on one
capability, before it is part of an integration, and gives the failures of each check,
none where it passes:
```python
>>> from relativisticpy import integrations
>>> integrations.check(Logistic)
{'declaration': [], 'examples': [], 'agreement': [], 'lifting': [], 'errors': [],
'display': [], 'reference': []}
```
In the package, `uv run pytest tests/integrations -k expit` runs the same checks.
4. **Run the curriculum.** `uv run python benchmarks/curriculum.py --update` records the
cases the capability makes pass in `curriculum/passing.txt`, and
`uv run python -m relativisticpy.reference --write docs/reference.md` writes the
reference again, from the declarations.
Nothing else is edited: the registry, the compiler and the reference read the
declarations.
## The conformance suite
`tests/integrations` runs thirteen checks for every capability the scan finds, each where
it applies to its kind. A failure names the capability and says what to do:
1. **Declaration.** Its names are its own, and the language reads each as one name; it
has a summary, at least two examples, each with its source, one at least a book or
the library called directly, and declares the library it needs, which is imported only
when it is used. Each written form reads as it, under
a name that is no other capability's: `N(x)` could not be the normal distribution
function, as `N` is numerical evaluation.
2. **Examples.** Each runs in the language, calls the capability, and gives its answer,
in the answer's form where the capability gives a form; an optimizer's is found by it.
3. **Agreement.** `exact` and `numeric` agree at each point, `numeric` takes arrays of the
points at once, and JAX agrees with NumPy where it is installed; of a function of a
matrix, entry by entry, at each matrix; of an optimizer, at each problem it declares,
the optimizers of the other kind, exact or numeric, that take it find the same value,
and none a better one than an optimum proven global; of a distribution, its density and
distribution function, as the language computes them exactly, agree with SciPy's.
4. **Lifting.** A function applied to a tensor, or to data, gives its value at each
component, over the same space, and applied to data past its points too: below 0, far
beyond them, between whole numbers and off the real line, where it gives the value
`exact` gives, complex where that is, or refuses where `exact` refuses, never nan or a
real part alone. A function of a matrix, applied to a map, gives its value at the map's
matrix, a number or a map over the same space.
5. **Errors.** The wrong number of arguments and a missing library are refused, saying
what to do; the wrong kind of argument, a list to a function or text in quotes to
anything else, never fails inside RelativisticPy.
6. **Display.** A call prints in text, Unicode, LaTeX and data, and each reads back as the
same value.
7. **Reference.** The language reference indexes it, by its names and forms, and
`relativisticpy help NAME` describes it in full, both from its declaration.
8. **Transform.** A transform of functions agrees with the integral or the sum it stands
for at points, and its inverse gives back what it transformed; a transform of data
agrees with its sum, its inverse undoes it, it keeps Parseval's relation, and its
result is over a space of the size and the labels it declares.
9. **Rewrite.** Each example of a rewrite is computed by what it names, and gives the
numbers it gives computed as written.
10. **Feasibility.** At each problem an optimizer declares, the point it reports keeps
every constraint, and the value it reports is the objective there.
11. **Optimality.** At that point, the conditions of optimality hold: of a smooth problem,
the KKT conditions, the gradient of the objective a combination of the gradients of the
constraints that hold there with equality, with multipliers of the right signs; over
finitely many points, no feasible point is better.
12. **Density.** At each of its points, a distribution's density integrates, or sums, to 1,
by SymPy, or by SciPy where SymPy cannot in time.
13. **Moments.** There, its mean and variance, as SymPy and SciPy compute them, are those
it declares.
A capability that breaks the pattern is told, for instance:
```text
brokenj's example brokenj(0) gives 0, not 2: fix exact, or the example's answer
brokenj: numeric and exact differ at (x=0.3): numeric gives 0.955336489126, exact
0.0141169980066; fix numeric, or, if the point is outside where it is defined, declare
points=[...] inside
brokenj: its module imports scipy when it is imported; import it inside exact or
numeric, and declare requires="scipy", so that the language runs without it
brokenj: fresnels(x) prints in latex as S\left(x\right), which reads back as S(x), in
which S is a function the language does not know; declare a latex form the language
reads as brokenj, as latex="J_{\nu}(x)"
```
A form may write a parameter that is known when the program is read, as the counts p and
q of `{}_pF_q(a; b; z)`: `exact` takes it by keyword, `def exact(self, a, b, z, *, p=None,
q=None)`, and checks it. A capability whose calls print other than by its parameters in
order says how, with a method `arguments(self, call)` that gives the value of each, as
the hypergeometric function does in `special_functions.py`.
## Python objects
An object integration says what a family of Python objects becomes when a program reads
one by name, as `\texttt{prices}` (see [Beyond spacetime](spaces.md#python-objects-by-name)):
a `Scalar`, a number or an expression; `Data`, an array with the labels and the name of
each axis, where the object has them, by which data from two objects meets; an `Array`, a
vector or a matrix, as the language's lists are; or a `PythonFunction`, called on numbers
and elementwise on data. It declares the classes it `takes`, by their module and name,
which takes their subclasses too, or a protocol, by its method, as `"__array__"`. The
most specific class an object has decides, then a protocol, a function last. Nothing is
imported to tell: no object of a library's class exists without the library. Its
examples are given the objects their programs read:
```python
>>> import datetime
>>> from relativisticpy.integrations import Scalar, python_object
>>> @python_object(
... "durations",
... takes="datetime.timedelta",
... summary="a duration: its seconds, a number",
... examples=[
... Example(r"\texttt{lap} / 60", 3, "three minutes",
... given=lambda: {"lap": datetime.timedelta(minutes=3)}),
... Example(r"\texttt{day}", 86400, "a day",
... given=lambda: {"day": datetime.timedelta(days=1)}),
... ],
... )
... class Durations:
... def becomes(self, value):
... return Scalar(value.total_seconds())
>>> integrations.check(Durations)
{'declaration': [], 'examples': [], 'errors': [], 'reference': []}
```
Its checks are four: the declaration; the examples, each run in a workbook given its
objects; that what its objects become, called, added and given to a function, is computed
or refused, never a failure inside RelativisticPy; and the reference, which lists what
each object becomes. `numpy_arrays.py`, `pandas_tables.py` and `python.py` are
integrations of this kind.
## Integrations outside RelativisticPy
A package of its own contributes through the entry-point group
`relativisticpy.integrations`, Python's standard mechanism. Each entry point names a
module of capabilities, a capability, or a list of them:
```toml
[project.entry-points."relativisticpy.integrations"]
mylibrary = "mypackage.relativisticpy_integration"
```
The capabilities are found when the language first needs them. An entry point that fails
to load is a warning that names it, never a language that does not start.
**Next:** [the language reference](reference.md), which lists every capability, each of
which `relativisticpy help NAME` describes in full.
# Python API
> **For:** programmers and agents who use RelativisticPy from Python. **You will learn:**
> the workbook, every kind of result, whether a claim holds, how results are shown, and
> errors. **Before this:** [Getting started](getting-started.md).
Everything the language does is available from Python, and the language's
results are ordinary Python values. This page is the reference: the
[Workbook](#workbook), then what each result is, how to ask whether a claim
holds, and how results are shown. Write LaTeX in raw strings, `r"..."`, and see
[the language reference](reference.md) for what a program may say.
## Workbook
```python
>>> from relativisticpy import Workbook
>>> wb = Workbook(workers=1)
```
| Method | What it does |
|---|---|
| `wb.expr(source)` | run a program; the value of its last expression, or `None` |
| `wb.exe(source)` (also `wb.run`) | run a program; the value of every expression, as a list |
| `wb.each(source)` | run a program one statement at a time, carrying on after errors; one `Step` per statement |
| `wb.run_file(path)` | run a file; in a Markdown file the `$$...$$` blocks are the program |
| `wb.check(document)` | run the equations of a LaTeX document or notebook and give a verdict on each, a `Report`: see [Checking papers](checking.md). A string is a path; pass LaTeX text as `Document(text, name)` |
| `wb.markdown(text)` | run a Markdown document's `$$...$$` blocks and typeset the results after each |
| `wb[name]` | the value bound to a name |
| `wb["R_{ta}"] = data` | bind data: a NumPy array, pandas DataFrame or Series, SciPy sparse matrix, SymPy array or list (see [Beyond spacetime](spaces.md)) |
| `wb.space(name, dim, basis=, labels=, field=, measure=)` | declare a space for indices to range over, with its basis, labels, field (`"real"` or `"complex"`) and the weights of its expectations; returns the `Space` |
| `wb.grad(source, wrt)` | the gradient of a scalar with respect to bound data, by automatic differentiation with JAX |
| `wb.metric`, `wb.coordinates` | the metric in force (a `Metric`) and the coordinates |
| `wb.copy()` | a workbook in the same state, whose definitions are its own from then on; it shares what has been computed |
| `wb.ir(source)` | the IR a program compiles to, as text |
| `wb.explain(source)` | how each statement is read, and why: see [How a statement is read](#how-a-statement-is-read) |
| `wb.tokens(source)`, `wb.parse(source)` | the tokens and syntax tree |
| `wb.reset()` | forget every definition |
`workers` sets how many processes share component-wise work such as
simplification (`None` for one per CPU). `backend="jax"` keeps bound data as JAX
arrays, so that it is computed with JAX. `scope=globals()` is where programs read
Python objects by name, as `\texttt{prices}` (see
[Beyond spacetime](spaces.md#python-objects-by-name)). A workbook is a context manager,
which stops its workers on exit. To reproduce a run exactly, start Python with
`PYTHONHASHSEED=0`, as the command line starts itself: a workbook cannot fix the seed of
the Python it runs in (see
[Troubleshooting](troubleshooting.md#a-result-changed-from-one-run-to-the-next)).
```python
>>> wb.exe(r"""
... Coordinates := [x, y]
... V^{a} := [y, -x]
... V^{a}
... """)
[V^a in (x, y): 2 components non-zero
V^x = y
V^y = −x]
>>> wb["V"].components
[y, -x]
```
`each` is how a document can be run as a whole even where some of it fails:
```python
>>> for step in Workbook().each("x := 2; R_{ab}; x + 1"):
... print(step.error.message if step.error else step.values)
[]
the Ricci tensor needs coordinates
[3]
```
Errors in syntax are raised before anything runs. Each `Step` has the
statement's `span` and `statement` (its syntax tree), its `values` (an empty list
for a definition) or its `error`, for an equation the values of its two `sides`,
and `notes` on how the statement was read where that could surprise. `zero`
says whether an equation's two sides are both zero.
## How a statement is read
`wb.explain(source)` says how each statement of a program is read, and why: how each
name was resolved, against what the workbook defines, its coordinates and the built-in
names; each ambiguous form decided, with why: a definition or a claim, notation or
components, a product or a call, an index or a power, a run of letters, a constant or a
symbol, a function named without its argument; and the notes given where the less
likely reading was taken. Nothing is computed, and nothing is defined: as with `wb.ir`,
the workbook is left as it was. Printed, the readings are text, with the values known
without computing shown as results are:
```python
>>> wb = Workbook()
>>> wb.exe(r"Coordinates := [t, r]" "\n" r"g_{\mu\nu} := diag(-(1 - 2M/r), 1)" "\n" "K := 2")
[]
>>> explanation = wb.explain(r"""
... K = \frac{2GM}{r}
... e^{i\pi} + \Gamma^t_{tr}
... """)
>>> print(explanation)
line 2: K = \frac{2GM}{r}
definition or claim: K = ... is a claim, since K already has a value
letters: GM is G M, since in LaTeX a run of letters that names nothing is a product
K: a value, defined on line 3, 2
G: a symbol
M: a symbol the metric is written with
r: a coordinate
note: K already has a value, so = compares it; to give K a new value, write K := ...
line 3: e^{i\pi} + \Gamma^t_{tr}
constant or symbol: e is a constant, since nothing defines e
index or power: e^{i\pi} is a power, since e is not a tensor
constant or symbol: i is a constant, since nothing defines i
constant or symbol: \pi is a constant, since nothing defines \pi
index or power: \Gamma^t_{tr} is a tensor with its indices, since \Gamma is the Christoffel connection
e: a constant, e
i: a constant, i
\pi: a constant, π
```
Each reading is a `Reading`, with the statement's `span`; its `names`, each a
`Resolution` with what is `written`, its `meaning` and, where it is known without
computing, its `value`; its `decisions`, each a `Decision` with its `kind`, what is
`written`, the `reading` taken, `why`, and the `note` given, if any; its `notes`; and
the `error` the statement gives, if it gives one, without stopping the readings after
it:
```python
>>> reading = explanation[0]
>>> [(decision.kind, decision.reading) for decision in reading.decisions]
[('definition or claim', 'a claim'), ('letters', 'G M')]
>>> reading.names[0].value
2
>>> print(wb.explain("T_{ab} + v_a")[0].error.message)
T is not a tensor
```
## Results
What a program gives back depends on what it computes:
| Result | Is | Holds? | Shown |
|---|---|---|---|
| a number or an expression | a SymPy value: `48*M**2/r**6` | not a claim | `48M²/r⁶` |
| a claim of scalars | `True`, `False`, or SymPy's `Eq`, `Ne`, `<`, ... | `holds(value)` | `x² + y² = 1` |
| a tensor with components | a [`Tensor`](#tensor) | not a claim | its name, then a line for each component |
| a metric | a [`Metric`](#metric), a `Tensor` | not a claim | its line element |
| an equation of tensors | a [`TensorEquation`](#tensorequation) | `.holds()`, `bool()` | whether it holds, and where not |
| index notation | an [`IndexEquation` or `IndexExpression`](#index-notation) | `.holds()`, `bool()` | the notation |
| several values | a list | | |
| a statement of a document | a [`Step`](#workbook), from `wb.each` | | |
| a checked document | a [`Report`](#checking-papers) of `Finding`s, from `wb.check` | `Verdict`s | |
| a geodesic | a [`Geodesic`](#geodesics) or the `geodesic_equations` | | its span, or an equation for each coordinate |
## Does it hold?
`relativisticpy.holds(value)` answers for any claim: `True`, `False`, or `None`
where it is not decided, as when SymPy cannot show the sides equal and numbers
cannot show that they differ. Equations of tensors and of index notation have
the same answer as a method, and `bool()` agrees with it:
```python
>>> from relativisticpy import holds
>>> vacuum = Workbook()
>>> vacuum.expr(r"""
... Coordinates := [t, r, \theta, \phi]
... g_{\mu\nu} := Schwarzschild(M)
... """)
>>> holds(vacuum.expr(r"R_{\mu\nu} = 0")), bool(vacuum.expr(r"R_{\mu\nu} = 0"))
(True, True)
>>> vacuum.expr(r"\Gamma^{a}_{bc} = 0").holds()
False
>>> holds(vacuum.expr(r"\Gamma^{r}_{\theta\theta} = -r")) # 2M - r is not -r
False
>>> holds(Workbook().expr(r"G_{\mu\nu} = 8\pi G T_{\mu\nu}")) # a law, not an identity
False
```
Where an equation is not decided, `bool()` is an `UndecidedError`, a
`RelativisticPyError` and a `TypeError`, rather than a guess. A program that states
such a claim gets the same error where the claim is written, rather than the claim
shown as if it were an answer. A value that is no claim, such as `48*M**2/r**6`, is a
`TypeError` for `holds`.
## How results look
Every result is shown in four forms, by `relativisticpy.display`, the one
printer that the command line, the prompt, notebooks, `repr` and the report of
a check all use:
| Function | What it gives |
|---|---|
| `display.unicode(value)` | mathematics for a terminal: `48M²/r⁶`; it is what `repr` shows |
| `display.text(value)` | ASCII in the language's own syntax: `48*M^2/r^6` |
| `display.latex(value)` | LaTeX for MathJax, KaTeX and papers: `\frac{48 M^{2}}{r^{6}}` |
| `display.data(value)` | a JSON-serialisable description: its `kind`, its three forms and its structure |
| `display.html(value)` | HTML for notebooks: numerical data as a table |
```python
>>> from relativisticpy import display
>>> K = vacuum.expr(r"R_{abcd} R^{abcd}")
>>> display.unicode(K), display.text(K), display.latex(K)
('48M²/r⁶', '48*M^2/r^6', '\\frac{48 M^{2}}{r^{6}}')
>>> display.data(K)["kind"]
'expression'
```
The text and LaTeX forms read back: the language parses them as the value they
show, and so does the Unicode form wherever the language reads Unicode.
Euler's number is `e` and the imaginary unit `i`, so that a symbol `E` is never
shown as either; numbers are shown as written, and an integer too long to read
is shortened, with its number of digits:
```python
>>> display.unicode(Workbook().expr("E + e")), display.unicode(Workbook().expr("0.1 + 0.2"))
('E + e', '0.30000000000000004')
>>> display.unicode(Workbook().expr("10000!"))
'2.846259680917054…×10³⁵⁶⁵⁹ (an integer of 35,660 digits)'
>>> display.text(Workbook().expr(r"\lambda + \beta x + M_\odot"))
'M_odot + \\beta*x + \\lambda'
>>> display.latex(Workbook().expr(r"M_\odot + \rho_{\rm vac}"))
'M_{\\odot} + \\rho_{\\mathrm{vac}}'
```
A result that RelativisticPy does not know shows itself in a form by a method
`_display_unicode`, `_display_text`, `_display_latex` or `_display_data`, where
it has one.
## Tensor
A `Tensor` has `components` (a SymPy array whose axes follow `indices`, or a
numerical array), `indices`, `coordinates`, an optional `name`, the `spaces` its
axes range over, and the `source` it is the value of, as written, where it has no
name of its own. Arithmetic follows index notation: `+` aligns operands by index
name, and `*` sums over every index that appears once up and once down. A
tensor is shown by its name and indices, then a line for each non-zero
component, labelled by coordinate; components equal, or opposite, by an
exchange of indices share a line:
```python
>>> from sympy import symbols
>>> from relativisticpy import Tensor
>>> t, x = symbols("t x")
>>> eta = Tensor([[-1, 0], [0, 1]], "_{a b}", (t, x), name="eta")
>>> v = Tensor([2, 3], "^{b}", (t, x), name="v")
>>> eta * v
η_{ab} v^b in (t, x): 2 components non-zero
η_{tb} v^b = −2
η_{xb} v^b = 3
>>> eta * v * v.relabel("^{a}")
5
>>> vacuum.expr(r"\Gamma^{a}_{bc}")
Γ^a_{bc} in (t, r, θ, φ): 13 of 64 components non-zero
Γ^t_{tr} = Γ^t_{rt} = M/(r (r − 2M))
Γ^r_{tt} = M (r − 2M)/r³
Γ^r_{rr} = M/(r (2M − r))
Γ^r_{θθ} = 2M − r
Γ^r_{φφ} = (2M − r) sin(θ)²
Γ^θ_{rθ} = Γ^θ_{θr} = 1/r
Γ^θ_{φφ} = −sin(θ) cos(θ)
Γ^φ_{rφ} = Γ^φ_{φr} = 1/r
Γ^φ_{θφ} = Γ^φ_{φθ} = cos(θ)/sin(θ)
>>> vacuum.expr(r"R_{\mu\nu}")
R_{μν} = 0
```
Each line reads back as a claim: `Γ^t_{tr} = M/(r (r − 2M))` is true in this
workbook. Components are taken by position or by name, and a slice is the
tensor of the components it leaves free:
```python
>>> gamma = vacuum.expr(r"\Gamma^{a}_{bc}")
>>> gamma["r", "t", "t"] == gamma[1, 0, 0]
True
>>> gamma["θ", "φ", "φ"]
-sin(theta)*cos(theta)
>>> gamma["r", "t", :]
Γ^r_{tc} in (t, r, θ, φ): 1 of 4 components non-zero
Γ^r_{tt} = M (r − 2M)/r³
```
| Attribute or method | What it is |
|---|---|
| `T.rank` (also `ndim`), `T.shape`, `T.size`, `T.dim` | the number of indices, of components along each axis, of components, and along every axis where they agree |
| `T[...]` | a component by position or by name (`G['r', 't', 't']`, `w['MSFT']`), or with a slice the tensor of those left free |
| `T.nonzero()` | the non-zero components, keyed by the names of their coordinates or basis elements, or by position |
| `T.labels(axis)` | the names of the components along an axis |
| `T.simplify()`, `T.subs(...)`, `T.diff(x)`, `T.applyfunc(f)` | act on every component |
| `T.relabel("_{c d}")` | the same components under new labels |
| `T.T` | the transpose: the axes and their indices in the other order |
| `T.free_symbols`, `T.dtype` | the symbols of the components; NumPy's type of numerical ones |
| `T.numerical`, `T.to_numpy(**values)`, `T.to_pandas()` | whether the components are numbers; them as NumPy or pandas data, labelled by their spaces |
| `T.latex()` | the LaTeX of `display.latex`; `sympy.latex(T)` gives it too |
| `len(T)`, `iter(T)` | the first axis, as for a NumPy array |
`sympy.sympify(T)` is the array of components, `numpy.asarray(T)` an array of
them, and NumPy's functions keep a numerical tensor's indices: `numpy.exp(A)` is a
tensor. Symbolic components need values to become numbers, and say which:
```python
>>> g = vacuum.expr(r"g_{\mu\nu}")
>>> g.to_numpy(M=1, r=4, theta=0.5)[0, 0]
np.float64(-0.5)
```
Components may also be numbers in an array, as data and what is computed from
it are. Each axis then ranges over one of `tensor.spaces`. Large data is
summarised, never dumped, and notebooks show a table labelled by the spaces'
bases:
```python
>>> import numpy as np
>>> book = Workbook()
>>> book["w^a"] = np.array([0.5, 0.5])
>>> book["w"].to_numpy()
array([0.5, 0.5])
>>> book["A_{ij}"] = np.arange(250000.0).reshape(500, 500)
>>> print(display.unicode(book["A"]).splitlines()[0])
A_{ij}: 500 × 500 float64
```
## Metric
A `Metric` is the tensor \(g_{\mu\nu}\) that knows its geometry, and is shown by
its line element. Each quantity is computed when first asked for, then cached:
```python
>>> from sympy import diag, sin
>>> from relativisticpy import Metric
>>> theta, phi, a = symbols("theta phi a", positive=True)
>>> sphere = Metric(diag(a**2, a**2 * sin(theta)**2), (theta, phi))
>>> sphere
g_{μν} in (θ, φ): ds² = a² dθ² + a² sin(θ)² dφ²
>>> sphere.ricci_scalar
2/a**2
>>> sphere.christoffel.nonzero()
{('theta', 'phi', 'phi'): -sin(theta)*cos(theta), ('phi', 'theta', 'phi'): cos(theta)/sin(theta), ('phi', 'phi', 'theta'): cos(theta)/sin(theta)}
```
| Attribute or method | What it is |
|---|---|
| `inverse`, `determinant` | \(g^{\mu\nu}\) and \(\det g_{\mu\nu}\) |
| `christoffel`, `riemann`, `ricci`, `einstein`, `weyl` | the tensors, with indices `^{a}_{bc}`, `^{a}_{bcd}`, `_{ab}`, `_{ab}`, `_{abcd}` |
| `ricci_scalar`, `kretschmann` | the scalars |
| `line_element` | \(ds^2\) as a SymPy expression in the differentials `dt`, `dr`, `dtheta`, ... |
| `line_element_text(form)` | the line element as a paper writes it, in a form of `display` |
| `geodesic_equations(parameter)` | the geodesic equations, one for each coordinate |
| `Metric.from_line_element(expr, coordinates)` | a metric from \(ds^2\) |
A metric is checked on construction: it must be square, symmetric and
non-degenerate. Its LaTeX is its line element, which the language reads back.
## TensorEquation
An equation between tensors with components, such as the field equations of a
metric, is a `TensorEquation`. It says whether it holds and, if not, where; each
component equal to another by a symmetry of both sides is counted once:
```python
>>> fails = vacuum.expr(r"R_{\mu\nu} = g_{\mu\nu}")
>>> fails.holds(), fails.analysis().failing, fails.analysis().total
(False, 4, 10)
>>> fails.failures()[("t", "t")]
(0, 2*M/r - 1)
```
It is shown by its `source`, the equation as written, which names its sides:
```python
>>> from sympy import Array
>>> from relativisticpy import Indices, TensorEquation
>>> M, r = symbols("M r")
>>> TensorEquation(Array([[0, 0], [0, 0]]), Array([[2*M/r - 1, 0], [0, r/(r - 2*M)]]),
... Indices(r"_{\mu\nu}"), (t, r), source=r"R_{\mu\nu} = g_{\mu\nu}")
R_{μν} = g_{μν}: differs in 2 of 3 components
R_{tt} = 0 but g_{tt} = 2M/r − 1
R_{rr} = 0 but g_{rr} = r/(r − 2M)
```
| Attribute or method | What it is |
|---|---|
| `E.holds()`, `bool(E)` | whether every component holds, as above |
| `E.failures()` | the components where the sides are not shown equal, keyed by coordinate names, each its two sides |
| `E.components()` | the same as SymPy equations, keyed by position |
| `E.equations()` | the equations of those components, in order, to `solve` |
| `E.analysis()` | how many independent components there are, and which fail |
| `E.lhs`, `E.rhs`, `E.indices`, `E.coordinates`, `E.spaces` | the sides' components, and what they range over |
| `E.source` | the equation as written, by which its components are named when shown |
| `E.latex()`, `E.subs(...)` | LaTeX, with `\neq` where it fails; the equation with values put in |
Numerical sides hold where they agree to rounding error. An equation of large
data is summarised, with its largest difference, in milliseconds.
## Index notation
An equation between tensors that have no components, such as
`G_{\mu\nu} = 8\pi G T_{\mu\nu}`, is an `IndexEquation`, and an expression an
`IndexExpression` (see [Solving tensor equations](notation.md)). They are
`relativisticpy.abstract` values, built on `sympy.tensor.tensor`:
| Attribute or method | What it is |
|---|---|
| `E.lhs`, `E.rhs`, `X.value` | the sides of an equation, the value of an expression: SymPy tensor expressions |
| `E.holds()`, `bool(E)` | whether an equation is an identity |
| `X == 0`, `X == F` | whether an expression vanishes, or equals a scalar or another expression |
| `X.is_zero`, `X.holds()` | whether an expression vanishes; as for any number, `bool(X)` is whether it does not |
| `E == F` | whether two equations say the same |
| `E.latex()`, `str(E)` | LaTeX; `repr(E)` and `E.display(form)` the forms of `display` |
| `E.algebra` (also `E.space`) | the `Algebra` they belong to |
```python
>>> efe = Workbook().expr(r"G_{\mu\nu} = 8\pi G T_{\mu\nu}")
>>> efe
IndexEquation(G_{μν} = 8π G T_{μν})
>>> efe.holds()
False
>>> print(efe.rhs)
8*pi*G*T(-mu, -nu)
>>> Workbook().expr(r"simplify(R_{\rho\sigma\mu\nu} + R_{\rho\mu\nu\sigma} + R_{\rho\nu\sigma\mu})") == 0
True
```
`relativisticpy.abstract` also offers the algebra on its own: `canonical`,
`solve`, `trace` and `substitute`. Each works in an `Algebra`, the tensors of a
computation in a given number of dimensions: their indices, the metric, the
Kronecker delta, and a head for every tensor by name and rank.
```python
>>> from relativisticpy.abstract import Algebra, canonical, trace
>>> algebra = Algebra(dim=3)
>>> a, b = algebra.index("a", upper=True), algebra.index("b")
>>> canonical(algebra.delta(a, -a), algebra)
3
>>> trace(algebra.head("R", 2, "ricci")(a, b), algebra)
R
>>> algebra
Algebra(dim=3, metric g, Ricci scalar R, 1 tensor: R)
```
## Space
A `Space` is what an index ranges over: its `name`, its dimension `dim`, the
names of its `basis` if it has them, its `field` (`"real"` or `"complex"`),
whether it is `spacetime`, and whether it was `inferred` from the shape of data
rather than declared. `position(name)` is the number of a basis element:
```python
>>> from relativisticpy import Space
>>> assets = Space("assets", 3, basis=("AAPL", "MSFT", "NVDA"))
>>> assets.position("MSFT"), assets.describe()
(1, 'space assets: ℝ³, basis (AAPL, MSFT, NVDA)')
```
## Checking papers
`wb.check(document)` gives a `Report` (from `relativisticpy.checking`, and
exported by `relativisticpy`) with the document's `name`, the number of its
display `equations`, and its `findings`, in the order of the document:
| Attribute or method | What it is |
|---|---|
| `report.findings` | one `Finding` for each statement, and for each link of a chain |
| `report.count(verdict)` | how many findings met a `Verdict` |
| `report.summary()`, `report.describe()` | how many statements met each verdict; and the whole report, as text |
| `report.ok`, `report.failed(verdicts)` | whether the check passes `--strict`, or fails on the verdicts given |
| `report.to_dict()` | the whole report as data, for JSON |
| `finding.verdict`, `finding.span`, `finding.detail` | what became of a statement, where it was written, and why |
| `finding.line`, `finding.location`, `finding.describe()` | its line, its place as `paper.tex:12:5`, and the finding on one line with its detail beneath |
A `Verdict` is one of `HOLDS`, `DIFFERS`, `RELATES`, `ILL_FORMED`, `DEFINES`,
`COMPUTES`, `NOT_COMPUTED`, `NOT_UNDERSTOOD` and `NOT_PARSED`; its `value` is its
name in words, its `mark` the sign the report shows (✓ ✗ ↔ ✗ = → ~ ? !) and its
`meaning` what it means. [Checking papers](checking.md#verdicts) explains each:
```python
>>> from relativisticpy import Document, Verdict
>>> report = Workbook().check(Document(r"\begin{equation} ds^2 = -dt^2 + a(t)^2 dx^2 \end{equation}"))
>>> [(finding.line, finding.verdict.value) for finding in report.findings]
[(1, 'defines')]
>>> Verdict.DIFFERS.mark
'✗'
```
## Geodesics
`relativisticpy.numeric.geodesic` returns a `Geodesic`, shown by its span and
the range of each coordinate, with `tau`, the coordinates `x` and velocities
`u` (one row per coordinate), each coordinate by name (`orbit["r"]`,
`orbit["θ"]`), `stopped`, and SciPy's `solution`. See [Numerics](numerics.md).
`metric.geodesic_equations()` gives a list of SymPy equations, shown one for
each coordinate:
```python
>>> from relativisticpy import spacetimes
>>> spacetimes.minkowski().geodesic_equations()
t: t''(τ) = 0
x: x''(τ) = 0
y: y''(τ) = 0
z: z''(τ) = 0
```
## Spacetimes
`relativisticpy.spacetimes` has `minkowski`, `schwarzschild`,
`reissner_nordstrom`, `kerr`, `kerr_newman`, `flrw`, `de_sitter` and
`anti_de_sitter`, each returning a `Metric`. Parameters are names, numbers or
SymPy expressions, and `G` and `c` default to one:
```python
>>> spacetimes.schwarzschild("M", G="G", c="c").kretschmann
48*G**2*M**2/(c**4*r**6)
```
## Errors
Every error a user can cause derives from `RelativisticPyError`, and carries its
`message`, the `span` of source text responsible (with its `line`, `column` and
`source.name`), a `hint` where there is a fix and `notes` where there is more to say.
`error.render()` gives the whole diagnostic, as the command line prints it, and
`error.to_dict()` the same as data:
| Error | What it means |
|---|---|
| `ParseError` | the text is not valid RelativisticPy |
| `CompileError` | a statement makes no sense: an unknown tensor, a metric without coordinates |
| `IndexNotationError` | a `CompileError` breaking the rules of index notation |
| `NotComputedError` | a `CompileError` for what is read but not computed, such as `\propto` or a condition |
| `EvaluationError` | a computation failed, such as inverting a degenerate metric |
| `MetricError` | a metric that cannot be one; also a `ValueError` |
| `DataError` | data from Python that cannot be bound as written; also a `ValueError` |
| `UnknownNameError` | `wb[name]` for a name nothing defines; also a `KeyError` |
| `UsageError` | a call from Python given what it cannot take; also a `TypeError` and a `ValueError` |
| `FileError` | a file that does not exist, or is not UTF-8; also an `OSError` |
| `UndecidedError` | `bool()` of an equation whose truth is not decided; also a `TypeError` |
| `InternalError` | a failure of RelativisticPy's own, never of the input, which invites a report |
```python
>>> from relativisticpy import RelativisticPyError
>>> try:
... Workbook().expr(r"\frac{1}{2")
... except RelativisticPyError as error:
... print(error.to_dict()["type"], error.to_dict()["line"])
ParseError 1
```
Some calls from Python raise Python's own errors for Python's mistakes: a
`KeyError` for a component name that is not a coordinate, and a `TypeError` for
components given after their indices.
## LaTeX output
`relativisticpy.latex(value)` is `display.latex`: it typesets any result, and
tensors, metrics, equations and geodesics also display themselves, typeset, in Jupyter
and marimo. Their hooks give `display.jupyter_latex(value)` and, for numerical data,
the table of `display.jupyter_html(value)` to Jupyter, and `display.marimo(value)` to
marimo.
```python
>>> from relativisticpy import latex
>>> latex(wb.expr(r"\frac{x^2}{2}"))
'\\frac{x^{2}}{2}'
>>> latex(vacuum.expr(r"R_{\mu\nu} = 0")).endswith(r"\tag*{holds in all 10 components}")
True
```
**Next:** [the language reference](reference.md), for what a program may say, or
[Jupyter and notebooks](jupyter.md), for how results display there.
# The command line
The `relativisticpy` command runs programs and Markdown notebooks, checks the
equations of papers, prints this documentation offline, and gives a prompt to
compute at. `python -m relativisticpy` is the same command. `relativisticpy mcp`
serves the same to AI agents, as tools: see [the MCP server](mcp.md).
```bash
relativisticpy schwarzschild.relpy # run a program, each result as it comes
relativisticpy notes.md # run the maths of a Markdown notebook
relativisticpy notes.md --render -o notes.md # typeset each block's results after it
relativisticpy -c '\int_0^1 x^2 \, dx' # run code given on the command line
printf 'x := 2\nx^3\n' | relativisticpy # run standard input
relativisticpy check paper.tex --strict # check the equations of a paper
relativisticpy help # the documentation, offline
relativisticpy help besselj # one function of the language, in full
relativisticpy # the prompt, in a terminal
```
The examples below run as they are shown, as the tests of this page:
`main(arguments)` is the command, given its arguments, and returns its exit status.
```python
>>> from relativisticpy.cli import main
>>> main(["-c", r"\int_0^1 x^2 \, dx"])
1/3
0
```
## Running a program
`relativisticpy FILE` runs a program, one statement at a time, and prints each
result as soon as it is computed. A program is a file of statements, `.relpy` by
convention; a Markdown notebook, `.md` or `.markdown`, runs its blocks of maths in
order (see below). `-c CODE` runs code given on the command line, and `-` or a pipe
runs standard input, named ``. A LaTeX document (`.tex`, or any file with
`\documentclass`) is checked rather than run, with `relativisticpy check`.
Each result is labelled with the statement it came from: where it is, as editors and
compilers write it, then the statement as written. A definition says what it
defines:
```python
>>> main(["-c", r"""g_{\mu\nu} := Schwarzschild(M)
... \Gamma^{r}_{tt}
... R_{\mu\nu} = 0
... x := 2; x^3"""])
:1:1: g_{\mu\nu} := Schwarzschild(M)
defines the metric g_{μν} and the coordinates t, r, θ, φ
:2:1: \Gamma^{r}_{tt}
M (r − 2M)/r³
:3:1: R_{\mu\nu} = 0
R_{μν} = 0: holds in all 10 components
:4:1: x := 2
defines x
:4:9: x^3
8
0
```
A program of one statement prints its result alone, as the first example does.
### Errors
Errors go to standard error, after everything printed before them. A run stops at
the first error, with every result before it already printed, and says what did not
run:
```text
$ relativisticpy plain.relpy
plain.relpy:1:1: x := 3
defines x
plain.relpy:2:1: x^2
9
plain.relpy:3:1: y := x + 1
defines y
plain.relpy:4:1: y > 2
True
EvaluationError: cannot differentiate with respect to a number
--> plain.relpy:5:1
|
5 | diff(sin(x), x)
| ^^^^^^^^^^^^^^^
hint: differentiate with respect to a symbol: a name defined as a number, as by x := 3, is that number
stopped at the first error, at plain.relpy:5:1: the statement after it did not run; --keep-going (-k) runs it
```
Statements that cannot be read are known before anything runs: after a stop, each
of them is reported too. `--keep-going` (`-k`) runs every statement that can be read,
and reports every error, in the order of the program:
```text
$ relativisticpy errors.relpy -k
errors.relpy:1:1: a := 1
defines a
CompileError: T is not a tensor
--> errors.relpy:2:1
|
2 | T_{ab} u^a
| ^^^^^^
hint: define it first, for example T_{ab} := [...]
errors.relpy:3:1: b := 2
defines b
ParseError: unknown LaTeX command \frca
--> errors.relpy:4:1
|
4 | \frca{1}{2}
| ^^^^^
hint: did you mean \frac?
errors.relpy:5:1: a + b
3
2 of 5 statements failed: errors.relpy:2:1, errors.relpy:4:1
```
Either way the exit status is 1 if a statement failed. A failure of RelativisticPy's
own is an `internal error`, which says so and invites a report; it never stops a
`--keep-going` run, nor the prompt. `RELATIVISTICPY_DEBUG=1` adds its Python
traceback.
Ctrl-C stops a run and says where: `interrupted after 3.1 s computing
kerr.relpy:4:1, R^{a}_{bcd}; the results above are complete`, with exit status 130.
SIGTERM, as a harness stops a command that takes too long, does the same with status
143, and stops the worker processes of `-j` at once.
### Forms of output
`--format` chooses how results are printed, as
[`relativisticpy.display`](python.md) shows them:
| Form | What it is |
|---|---|
| `unicode` | mathematics for a terminal, `48M²/r⁶`: the default |
| `text` | plain ASCII in the language's own syntax, which reads back as the same value: `48*M^2/r^6`; the default where the console cannot show Unicode |
| `latex` | LaTeX, `\frac{48 M^{2}}{r^{6}}`, labelled by LaTeX comments; `--latex` is short for it |
| `json` | JSON Lines: one object per statement |
```python
>>> main(["-c", r"y := 2; \frac{1}{y}", "--latex"])
% :1:1: y := 2
% defines y
% :1:9: \frac{1}{y}
\frac{1}{2}
0
>>> main(["-c", r"\theta^2", "--format", "text"])
\theta^2
0
```
With `--format json`, each statement is a line of JSON, written as soon as it is
computed. Its keys:
| Key | What it holds |
|---|---|
| `file`, `line`, `column`, `end_line`, `end_column` | where the statement is, from 1 |
| `statement` | the statement as written |
| `values` | each value it showed, as `relativisticpy.display.data` describes it: its `kind`, `text`, `unicode` and `latex` forms, and its structure; and whether it is `complete`, the `reasons` it is not, and whether it is `approximate` (below) |
| `defines` | what it defined: each with its `name`, `kind` and how it is `written` |
| `notes` | how it was read, where that could surprise, and what its computation did, as dropping the solutions an assumption rules out |
| `assuming` | what its values are given under that books assume and the program did not say, as `a > 0` |
| `error` | `null`, or the error as `RelativisticPyError.to_dict()` gives it: its `type`, `message`, place, `notes` and `hint` |
```python
>>> main(["-c", "x := 2; x^3", "--format", "json"])
{"file": "", "line": 1, "column": 1, "end_line": 1, "end_column": 7, "statement": "x := 2", "values": [], "defines": [{"name": "x", "kind": "value", "written": "x"}], "notes": [], "assuming": [], "error": null}
{"file": "", "line": 1, "column": 9, ..., "values": [{"kind": "number", "digits": 1, "value": 8, "text": "8", "unicode": "8", "latex": "8", "complete": true, "reasons": [], "approximate": false}], ...}
0
```
A value is `complete` unless the program kept part of it as written, as it could not
carry it out; `reasons` then says why, each in a word or two:
| Reason | What is kept as written |
|---|---|
| `integral`, `sum`, `product`, `limit` | one SymPy found no closed form of |
| `derivative` | a derivative SymPy could not take |
| `unknown function` | a call of a function RelativisticPy does not know, as `foo(x)` |
| `time budget` | besides one of the above: SymPy was stopped looking for its closed form, at the end of the time it is given |
The statement's `notes` say the same in words. `approximate` is `true` for a value with a
floating-point number in it, from a decimal written, as `0.1`, or a numerical method: an
approximation, not exact.
```python
>>> main(["-c", r"\int_0^1 \sin(\sin x) \, dx", "--format", "json"])
{..., "values": [{"kind": "expression", ..., "complete": false, "reasons": ["integral"], "approximate": false}], ..., "notes": ["an integral is left as written: SymPy could not compute it"], ...}
0
```
Errors are in the JSON, not repeated on standard error; what a person needs besides,
such as `stopped at the first error`, is on standard error.
### Standard input
Standard input that is not a terminal is read to its end as one program named
``, with no banner and no prompts; errors go to standard error, and a failure
exits with status 1. If nothing comes for two seconds, as when a harness leaves
standard input open, the command says on standard error that it is reading it, to
its end. `-i` starts the prompt instead, or after running a FILE or CODE, with what
it defined.
## Markdown notebooks
A Markdown notebook runs its blocks of maths, in order, as one program: `$$...$$`,
`\[...\]`, display environments such as `\begin{equation}`, and fenced blocks of
` ```math `; a fenced block of ` ```relativisticpy ` is a program, run as written.
Code, and maths in code, is not run. Errors point at the notebook's own lines.
`--render` prints the notebook with each block's results typeset after it, in LaTeX,
between two comments that a reader of the rendered page does not see:
```markdown
$$
a := 2 \\
a^2
$$
$$
4
$$
```
- **Every block is rendered.** A statement that fails is typeset as its error, in a
block of code where the result would be, and the blocks after it still run. The
errors are reported on standard error too, and the exit status is 1.
- **Rendering again replaces the results**, rather than running them: rendering a
rendered notebook gives the same document. A run, or a check, of a rendered
notebook skips them.
- **`-o FILE`** writes the document to FILE, which may be the notebook itself: the
file is written whole or not at all.
`--ir` prints the IR, the computation a program compiles to, without computing it.
The blocks of a notebook compile in order, so that each sees what those before it
define, and the IR of each is headed by where it is: `# notes.md:12`.
## The prompt
`relativisticpy` with no file, in a terminal, starts the prompt:
```text
RelativisticPy 0.1.0: type help for help, who for what is defined, exit or Ctrl-D to leave.
rp> g_{\mu\nu} := Schwarzschild(M)
defines the metric g_{μν} and the coordinates t, r, θ, φ
rp> R_{abcd} R^{abcd}
48M²/r⁶
```
Definitions persist from one input to the next, and no error ends the session.
| Key or command | What it does |
|---|---|
| Enter | runs the input, unless a bracket, `\left`, `\begin{...}`, `$$` or `\[` is still open, or the line ends with an operator, `=`, `:=` or a single `\`; then the input goes on, at a `...` prompt |
| pasting | lines pasted at once are one input, so a line element over two lines is one statement |
| Ctrl-C | clears the input, or stops a computation; every definition is kept |
| Ctrl-D | leaves, at an empty prompt; on an unfinished input, runs what there is |
| Tab | completes built-in functions, spacetimes, constants, LaTeX commands, and what you defined |
| Up, Down | the inputs before, kept from one session to the next |
| `help`, `help TOPIC` | what the language looks like and the topics; one topic, or one function in full |
| `who` | what is defined, by kind: coordinates, metric, functions, tensors, values, spaces |
| `reset` | forgets every definition, once you say yes |
| `exit`, `quit` | leaves |
Each input is named by its number in errors, `--> :1:5`. Input that looks
like Python, as `wb = Workbook()` or a line pasted from a Python session, gets a hint
rather than a result: the prompt reads the language itself. The history is kept in
`$XDG_STATE_HOME/relativisticpy/history` (by default
`~/.local/state/relativisticpy/history`), or in the file `RELATIVISTICPY_HISTORY`
names; set it to nothing to keep none. Line editing, history and completion use
Python's `readline` where it is installed, and the prompt works without it.
## Checking papers
`relativisticpy check FILE...` runs the equations of LaTeX documents and Markdown
notebooks in order, as a reader would, and says what became of each, as
[Checking papers](checking.md) explains. It takes:
- **files:** a `.md` or `.markdown` file is a notebook, and anything else is LaTeX;
- **patterns,** such as `'chapters/*.tex'`, where the shell does not expand them;
- **folders,** searched for the LaTeX documents that no other includes (a chapter
that `main.tex` reads with `\input` is checked through it) and the notebooks with
maths in them;
- **`-`,** standard input, read as LaTeX.
```text
$ relativisticpy check paper.tex --strict
paper.tex: 3 equations, 3 statements, checked in 0.1 s
✓ holds 1 proven equal
✗ differs 1 of known quantities, whose sides are not equal: a mistake, or a condition
= defines 1 definitions
paper.tex:6:18: ✗ differs \Gamma^\theta_{r\theta} = r
the left side minus the right is 1/r − r
Not listed: 1 holds, 1 defines. --all lists every statement.
failed by --strict: 1 differs (paper.tex:6:18)
```
What fails `--strict` is listed; the rest is counted, and `--all` lists it. Nothing
is cut short when the output is not a terminal; in a terminal, long lines are
wrapped to its width. Several documents are reported one after another, and a last
line totals them. A file that cannot be read is reported, the others are checked,
and the exit status is 2.
| Option | What it does |
|---|---|
| `--all` | lists every statement, with its reason, not only those that fail |
| `--lines RANGE` | checks only these lines of one document: `120:340`, `13`, `10:` or `:10`. What comes before them still runs, for its definitions |
| `--time-limit SECONDS` | the time each statement may take, or `inf` (default 30) |
| `--strict` | exits with status 1 if an equation differs or is ill-formed, a statement is not parsed or is over its time limit, or a document has no equations |
| `--fail-on VERDICTS` | exits with status 1 on these verdicts, separated by commas: `differs`, `relates`, `ill-formed`, `defines`, `computes`, `not-computed`, `not-understood`, `not-parsed`, and the conditions `time-limit` and `empty`. With `--strict`, either fails it |
| `--format unicode` | the report as above: the default |
| `--format text` | the same, with marks in ASCII: `+ holds`, `x differs`, `<> relates`, `-> computes` |
| `--format json` | each report as one line of JSON: `Report.to_dict()`, with the `policy` it was checked against and whether it `failed` it |
| `--format github` | the summary, then an annotation of GitHub Actions for each finding listed: an error for what differs, is ill-formed or is not parsed, a warning for what is not computed or not understood |
| `-j N` | processes for component-wise work, as for a run |
```text
$ relativisticpy check paper.tex --format github
paper.tex: 3 equations, 3 statements, checked in 0.1 s
✓ holds 1 proven equal
✗ differs 1 of known quantities, whose sides are not equal: a mistake, or a condition
= defines 1 definitions
::error file=paper.tex,line=6,col=18,endLine=6,endColumn=45,title=RelativisticPy%3A differs::\Gamma^\theta_{r\theta} = r%0Athe left side minus the right is 1/r − r
```
On a terminal, a check that takes more than a second shows where it is on standard
error: `⠼ checking paper.tex, line 9102 of 12011 · 1 min 12 s`.
## Reading the documentation
`relativisticpy help` prints what the language looks like and the topics of this
documentation; `relativisticpy help TOPIC` prints one, as Markdown, offline. A topic
may be asked for by another name, as `check` for `checking`, and a topic that does
not exist is told what it may have meant. At the prompt, `help` and `help TOPIC` do
the same. `relativisticpy --help` and `relativisticpy check --help` list every
option, with examples.
[The language reference](reference.md) lists every function of the language by name,
a line for each family. `relativisticpy help NAME` describes one in full, generated from
what its integration declares: the forms it is written in, its arguments, what computes
it, with SymPy or a library on data and what installs that library, its examples with
their answers and where each answer comes from, and its notes. Another of its names
does the same, as `arcsin` for `asin`, and so does its name in another case, where only
one function has it. A page comes first: `relativisticpy help latex` is the page on
LaTeX, and `relativisticpy help 'latex()'`, with brackets, the function.
```text
$ relativisticpy help besselj
# besselj
The Bessel function of the first kind, of order `\nu`.
- **Written:** `besselj(nu, x)`, `J_{\nu}(x)`
- **Arguments:** 2, `nu` and `x`
- **Takes:** numbers and expressions
- **Computed by:** SymPy, exactly; on data, SciPy (`pip install "relativisticpy[numeric]"`)
- **Kind:** a function, declared by the integration `relativisticpy.integrations.bessel`: Bessel and Airy functions
## Examples
- `J_0(1)` gives `0.7651976865579666` (scipy.special.jv(0, 1.0))
- `J_{1/2}(\pi/2)` gives `2/π` (DLMF 10.16.1)
## Notes
- Given a tensor, it applies to each component, and given data, to each number.
```
A name that is neither a topic nor a function is told what it may have meant, among
both: `relativisticpy help besselk2` suggests `besselk`.
## Options of a run
| Option | What it does |
|---|---|
| `FILE` | a program, a Markdown notebook, or `-` for standard input |
| `-c CODE` | runs CODE: statements separated by line breaks or `;`. Given more than once, the pieces are lines of one program. What follows `-c` is code, even `-x` |
| `-k`, `--keep-going` | runs every statement, reporting every error, rather than stopping at the first |
| `-i`, `--interactive` | starts the prompt after FILE or CODE, or with standard input that is not a terminal |
| `--format FORM` | `unicode`, `text`, `latex` or `json` |
| `--latex` | `--format latex` |
| `--render` | prints a Markdown notebook with its results typeset |
| `-o FILE` | with `--render`, writes the document to FILE |
| `--ir` | prints the IR instead of computing |
| `-j N`, `--workers N` | processes that share component-wise work, such as simplifying the components of a tensor: a number, or `0` or `auto` for one per CPU (default 1) |
| `--color WHEN` | `auto` (the default), `always` or `never` |
| `-V`, `--version` | the versions of RelativisticPy, Python, SymPy and NumPy, for a report |
| `-h`, `--help` | every option, with examples |
Options that do not go together are refused, never ignored: a FILE and `-c`,
`--render` and `--ir`, `--render` of something that is not a notebook, `-o` without
`--render`, `--format json` at the prompt, `--keep-going` with nothing to run.
Options of a command may come before it: `relativisticpy -j 4 check paper.tex`. A
file named `check` or `help` is written `./check`.
## Exit status
| Status | Meaning |
|---|---|
| 0 | done, and everything succeeded; a check that passed its policy, or had none |
| 1 | a statement failed, or a check failed its policy (`--strict`, `--fail-on`) |
| 2 | the command line was wrong: an unknown option, options that do not go together, or a file that cannot be read (missing, a folder, not UTF-8, or not a program) |
| 130 | interrupted with Ctrl-C |
| 143 | stopped with SIGTERM |
A false equation in a run is a result, not a failure: to fail on it, check it.
## Environment
| Variable | What it does |
|---|---|
| `NO_COLOR` | set to anything, no colour; nor with `TERM=dumb` |
| `FORCE_COLOR` | set to anything but `0`, colour even where the output is not a terminal |
| `RELATIVISTICPY_DEBUG` | `1` shows the Python traceback of an internal error |
| `RELATIVISTICPY_HISTORY` | the file the prompt keeps its history in; empty for none |
| `XDG_STATE_HOME` | where the history is kept otherwise, as `relativisticpy/history` |
| `PYTHONHASHSEED` | the seed of Python's hashes, which order SymPy's sets of symbols. Where it is not set, the command starts itself again with `0` before it imports anything else, so that a program gives the same answer every time, and the processes it starts for its work, of `-j` and of `relativisticpy mcp`, inherit it; `RELATIVISTICPY_RESTARTED` marks the command started again. A value set, as `random`, is kept. On Windows, which cannot replace a process, only the processes it starts get `0`: set it yourself to reproduce a run there |
# The MCP server
> **For:** anyone who gives an AI agent mathematics to do, and agents themselves. **You
> will learn:** how to serve RelativisticPy to any MCP client, what each tool takes and
> gives, how to tell an answer from a refusal or a value kept as written, and the bounds
> the server keeps.
> **Before this:** [Getting started](getting-started.md).
Language models write physics and mathematics fluently, and get long algebra wrong.
RelativisticPy reads what they write, in LaTeX, plain text or Unicode, computes it
exactly, and says where a claim does not hold. `relativisticpy mcp` serves it over the
[Model Context Protocol](https://modelcontextprotocol.io), on standard input and output,
as tools an agent calls:
| Tool | What it does |
|---|---|
| [`compute`](#compute) | runs a program, and gives each statement's values, what it defines, and its error, if it failed; a `session` keeps definitions from one call to the next |
| [`verify`](#verify) | checks one claimed equality or step of a derivation, `lhs = rhs` or `a = b = c`, after its context: holds, differs, relates, not decided or error, with the difference of the sides in LaTeX |
| [`check`](#check) | checks every display equation of a LaTeX document or Markdown notebook |
| [`help`](#help) | the documentation, offline; `reference` is the whole language on one page, and the name of a function, as `besselj`, that function in full |
| [`list_sessions`, `reset_session`](#sessions) | the named sessions, and forgetting one |
Every page of this documentation is also a [resource](#resources), and two
[prompts](#prompts) start a verification and the check of a paper.
## Install
The server needs the `mcp` extra, which adds the official MCP SDK:
```bash
pip install "relativisticpy[mcp] @ git+https://github.com/cottrellashley/relativisticpy"
```
`relativisticpy mcp` then waits for a client on standard input; a client starts it
itself, as below. `python -m relativisticpy mcp` is the same command.
## Connect a client
A client needs one thing: the command that starts the server. Give a client the absolute
path of `relativisticpy` (`which relativisticpy`) if it does not find it, since clients
start servers with an environment of their own.
### Claude Code
```bash
claude mcp add relativisticpy -- relativisticpy mcp
```
To let it check the papers of a folder by their paths, allow the folder:
```bash
claude mcp add relativisticpy -- relativisticpy mcp --allow-files /path/to/papers
```
`/mcp`, in a session, shows the server and its tools. Without installing anything first,
`uvx` runs it from GitHub:
```bash
claude mcp add relativisticpy -- uvx --from "relativisticpy[mcp] @ git+https://github.com/cottrellashley/relativisticpy" relativisticpy mcp
```
### Claude Desktop
Add the server to `claude_desktop_config.json`, which is in
`~/Library/Application Support/Claude` on macOS and in `%APPDATA%\Claude` on Windows,
and restart Claude Desktop:
```json
{
"mcpServers": {
"relativisticpy": {
"command": "relativisticpy",
"args": ["mcp", "--allow-files", "/Users/you/papers"]
}
}
}
```
Or, run from GitHub by `uvx`:
```json
{
"mcpServers": {
"relativisticpy": {
"command": "uvx",
"args": [
"--from",
"relativisticpy[mcp] @ git+https://github.com/cottrellashley/relativisticpy",
"relativisticpy",
"mcp"
]
}
}
}
```
### Any MCP client
Every client that starts servers over standard input and output takes the same command
and arguments. Cursor reads `.cursor/mcp.json`, in the same form as Claude Desktop;
VS Code reads `.vscode/mcp.json`:
```json
{
"servers": {
"relativisticpy": {
"type": "stdio",
"command": "relativisticpy",
"args": ["mcp", "--time-limit", "120"]
}
}
}
```
### From Python
The SDK's own client connects to the server in memory, with no process of its own, as the
tests of this page do. `call` here calls one tool of a new server, and gives its
structured result:
```python
>>> import anyio
>>> from mcp import Client
>>> from relativisticpy.mcp import create_server
>>> def call(tool, **arguments):
... async def run():
... async with Client(create_server()) as client:
... result = await client.call_tool(tool, arguments)
... return result.structured_content
... return anyio.run(run)
```
`Client(StdioServerParameters(command="relativisticpy", args=["mcp"]))` starts it as a
command instead, as a client does.
## The tools
Each tool says, in its description, what it takes and gives, and the limits the server
was started with; the server's instructions, which a client may give the model, sum up
the language.
Every answer is right, or says that it is not one: a wrong answer given without a word
is a bug, and the [roadmap](roadmap.md) lists those known. What an agent reads, to know
which:
| Field | Where | What it says |
|---|---|---|
| `ok` | `compute` | every statement ran, and none failed |
| `complete` | `compute`, and each value | `ok`, and every value an answer; a value with `complete` false is kept in part as written, and is no answer |
| `reasons` | each value | why a value is not complete: `integral`, `sum`, `product`, `limit`, `derivative`, `unknown function` or `time budget` |
| `approximate` | each value | the value holds floating-point numbers: an approximation, not exact |
| `error` | each statement of `compute`, each link of `verify`, each finding of `check` | a refusal: its `type`, `message`, place, `notes`, and a `hint` of what to write instead |
| `verdict` | `verify` | `holds`, `differs`, `relates`, `not decided` or `error` |
### compute
Runs a program: mathematics as written, in LaTeX, plain text or Unicode, with statements
on lines of their own or separated by `;`.
| Argument | What it is |
|---|---|
| `source` | the program |
| `session` | a session to run in, made on first use, whose definitions persist from one call to the next; without it, the program runs in a new, empty workbook |
| `time_limit` | seconds the call may run, up to the server's limit |
It gives one entry for each statement, in order, exactly as a line of
`relativisticpy --format json` gives it (see [the command line](cli.md#forms-of-output)):
where it is, the statement, its `values`, each as `relativisticpy.display.data`
describes it, with its `text`, `unicode` and `latex` forms, what it `defines`, `notes` on
how it was read, what its values are given `assuming`, as `a > 0`, where books assume it
and the program did not say, and its `error`. `ok` says whether every statement ran and
none failed, and `complete` whether besides every value is a complete answer.
```python
>>> result = call("compute", source=r"g_{\mu\nu} := Schwarzschild(M); R_{abcd} R^{abcd}")
>>> [entry["statement"] for entry in result["statements"]]
['g_{\\mu\\nu} := Schwarzschild(M)', 'R_{abcd} R^{abcd}']
>>> [d["name"] for d in result["statements"][0]["defines"]]
['t', 'r', 'theta', 'phi', 'g']
>>> kretschmann = result["statements"][1]["values"][0]
>>> kretschmann["text"], kretschmann["unicode"], kretschmann["latex"]
('48*M^2/r^6', '48M²/r⁶', '\\frac{48 M^{2}}{r^{6}}')
>>> result["ok"], result["complete"]
(True, True)
```
A statement that fails does not stop the others. Its error comes whole, as
`RelativisticPyError.to_dict()` gives it: its type, its message, where it is, the text it
is about, its notes and its hint:
```python
>>> result = call("compute", source="x := 2\n\\frac{1}{2\nx + 1")
>>> result["statements"][1]["error"]
{'type': 'ParseError', 'kind': 'ParseError', 'message': "unclosed '{' in the argument of \\frac", 'file': '', 'line': 2, 'column': 9, 'end_line': 2, 'end_column': 10, 'text': '{', 'notes': [], 'hint': "add '}' where the argument ends"}
>>> result["statements"][2]["values"][0]["text"], result["ok"]
('3', False)
```
A value says whether it is an answer. Where the program could not carry part of it out,
it keeps that part as written, with a note, and `complete` is false: `reasons` says why,
as [the command line](cli.md#forms-of-output) lists them. Such a value is not the answer:
write it another way, or ask for a number, with `evalf`, which is `approximate`:
```python
>>> result = call("compute", source=r"\int_0^1 \sin(\sin x) \, dx")
>>> value = result["statements"][0]["values"][0]
>>> value["complete"], value["reasons"], result["ok"], result["complete"]
(False, ['integral'], True, False)
>>> result = call("compute", source=r"evalf(\int_0^1 \sin(\sin x) \, dx)")
>>> value = result["statements"][0]["values"][0]
>>> value["complete"], value["approximate"], round(value["value"], 6)
(True, True, 0.430606)
```
### verify
Checks one claimed equality, or one step of a derivation, as
[a check](checking.md) judges the equations of a paper.
| Argument | What it is |
|---|---|
| `claim` | an equation, `lhs = rhs`, or a chain, `a = b = c`, each link of which is judged |
| `context` | what the claim relies on, run first: definitions, a metric, coordinates, or symbols declared as variables, as `Reals := [x]` |
| `time_limit` | seconds the call may run, up to the server's limit |
The `verdict`, on the claim and on each of its `links`:
| Verdict | Meaning |
|---|---|
| `holds` | proven equal |
| `differs` | every quantity is known, and the sides are not equal: a mistake. The `difference`, left side minus right, is given in each form, LaTeX among them |
| `relates` | the sides are not equal, but involve quantities the context does not define, so the claim may be an equation to solve rather than an identity; the difference is given. Declaring the symbols in the context, as `Reals := [x]`, has such a claim judged |
| `not decided` | not proven equal, though numbers do not show that the sides differ; or a relation such as `\approx`; or over the time limit |
| `error` | the claim could not be read or computed, or is not a claim; its `detail`, place, `notes` and `hint` say why |
Each link also has `check`, the verdict `relativisticpy check` would give it, and, where
it is an error or not decided for one, `error`, as `compute` gives a statement's error.
Statements of the context that fail are listed in `context`. A step with its sign wrong:
```python
>>> step = call(
... "verify",
... claim=r"\frac{d}{dr} \left(1 - \frac{2M}{r}\right)^{-1} = \frac{2M}{(r - 2M)^2}",
... context="Reals := [r, M]",
... )
>>> step["verdict"], step["links"][0]["difference"]["latex"]
('differs', '- \\frac{4 M}{4 M^{2} - 4 M r + r^{2}}')
>>> claim = call(
... "verify",
... claim=r"\Gamma^{r}_{\theta\theta} = -r",
... context=r"g_{\mu\nu} := Schwarzschild(M)",
... )
>>> claim["verdict"], claim["links"][0]["detail"]
('differs', 'the left side minus the right is 2M')
>>> chain = call("verify", claim="(x+1)^2 = x^2 + 2x + 1 = x^2 + 1", context="Reals := [x]")
>>> [(link["verdict"], link["statement"]) for link in chain["links"]]
[('holds', '(x+1)^2 = x^2 + 2x + 1'), ('differs', 'x^2 + 2x + 1 = x^2 + 1')]
```
### check
Checks the equations of a LaTeX document or a Markdown notebook, as
[`relativisticpy check`](checking.md) does, and gives the report as `Report.to_dict()`
gives it.
| Argument | What it is |
|---|---|
| `document` | the text of the document |
| `path` | or the path of a file, which the server may read only in the folders it was started with, by `--allow-files`; relative to its working directory or to one of those folders |
| `format` | `latex`, the default for text, or `markdown`; a path goes by its suffix |
| `name` | the name findings in text are located by, as `paper.tex` |
| `lines` | only these lines, as `120:340`, after what comes before them has run, for its definitions |
| `strict`, `fail_on` | a policy: fail on what `--strict` fails on, or on these verdicts; `failed` says whether the document fails it |
| `all` | list every statement's finding; by default `findings` lists what fails `--strict` and what ran over its time limit, and `counts` counts the rest |
| `statement_time_limit` | seconds each statement may run (default 30) |
| `time_limit` | seconds the whole check may run, up to the server's limit; a check that runs out of time reports what it checked, and says where it stopped |
```python
>>> paper = r"""
... \begin{equation} ds^2 = -dt^2 + a(t)^2 dx^2 \end{equation}
... \begin{equation} \Gamma^x_{tx} = \frac{\dot a}{a} \end{equation}
... \begin{equation} \Gamma^t_{xx} = a \end{equation}
... """
>>> report = call("check", document=paper, name="paper.tex", strict=True)
>>> report["counts"], report["failed"]
({'holds': 1, 'differs': 1, 'defines': 1}, True)
>>> [(f["line"], f["verdict"], f["difference"]["text"]) for f in report["findings"]]
[(4, 'differs', "a(t)*a'(t) - a(t)")]
```
### help
The documentation, as Markdown, offline. Without a `topic`, what the language looks like
and the topics; `reference` is [the language reference](reference.md), the whole
language on one page of about 11,000 tokens, with every function by name, which an agent
can read before it writes. A topic may be asked for by another name, as `check` for
`checking`. The name of a function, as `besselj`, gives that function in full, as
`relativisticpy help besselj` does ([Command line](cli.md#reading-the-documentation)):
the forms it is written in, its arguments, what computes it, its examples with their
answers, and its notes.
## Sessions
`compute` with a `session` runs in the workbook of that name, so that a metric defined in
one call is there in the next; each call's statements are located as ``,
`` and so on. `list_sessions` gives each session's statements, what it defines,
and the server's limits; `reset_session` forgets one, with everything it defined. A
server keeps eight sessions at most (`--max-sessions`).
## Resources
Every page of this documentation is a resource, `relativisticpy://docs/{topic}`, as
Markdown: `relativisticpy://docs/reference` is the language reference, and
`relativisticpy://docs/check` the page on checking, by another name for it. The same
template gives a function in full, as the `help` tool does: `relativisticpy://docs/besselj`.
A client can put one in front of the model before it writes.
## Prompts
| Prompt | Arguments | What it asks for |
|---|---|---|
| `verify_derivation` | `derivation`, `context` | each step verified with `verify`, its verdict reported, and a wrong step corrected |
| `check_paper` | `document`, a path or LaTeX | the document checked with `check`, and each finding that fails explained, with a fix |
## Errors
A statement the program cannot read or compute is refused, never guessed at. Its `error`
is the same in every tool: `compute` gives it for each statement that failed, and the
call goes on; `verify` for each link that is an error, or not decided for one, as over
the time limit; `check` for each finding. It says what is wrong, its `type` and
`message`; where, its `file`, `line`, `column`, `end_line`, `end_column` and the `text`
there; why, in `notes`; and, in a `hint`, what to write instead, where there is something
to write. Fix the statement as the hint says, and run it again; the
[language reference](reference.md), or `help`, says how to write the rest.
A call that cannot be done at all is a tool error, `isError` in MCP, whose text says what,
and how to go on, in a line `hint:`: a session that cannot be named so, a file the server
may not read, a topic there is no help on, or a computation that would not stop at its
time limit.
## Safety
The server is for an agent to drive on its own, so it keeps these bounds:
- **No Python.** Workbooks are given no Python scope, and the language never runs Python:
text in quotes is never evaluated, and `\texttt{os}`, which names a Python object, is
refused, saying so. No tool binds data from a client, and no tool writes a file.
- **Files only where allowed.** `check` reads a file only if the server was started with
`--allow-files`, and only in those folders, after symbolic links and `..` are followed.
The files a document reads in, by `\input`, `\include` or `\usepackage`, are held to the
same folders. Without the option, `check` takes documents as text.
- **Every call in time.** Each call runs in a worker process of its own: one for each
session, and up to four for calls without one. A call may run for 60 seconds, or the
server's `--time-limit`, and may ask for less. When the time runs out, the statement
running is stopped and reported as over the time limit, with what ran before it, and a
session keeps its definitions. A computation that does not stop when asked, as one in
a library's compiled code may not, has its worker stopped five seconds later: the call
fails, saying so, and a session computing in it is lost. A client that gives up on a
call interrupts its computation.
- **Memory.** Each worker may use 4096 MiB (`--memory-limit`), where the system enforces
it, as Linux does; a computation that needs more fails with `there is not enough memory
to compute this`, and the server goes on.
- **Results of a size.** What `compute`, `verify` or `check` gives is cut to 50,000
characters of JSON (`--max-output`): long text first, marked `…`, then lists, with
`truncated` set and a note that says what was cut. A program, claim or document of
more than 1,000,000 characters is refused.
- **Workers of their own.** A worker starts in the folder RelativisticPy is installed in,
with Python's safe path, so that no module in the server's working directory can stand
in for one RelativisticPy imports. It ends when the server does.
- **The same answer every time.** The command starts itself again with
`PYTHONHASHSEED=0` where it is not set, and its workers inherit the seed, so that a call
gives the same answer in every session (see
[Troubleshooting](troubleshooting.md#a-result-changed-from-one-run-to-the-next)).
On Windows, which has no `SIGALRM`, a statement is not stopped softly: its worker is
stopped instead, at the end of the call's time; nor is the memory limit enforced there.
## Options
| Option | What it does |
|---|---|
| `--allow-files [FOLDER]` | lets `check` read documents in FOLDER, and the files they include there; without FOLDER, the working directory. Give it again for more folders |
| `--time-limit SECONDS` | the longest any call may run (default 60); a call may ask for less |
| `--max-output CHARACTERS` | the most characters a result may have, as JSON (default 50000) |
| `--max-sessions N` | the most named sessions at once (default 8) |
| `--memory-limit MIB` | the memory each worker may use, where the system enforces it; 0 for no limit (default 4096) |
`relativisticpy mcp --help` lists them, with examples.
**Next:** [the language reference](reference.md), for what an agent may write, or
[checking papers](checking.md), for what each verdict means.
# Glossary
> **For:** everyone, whenever a word in these pages needs pinning down. **You will
> learn:** what each term means here; the pages use each in this one sense.
```python
>>> from relativisticpy import Workbook, holds
>>> wb = Workbook()
>>> wb.exe(r"""
... ds^2 = a^2 (d\theta^2 + \sin^2\theta\, d\phi^2)
... R
... x^2 + y^2 = 1
... """)
[2/a**2, Eq(x**2 + y**2, 1)]
>>> holds(wb.expr("R = 0")), holds(wb.expr(r"R = \frac{2}{a^2}"))
(False, True)
```
The line element is a *definition*, `R` an *expression*, `x^2 + y^2 = 1` an *equation*
to solve, and `R = 0` a *claim*, which does not hold on a sphere.
## Programs
**Workbook.** A session in which programs run, from Python: `Workbook()`. Definitions
persist from one call to the next, as in the cells of a notebook.
**Program.** Text in the language: a sequence of statements, given as a string, read
from a file (by convention ending in `.relpy`), or taken from the displays of a
Markdown notebook or a LaTeX document.
**Statement.** One step of a program, on a line of its own or separated by `;`: a
definition, a declaration, an expression or an equation.
**Expression.** A statement that computes a value, such as `R_{abcd} R^{abcd}`. Its value
is a *result*.
**Result.** What an expression gives: a SymPy value, a `Tensor`, a `TensorEquation`, an
`IndexEquation` and so on. [The Python API](python.md#results) lists them.
**Step.** What one statement gave, or the error it raised, when `wb.each` runs a program
one statement at a time.
**Raw string.** A Python string with `r` before its quote, `r"\frac{1}{2}"`, in which a
backslash stays a backslash. LaTeX written in Python belongs in raw strings.
## Meanings of `=`
**Definition.** A statement that gives a name a meaning: `x := 2`, `f(x) := x^2`,
`T_{\mu\nu} := \ldots`, or a line element. `:=` always defines; `=` defines only what has
no meaning yet.
**Declaration.** A statement that says what names are, rather than what they equal:
`Coordinates := [t, r, \theta, \phi]`, `Positive := [a]`, `a, b \in \mathcal{A}`,
`MetricSymbol := G`.
**Assumption.** A relation on names nothing defines, standing alone, as `a > 0`,
`0 < x < 1` or `x \in \mathbb{R}`: it says what the names are from then on, and shows
nothing.
**Equation.** Two sides joined by `=`. What it does depends on its left side: it is a
definition, a claim, a condition, or an equation to solve, as `x^2 + y^2 = 1` is.
**Claim.** An equation whose sides both have a meaning already, such as `R = 0` with a
metric in force. A claim is true or false, and RelativisticPy checks it: `holds(claim)`.
**Identity.** A claim that holds whatever its symbols stand for:
`\sin^2 x + \cos^2 x = 1`, or, between tensors without components,
`G_{\mu\nu} = R_{\mu\nu} - \frac{1}{2} R g_{\mu\nu}`.
**Condition.** An equation that fixes a coordinate, such as `t = 0` or
`\theta = \pi/2`. It is read, but not computed.
**Relation.** A statement joined by a relation other than `=` or an inequality, such as
`\approx`, `\propto` or `\sim`. It is read, but not computed. (The verdict *relates* of a
check is something else: an equation between quantities nothing defines.)
## Names
**Symbol.** A name nothing defines, which stands for itself: in `x^2 + 1`, x.
**Unknown function.** A function nothing defines, written with its arguments, as `A(r)`
in a metric. It stays unknown, and can be solved for with `dsolve`.
**Built-in.** What the language names without your defining it: the built-in tensors
(the metric, the Christoffel symbols, the Riemann, Ricci, Einstein and Weyl tensors, the
Kronecker delta), the built-in scalars (`R`, `Kretschmann`), the functions, which are
called *builtins* (`sin`, `simplify`, `Schwarzschild`), and the constants (`pi`, `e`,
`i`). [The language reference](reference.md) lists them all.
## Tensors
**Index notation.** Writing tensors with indices, up with `^` and down with `_`. An index
that appears once up and once down in a term is *summed*, by Einstein's convention; one
that appears once is *free*, and every term has the same free indices.
**Components.** The values of a tensor for each choice of its indices, such as `g_{tt}`.
With a metric in force, the built-in tensors and those defined from them have
components, and an equation between them stands for one equation for each component: a
`TensorEquation`.
**Without components.** A tensor nothing gives components to, such as `T_{\mu\nu}` in
Einstein's equation, is kept as notation, and an equation between such tensors is an
`IndexEquation`, which `solve`, `trace`, `simplify` and `subs` rearrange as on paper.
[Solving tensor equations](notation.md) is about these.
**Metric in force.** The metric defined last, by `g_{\mu\nu} := \ldots` or a line
element. The built-in tensors are those of its geometry.
**Line element.** The metric written as `ds^2 = \ldots`, in the differentials of the
coordinates.
**Coordinates.** The names the components of the metric depend on: declared with
`Coordinates := [\ldots]`, or taken from a line element's differentials, in the order
they first appear.
**Space.** What an index ranges over: the coordinates of spacetime, the assets of a
portfolio, the days of a series, the states of a qubit. A space is declared, as
`\mathcal{H} := \mathbb{C}^{2}`, or comes with data.
**Data.** Numbers bound from Python to a tensor, as in `wb["R_{ta}"] = returns`.
## Documents
**Notebook.** A Markdown file whose displays are a program: `relativisticpy notes.md`
runs it, and `--render` typesets its results under each display. A Jupyter notebook is
something else, from which RelativisticPy is used as a library; see
[Jupyter and notebooks](jupyter.md).
**Display.** An equation set apart from the text: an environment such as `equation` or
`align`, `$$ ... $$` or `\[ ... \]`. A display may hold several statements. The summary
of a check counts displays as its equations.
**Check.** Running the displays of a document in order and giving each statement a
verdict: `relativisticpy check paper.tex`, or `wb.check(document)`.
**Verdict.** What became of a statement in a check: *holds*, *differs*, *relates*,
*ill-formed*, *defines*, *computes*, *not computed*, *not understood* or *not parsed*.
See [Checking papers](checking.md#verdicts).
**Finding.** One statement's verdict, with where the statement is and why. A **report**
is the findings of a check, with their summary.
**Next:** [Troubleshooting](troubleshooting.md), for the mistakes these words help to
explain, or [the language reference](reference.md).
# Troubleshooting
> **For:** anyone whose result is not what they expected. **You will learn:** the
> mistakes that are easiest to make, why each happens, and what to write instead.
```python
>>> from relativisticpy import Workbook, holds
>>> wb = Workbook()
```
## LaTeX from Python fails, or names a tab or a form feed
In an ordinary Python string, `\a`, `\b`, `\f`, `\n`, `\r`, `\t` and `\v` are control
characters, and Python turns them into those before RelativisticPy sees the text:
`"\theta"` arrives as a tab and `heta`. RelativisticPy refuses such text and says so:
```python
>>> wb.expr("\theta + 1")
Traceback (most recent call last):
...
relativisticpy.errors.ParseError: Python turned \t in \theta into a tab
...
```
Write LaTeX in a raw string, with `r` before its quote: `r"\theta + 1"`. A triple-quoted
string takes several lines: `r"""..."""`.
## `=` checked a claim where you meant to define
`:=` always defines, or redefines. `=` defines only what has no meaning yet: a new name,
a new function, a new tensor, a line element. Otherwise it is a claim, which is checked.
So with a metric in force, `R = 0` asks whether the Ricci scalar vanishes; it does not
make `R` zero:
```python
>>> sphere = Workbook()
>>> sphere.expr(r"ds^2 = a^2 (d\theta^2 + \sin^2\theta\, d\phi^2)")
>>> holds(sphere.expr("R = 0"))
False
>>> sphere.expr("R")
2/a**2
```
To give a built-in's name a meaning of your own, write `R := 0`; to give a name that has
a value a new one, write `x := 3`.
## A derivative came out as 0
In `\frac{d f}{dx}`, `f` is a symbol unless something says it depends on x, and the
derivative of a symbol is 0. Write the function with its argument:
```python
>>> wb.exe(r"""
... \frac{d f}{dx}
... \frac{d f(x)}{dx}
... """)
[0, Derivative(f(x), x)]
```
## A script took one letter
As in TeX, `^` and `_` without braces take one letter, one command or one number:
`x^ab` is x to the power a, times b, and `\Gamma^r_tt` is `\Gamma^r_t` times t. Put
indices of more than one letter in braces:
```python
>>> wb.exe(r"x^ab + y^{ab}")
[b*x**a + y**ab]
```
## Letters became a product
In LaTeX, a run of letters is a product of single letters, as it is typeset:
`\frac{2GM}{c^2 r}` is 2·G·M/(c²r). Greek names, names you have defined and builtins
stay whole. To keep a longer name whole, write it in `\mathrm{...}` or `\text{...}`. In
plain text, outside a display and without LaTeX commands, a run of letters is one name:
```python
>>> wb.exe(r"""
... \frac{2GM}{c^2 r}
... \mathrm{GM} + 1
... """)
[2*G*M/(c**2*r), GM + 1]
```
## A name followed by a bracket became a function
`A(r)` with no space is a call: if nothing defines `A`, it is an unknown function, which
is how a metric writes one. To multiply by a bracket, leave a space or write `\,`:
```python
>>> wb.exe(r"""
... A(r)
... G\,(p^2 + q^2)
... """)
[A(r), G*(p**2 + q**2)]
```
## A line did not continue
A statement goes on to the next line while a bracket is open, after a line that ends
with an operator, and before a line that starts with one such as `+` or `=`. A line
that starts with `-` is a statement of its own, as `-x` is, unless it is indented further
than the line before. Indent the continuation of a long equation, or end the line before
it with the operator.
## `%` cut a line short
`%` starts a comment, as in LaTeX, so `x % 2` is not a remainder: RelativisticPy says so.
Write `#` for a comment in plain text.
## `R` or `g` is a symbol, not the curvature
`R` is the Ricci scalar, and `g` the determinant of the metric, unless the metric is
written with them, as the radius `R` of a sphere is; then they are its symbols. `Ric` is
always the Ricci scalar, and `\det(g_{\mu\nu})` always the determinant.
## The metric uses a name defined after it
Papers write "where Δ = 1 − 2M/r" after the line element. Define the names a metric is
written with before its line element, as a reader is told them, so that the metric is
the one meant from the start.
## A result changed from one run to the next
SymPy walks sets of symbols in an order that follows Python's hashes of their names, and
Python draws a new seed for those hashes in every process unless `PYTHONHASHSEED` fixes
it. So a few computations, some solves above all, can take another path in another run:
an answer in another form, or none. The command line fixes the seed: `relativisticpy`
and `relativisticpy mcp` start themselves again with `PYTHONHASHSEED=0` where it is not
set, and the processes they start inherit it (see [the command line](cli.md#environment)).
A workbook cannot fix the seed of the Python it runs in, which Python draws as it starts.
To reproduce a run exactly from Python, set the variable before Python starts, for a
script, a notebook server or the tests, whose kernels and workers inherit it:
```bash
PYTHONHASHSEED=0 python analysis.py
PYTHONHASHSEED=0 jupyter lab
PYTHONHASHSEED=0 pytest
```
`sys.flags.hash_randomization` is `0` in a Python whose seed is 0. Setting
`os.environ["PYTHONHASHSEED"]` in a Python already running fixes the seed of the
processes it starts afterwards, as the workers of `Workbook(workers=4)`, but not its own.
On Windows, where the command cannot start itself again, set it before running
`relativisticpy`: `set PYTHONHASHSEED=0` in a command prompt, `$env:PYTHONHASHSEED = 0` in
PowerShell. What is decided within a time limit, as a closed form sought for 5 s before a
number is computed instead, can still differ on a much slower or busier machine.
## Getting what you want out of a result
| To get | Write |
|---|---|
| a decimal number | `N(x)`, or `N(x, 5)` for five digits |
| the non-zero components of a tensor | `T.nonzero()` in Python |
| one component | `\Gamma^{r}_{\theta\theta}`, or `T["r", "theta", "theta"]` in Python |
| the equations of a tensor equation, to solve | `E.equations()` in Python |
| whether a claim holds | `holds(value)` in Python, or `E.holds()` |
| LaTeX | `latex(value)`, in the language or in Python |
| a NumPy function | `relativisticpy.numeric.lambdify`; see [Numerics](numerics.md) |
```python
>>> wb.exe("N(pi)\nN(pi, 5)")
[3.14159265358979, 3.1416]
```
## Still stuck
[The language reference](reference.md) lists everything the language reads, and
`relativisticpy help reference` prints it offline; `relativisticpy help NAME` describes
one function in full, with examples. An equation copied from a paper that
fails to run is a bug: please
[report it](https://github.com/cottrellashley/relativisticpy/issues).
**Next:** [The language](language.md), for the rules behind these answers, or the
[glossary](glossary.md).
# Coming from other tools
> **For:** users of SymPy, Mathematica and xAct, or EinsteinPy. **You will learn:** how
> what you write there is written here, and how RelativisticPy and SymPy work together.
RelativisticPy is not a library of functions to call but a language: you write the
mathematics, in LaTeX or plain text, and it computes it. Its results are SymPy values,
so whatever SymPy does to them still works.
```python
>>> import sympy
>>> from relativisticpy import Workbook
>>> wb = Workbook()
>>> wb.expr(r"g_{\mu\nu} := Schwarzschild(M)")
>>> K = wb.expr(r"R_{abcd} R^{abcd}")
>>> K
48*M**2/r**6
>>> sympy.diff(K, sympy.Symbol("r"))
-288*M**2/r**7
```
## SymPy
| SymPy | RelativisticPy |
|---|---|
| `x = sympy.Symbol("x")` | nothing: a name nothing defines is a symbol |
| `sympy.Symbol("a", positive=True)` | `a > 0`, or `Positive := [a]` |
| `f = sympy.Function("f")` | nothing: `f(x)` is an unknown function |
| `sympy.diff(f(x), x, 2)` | `f''(x)`, `\frac{d^2}{dx^2} f(x)`, or `diff(f(x), x, 2)` |
| `sympy.integrate(x**2, (x, 0, 1))` | `\int_0^1 x^2 \, dx`, or `integrate(x^2, (x, 0, 1))` |
| `sympy.Eq(x**2, 4)` | `x^2 = 4` |
| `sympy.solve(sympy.Eq(x**2, 4), x)` | `solve(x^2 = 4, x)` |
| `expr.subs(x, 2)` | `subs(expr, x, 2)`, or an evaluation bar |
| `sympy.Matrix([[1, 2], [3, 4]])` | `\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}` |
| `sympy.tensor.tensor` | index notation, as written: `R_{\mu\nu} - \frac{1}{2} R g_{\mu\nu}` |
A SymPy value can be bound to a name from Python, and used in the language:
```python
>>> x = sympy.Symbol("x")
>>> wb["f"] = sympy.sin(x) ** 2
>>> wb.expr(r"\frac{d}{dx} f")
2*sin(x)*cos(x)
```
## Mathematica and xAct
Mathematica's functions have their counterparts in the language, written as in LaTeX:
| Mathematica | RelativisticPy |
|---|---|
| `D[f[x], {x, 2}]` | `f''(x)` |
| `Integrate[f, {x, 0, 1}]` | `\int_0^1 f \, dx` |
| `Limit[Sin[x]/x, x -> 0]` | `\lim_{x \to 0} \frac{\sin x}{x}` |
| `Series[f, {x, 0, 5}]` | `series(f, x, 0, 6)`: SymPy counts the order of the remainder |
| `Solve[x^2 == 4, x]` | `solve(x^2 = 4, x)` |
| `DSolve[y'[x] == y[x], y[x], x]` | `dsolve(y'(x) = y(x), y(x))` |
| `Simplify[expr]`, `FullSimplify[expr]` | `simplify(expr)` |
| `Sum[1/n^2, {n, 1, Infinity}]` | `\sum_{n=1}^{\infty} \frac{1}{n^2}`, its closed form where there is one |
xAct's tensors are abstract until a chart gives them components. RelativisticPy works
at both levels too, without the definitions xAct asks for first:
| xAct | RelativisticPy |
|---|---|
| `DefManifold[M, 4, {a, b, c, d}]` | nothing: any letter, Latin or Greek, is an index |
| `DefMetric[-1, g[-a, -b], CD]` | `g_{\mu\nu} := \ldots`, or a line element, `ds^2 = \ldots` |
| `RiemannCD[-a, -b, -c, -d]` | `R_{abcd}` |
| `RicciCD[-a, -b]`, `RicciScalarCD[]` | `R_{ab}`, `R` |
| `EinsteinCD[-a, -b]` | `G_{ab}` |
| `ChristoffelCD[a, -b, -c]` | `\Gamma^{a}_{bc}` |
| `CD[-a][T[a, b]]` | `\nabla_a T^{ab}` |
| `ToCanonical[expr]` | `simplify(expr)`, for tensors without components |
| components with xCoba | components come with the metric: `\Gamma^{r}_{\theta\theta}` |
Without a metric, an equation between tensors stays notation, and `simplify` brings it
to a canonical form with the symmetries of the Riemann tensor, as `ToCanonical` does:
```python
>>> Workbook().expr(r"simplify(R_{\rho\sigma\mu\nu} + R_{\rho\mu\nu\sigma} + R_{\rho\nu\sigma\mu})")
IndexExpression(0)
```
## EinsteinPy
EinsteinPy builds a tensor object for each quantity from a metric object.
RelativisticPy computes what you write, and caches it for the metric in force:
| EinsteinPy | RelativisticPy |
|---|---|
| `MetricTensor(components, symbols)` | `g_{\mu\nu} := [[\ldots]]` after `Coordinates := [\ldots]`, or a line element |
| `einsteinpy.symbolic.predefined.Schwarzschild()` | `g_{\mu\nu} := Schwarzschild(M)` |
| `ChristoffelSymbols.from_metric(m).tensor()` | `\Gamma^{a}_{bc}` |
| `RiemannCurvatureTensor.from_metric(m)` | `R^{a}_{bcd}` |
| `RicciTensor.from_metric(m)` | `R_{\mu\nu}` |
| `RicciScalar.from_metric(m).expr` | `R` |
| `EinsteinTensor.from_metric(m)` | `G_{\mu\nu}` |
| `WeylTensor.from_metric(m)` | `C_{abcd}` |
| `.change_config("uu")` | the indices where you want them: `R^{\mu\nu}` |
| `einsteinpy.geodesic` | `relativisticpy.numeric.geodesic`; see [Numerics](numerics.md) |
Components are taken by coordinate name, and equations between tensors say whether
they hold:
```python
>>> wb.expr(r"\Gamma^{r}_{\theta\theta}")
2*M - r
>>> wb.expr(r"R_{\mu\nu} = 0")
R_{μν} = 0: holds in all 10 components
```
**Next:** [Getting started](getting-started.md), or the
[language reference](reference.md) for everything at once. From RelativisticPy 1.x, see
[Coming from 1.x](upgrading.md).
# Coming from 1.x
> **For:** users of RelativisticPy 1.x, the releases on PyPI from 1.1.9 to 1.2.9. **You
> will learn:** what still works, what changed, and the program of the 1.x README,
> rewritten.
RelativisticPy is a new implementation, from the reading of the text to the computing of
its results, and it starts its version numbers again, at 0.1.0. Most programs written for
1.x run, and most run as before; the changes below are the ones to look for.
## Installing
Version 1.2.9, the last of the 1.x releases, fails to import, because it needs a package,
`loguru`, that it does not declare. RelativisticPy now needs only SymPy, and Python 3.10
or newer. While PyPI still serves the 1.x releases, install it from GitHub:
```bash
pip install "relativisticpy @ git+https://github.com/cottrellashley/relativisticpy"
```
## What still works
- `import relativisticpy as rel` and `rel.Workbook()`, and its `expr` method.
- Index notation in the style of 1.x: `g_{mu}_{nu}`, `Ric_{mu}_{nu}`, and components
chosen with a colon, `Ric_{mu:0}_{nu:0}` and `C^{a:1}_{b:0 c:0}`.
- `Coordinates := [t, r, theta, phi]`, metrics as nested lists, and `**` for powers.
- `RHS`, `dsolve`, `subs`, `simplify` and `tsimplify`, and tensors defined from
expressions, such as `Gamma^{a}_{c f} := (1/2)*g^{a b}*(\ldots)`.
## What changed
- **`:=` and `=`.** In 1.x, `eq0 = Ric_{mu:0}_{nu:0}` named a value. Now `:=` defines, and `=` defines only what has no meaning yet; otherwise it is a claim,
which is checked. Write `:=` for every definition.
- **Names and unknown functions.** `B` and the unknown function `B(r)` are one name: once
`B` has a value, `B(r)` no longer means the unknown function. Give a solution a name of
its own, as `B_1` below.
- **Results.** `exe` returns a list of every value; `expr` returns the last. Arithmetic
is exact, so `1/2` is a half, not `0.5`.
- **Errors** are raised as exceptions, every one a `RelativisticPyError`, with the place
in the source and a hint, rather than returned as text.
- **LaTeX** runs as well as plain text: `\Gamma^{\lambda}_{\mu\nu}`, `\frac{1}{2}`,
`\partial_\mu`, line elements and whole environments.
- **Built-in names.** A bare `g` is the determinant of the metric, and `R` is the
Riemann tensor, the Ricci tensor or the Ricci scalar by its number of indices, unless
the metric is written with them as symbols.
- **Letters.** In LaTeX a run of letters is a product, as it is typeset: `2GM` is
2·G·M. In plain text it is one name.
- **Lists** are vectors and matrices in arithmetic: `2 [1, 2]` is `[2, 4]`.
- **Identities.** An equation that is an identity, such as
`e^{2a}(1 + b) = e^{2a} + b e^{2a}`, evaluates to `True`.
- **Notebooks.** `Workbook.markdown` takes the text of a document, not its path, and
returns it with the results typeset. `Workbook.run_file` runs a file.
- **Modules.** The modules of 1.x, such as `relativisticpy.core`,
`relativisticpy.gr` and `relativisticpy.symengine`, are gone. Import from
`relativisticpy` itself; [the Python API](python.md) lists what it holds.
## The README of 1.x, as it is written now
The README of 1.x derived the Schwarzschild solution in these steps:
```text
eq0 = Ric_{mu:0}_{nu:0}
eq1 = Ric_{mu:1}_{nu:1}
eq2 = Ric_{mu:2}_{nu:2}
eq5 = (eq0*B(r) + eq1*A(r))*(r*B(r))
B = RHS( dsolve(eq5, B(r)) )
eq6 = simplify( subs(eq2, B(r), B) )
A = RHS( dsolve(eq6, A(r)) )
```
Now it defines with `:=`, and names the solution for `B(r)` apart from the
function:
```python
>>> from relativisticpy import Workbook
>>> Workbook().expr("""
... Coordinates := [t, r, theta, phi]
... g_{mu}_{nu} := [[-A(r), 0, 0, 0], [0, B(r), 0, 0], [0, 0, r**2, 0], [0, 0, 0, r**2*sin(theta)**2]]
... eq0 := Ric_{mu:0}_{nu:0}
... eq1 := Ric_{mu:1}_{nu:1}
... eq2 := Ric_{mu:2}_{nu:2}
... B_1 := RHS(dsolve((eq0*B(r) + eq1*A(r))*(r*B(r)), B(r)))
... RHS(dsolve(simplify(subs(eq2, B(r), B_1)), A(r)))
... """)
C1 + C2/r
```
That is Schwarzschild's A(r), with the constants that the Newtonian limit fixes.
**Next:** [Getting started](getting-started.md), for what is new, and
[the language](language.md).
# Jupyter and notebooks
> **For:** anyone who works in Jupyter, or writes derivations in Markdown. **You will
> learn:** how results display in Jupyter, a first cell to start from, and how a Markdown
> file becomes a notebook that RelativisticPy runs and typesets.
To see a whole program typeset with its results, or to compute mathematics as you type
it, in Jupyter or marimo, see [Live mathematics in notebooks](live.md).
## Jupyter
Install RelativisticPy where Jupyter runs, with the extras your work needs (see
[Getting started](getting-started.md#install)), and start from this cell:
```python
>>> from relativisticpy import Workbook, display, holds
>>> wb = Workbook()
>>> wb.expr(r"g_{\mu\nu} := Schwarzschild(M)")
```
A workbook is a session, like the notebook it is in: what one cell defines, the next
uses. Each result displays as mathematics. A scalar is a SymPy expression, which
Jupyter typesets; a tensor shows its non-zero components, labelled by coordinate; an
equation between tensors says whether it holds; and a metric shows its line element.
What Jupyter shows is the LaTeX of `display.latex`:
```python
>>> print(wb.expr(r"\Gamma^{r}_{ab}")._repr_latex_())
$\displaystyle \begin{aligned}
\Gamma^{r}_{tt} &= \frac{M \left(r - 2 M\right)}{r^{3}} \\
\Gamma^{r}_{rr} &= \frac{M}{r \left(2 M - r\right)} \\
\Gamma^{r}_{\theta\theta} &= 2 M - r \\
\Gamma^{r}_{\phi\phi} &= \left(2 M - r\right) \sin^{2}{\left(\theta \right)}
\end{aligned}$
>>> print(wb.expr(r"R_{\mu\nu} = 0")._repr_latex_())
$$ R_{\mu\nu} = 0 \tag*{holds in all 10 components} $$
```
Numerical data shows as a table, labelled by its spaces, and large data is summarised,
never printed in full. An error shows as RelativisticPy's diagnostic, the place in the
source and the hint, without the frames of Python's traceback; set the environment
variable `RELATIVISTICPY_DEBUG=1` to see them.
A few habits help in a notebook:
- Write LaTeX in raw strings, `r"..."`, and longer programs in triple-quoted ones,
`r"""..."""`.
- `wb.exe(...)` returns every value of a cell's program, `wb.expr(...)` the last.
- `display.unicode(value)` gives a result as text, for `print`, and
`display.latex(value)` as LaTeX, for a paper.
- `Workbook(workers=4)` shares component-wise work, such as simplifying the Riemann
tensor of Kerr, among four processes.
## Markdown notebooks
A Markdown file is a notebook too. Write the derivation in Markdown, with the equations
in displays, `$$ ... $$`, as usual: GitHub and most editors typeset them, and
RelativisticPy runs them, in order, as one program.
```bash
relativisticpy notes.md # run the displays and print the results
relativisticpy notes.md --render # print the document, with the results typeset under each display
```
From Python, `Workbook.markdown(text)` does the same as `--render`, and
`Workbook.run_file(path)` the same as running the file:
```python
>>> print(Workbook().markdown("""A number, squared:
...
... $$
... x := 2
... x^2
... $$
... """))
A number, squared:
$$
x := 2
x^2
$$
$$
4
$$
```
The displays a notebook runs are `$$ ... $$`, `\[ ... \]`, display environments such as
`\begin{equation}`, and fenced blocks of maths, as GitHub writes them. A fenced block
marked `relativisticpy` (or `relpy`) is a program, run as it is written; other code
blocks, code spans and inline maths are text. The [examples](examples.md) are notebooks
of this kind, shown with their results.
**Next:** [Live mathematics in notebooks](live.md), for `show` and the editor,
[Examples](examples.md), or [the Python API](python.md) for every method of a workbook.
# Live mathematics in notebooks
> **For:** anyone who works in marimo or Jupyter. **You will learn:** how results show
> themselves typeset, what `show` shows, and how the editor computes as you type.
> **Before this:** [Jupyter and notebooks](jupyter.md).
Write mathematics in a notebook and see it computed as it is written. Results show
themselves typeset. `show` runs a program and shows each statement with its results,
its notes and its errors, in place. The editor computes a program as it is typed, and
computes any part of a statement you select.
## Install
```bash
pip install "relativisticpy[live] @ git+https://github.com/cottrellashley/relativisticpy"
```
The `live` extra adds anywidget, which the editor needs. Typeset results and `show` need
nothing more. marimo and Jupyter are your own: RelativisticPy installs neither.
## Results show themselves
In marimo and in Jupyter, a tensor, a metric, an equation, index notation and a geodesic
show themselves typeset, with nothing to call. marimo calls `_display_`, and Jupyter
`_repr_latex_`, or `_repr_html_` for numerical data, which is a table. Each goes through
`relativisticpy.display`, so a result looks the same in a notebook as at the command line:
```python
>>> from relativisticpy import Workbook, display
>>> wb = Workbook()
>>> wb.expr(r"g_{\mu\nu} := Schwarzschild(M)")
>>> vacuum = wb.expr(r"R_{\mu\nu} = 0")
>>> vacuum._repr_latex_() == display.jupyter_latex(vacuum)
True
>>> print(display.jupyter_latex(vacuum))
$$ R_{\mu\nu} = 0 \tag*{holds in all 10 components} $$
```
A scalar is a SymPy expression, which marimo and Jupyter typeset themselves.
## show
`show(source)` runs a program, one statement at a time, and gives back what the cell
shows: each statement typeset, then its results, what it defines and its notes. A
statement that fails shows its error in its place, as `error.render()` gives it, and the
statements after it still run, as `relativisticpy --render` typesets a Markdown notebook:
```python
>>> from relativisticpy.live import show
>>> shown = show(r"""
... g_{\mu\nu} := Schwarzschild(M)
... R_{abcd} R^{abcd}
... \frca{1}{2}
... \Gamma^{r}_{\theta\theta}
... """)
>>> print(shown)
g_{\mu\nu} := Schwarzschild(M)
defines the metric g_{μν} and the coordinates t, r, θ, φ
R_{abcd} R^{abcd}
48M²/r⁶
ParseError: unknown LaTeX command \frca
--> :4:1
|
4 | \frca{1}{2}
| ^^^^^
hint: did you mean \frac?
\Gamma^{r}_{\theta\theta}
2M − r
```
That is the text of it, for a console. In a notebook it is HTML, typeset by the
notebook: by KaTeX in marimo and by MathJax in Jupyter. From Python, it has the `steps`
of the program, as `Workbook.each` gives them, their `values` and `errors`, whether it
is `ok`, the `workbook` it ran in, and its `html()`:
```python
>>> shown.values
[48*M**2/r**6, 2*M - r]
>>> [error.kind for error in shown.errors], shown.ok
(['ParseError'], False)
```
Without a workbook, each call runs in a new one. With `workbook=`, the definitions of one
call are there in the next, as from one cell to the next:
```python
>>> show(r"\Gamma^{t}_{tr}", workbook=wb).values
[M/(r*(-2*M + r))]
```
## Python objects
Python reads the files, in its own cells, and the mathematics reads the objects by name:
`\texttt{signal}` is the object passed to `show` as `signal=signal`. The objects passed
come before the scope of the workbook, if it has one, and are read for that call alone
(see [Beyond spacetime](spaces.md#python-objects-by-name) for what each becomes):
```python
>>> import numpy as np
>>> signal = np.array([1.0, 2.0, 6.0])
>>> show(r"x_t := \texttt{signal}" "\n" r"\mathbb{E}_t[x_t]", signal=signal).values
[3.0]
```
In marimo, pass each object a cell's mathematics reads by name. marimo runs a cell again
whenever a name it uses changes, and it sees the names the cell passes, so the mathematics
follows the data. One cell reads the table:
```python
prices = pd.read_csv("prices.csv", index_col="date")
```
and another shows the mathematics, and runs again whenever `prices` changes:
```python
show(
r"""
P_{ta} := \texttt{prices}
\mathbb{E}_t[P_{ta}]
""",
prices=prices,
)
```
`Workbook(scope=globals())` reads any name of the notebook too, but marimo cannot see
which, so a cell that uses it does not run again when one of them changes.
## The editor
The editor is a widget: the source on the left, in LaTeX, plain text or Unicode, and on
the right each statement typeset with its results. In marimo:
```python
import marimo as mo
from relativisticpy import Workbook
from relativisticpy.live import Editor
editor = mo.ui.anywidget(Editor(Workbook()))
editor
```
In Jupyter and VS Code, `Editor()` as the last line of a cell shows it. What it does:
- **It computes as you type.** About 300 ms after you stop typing, the program runs, from
its first changed statement: the statements before it keep what came of them.
Ctrl+Enter runs it at once. A run that more typing makes stale is dropped.
- **It never changes your workbook.** `Editor(wb)` starts each run from a copy of `wb` as
it is then, so a half-typed definition never reaches it, and what other cells define
in `wb` is there at the next run.
- **Errors are where they are.** The span of an error is underlined in the source, and its
message, notes and hint show under the pointer and beside the statement.
- **Point and compute.** Select part of a statement and right-click it, or press
*Compute selection*, for a menu: compute, simplify, expand, does it hold, and copy
LaTeX. The part computed is the smallest expression that holds the selection, in the
workbook as it stands at that statement, and its answer shows under the statement.
Right-click a result for the same menu, on its statement, and to copy the result as
LaTeX or text. Click a statement on the right to select it in the source.
### Its value is data
What the editor shows is data: `source`, and `statements`, one for each statement, each
as a line of `relativisticpy --format json` gives it, with its values as
`display.data` describes them, each saying whether it is `complete` and whether it is
`approximate` (see [the command line](cli.md#forms-of-output)). In marimo, another cell
that reads `editor.value["statements"]` runs again whenever they change. From Python,
`run` computes the source at once, and waits for it:
```python
>>> from relativisticpy.live import Editor
>>> editor = Editor(wb, source="K := R_{abcd} R^{abcd}\nK r^6")
>>> statements = editor.run()
>>> [entry["statement"] for entry in statements]
['K := R_{abcd} R^{abcd}', 'K r^6']
>>> statements[0]["definition"], statements[1]["values"][0]["text"]
('defines K', '48*M^2')
>>> "K" in wb
False
```
Beside the fields of `--format json`, an entry has `start` and `end`, where its statement
is in the source, `typeset`, the LaTeX it is typeset from, and `definition`, what it
defines in words. Its `error` has `start` and `end` too, and is `rendered` as the command
line prints it. `compute` computes a part of the source, as the menu does, with `compute`,
`simplify`, `expand`, `holds` or `latex`:
```python
>>> editor.source = r"\frac{d}{dr}\left(1 - \frac{2M}{r}\right) = \frac{2M}{r^2}"
>>> answer = editor.compute(0, 41, "simplify")
>>> answer["part"], answer["values"][0]["text"]
('\\frac{d}{dr}\\left(1 - \\frac{2M}{r}\\right)', '2*M/r^2')
>>> editor.compute(0, len(editor.source), "holds")["holds"]
True
>>> editor.close()
```
### Where it computes
The editor computes in a worker process of its own, so that the notebook's kernel never
waits on it, in marimo and in Jupyter alike:
- **A time limit.** A run, or a part computed, may take 30 seconds, or what
`Editor(time_limit=...)` gives it. The statement over it is stopped and says so, the
statements before it keep their results, and those after it did not run.
- **Stale runs stop.** A run that more typing makes stale is interrupted, as Ctrl-C would
interrupt it.
- **A computation that does not stop** when asked, as one in a library's compiled code
may not, has its worker stopped five seconds later, and the next run starts another.
- **Memory.** The worker may use 4096 MiB, or `Editor(memory_limit=...)`, where the system
enforces it, as Linux does. A computation that needs more fails, and the editor goes on.
- **Your workbook goes with it.** The worker is given the workbook, pickled, with what it
has computed, whenever it has changed.
- **Python objects go as data.** `Editor(wb, scope=globals())`, or a dict of objects,
gives its programs a scope; without one, the workbook's. The objects a program names
are read in the notebook's process as each run starts, and go to the worker as what
they become, arrays, numbers and expressions, whenever they have changed: never the
scope itself. A Python function goes by name, where the worker can import it, as
`numpy.hanning` or a function of an installed module.
Where no process can be started, as in a notebook running in the browser, the editor
computes in the notebook's own process, without a time limit; so it does for a workbook
holding data no other process can take, or a program that calls a function defined in
the notebook, which no other process can import, and says why under each run. On Windows,
a stale run or a run over its time stops its worker, as there is no Ctrl-C to send it.
### Typesetting
The editor typesets with Temml 0.14.0, which RelativisticPy carries, with its MIT licence,
so that it works offline and loads nothing from the network. Temml writes MathML, which
the browser draws in the system's font for mathematics: Cambria Math on Windows and STIX
Two Math on macOS. On Linux, install one, such as Noto Sans Math or Latin Modern Math;
without one, brackets around a matrix do not stretch.
## Later
- Right-clicking a part of a typeset result, rather than all of it.
- Notebooks exported as pages that compute in the reader's browser.
**Next:** [Jupyter and notebooks](jupyter.md), for Markdown notebooks and the command
line's `--render`, or [the Python API](python.md), for every method of a workbook.
# Examples
> **For:** anyone who learns from worked examples. **You will learn:** what
> RelativisticPy makes of whole derivations, in General Relativity, quantum mechanics and
> finance, with every result shown.
Each example is a file in the `examples` folder of the repository. A Markdown example is
a notebook: its displays are the program, and its results are typeset under each
display, as `relativisticpy examples/NAME.md --render` prints them. A Python example is
shown with what it prints. Every example runs in the tests, and this page is written
from them, by `tools/examples.py`.
| Example | File | What it shows |
|---|---|---|
| [The Schwarzschild solution](#the-schwarzschild-solution) | `schwarzschild.md` | The Schwarzschild metric, derived from Einstein's equations in vacuum |
| [The Kretschmann scalar, from scratch](#the-kretschmann-scalar-from-scratch) | `kretschmann.md` | The Kretschmann scalar by hand, index by index, checked against the built-in |
| [The Friedmann equations](#the-friedmann-equations) | `friedmann.md` | The Friedmann equations and the continuity equation of an expanding universe |
| [Geodesics from a Lagrangian](#geodesics-from-a-lagrangian) | `geodesics.md` | The geodesic equations from a Lagrangian, checked against the Christoffel symbols |
| [Light near a black hole](#light-near-a-black-hole) | `light.py` | Python: light bent and captured by a black hole, integrated numerically |
| [Two spins](#two-spins) | `spins.md` | Two spins: an operator on a product space, its exact spectrum, and the evolution of a spin |
| [A portfolio of 500 assets, in index notation](#a-portfolio-of-500-assets-in-index-notation) | `portfolio.py` | Python: 500 assets, the tangency portfolio, risk as a metric, and real factors told from noise |
## The Schwarzschild solution
Every equation on this page is both LaTeX, which GitHub typesets, and
RelativisticPy, which computes. To see the results typeset under each step:
```bash
relativisticpy examples/schwarzschild.md --render
```
### The ansatz
Outside a static, spherically symmetric star, spacetime can be written with two
unknown functions of the radius, $A(r)$ and $B(r)$:
$$
\begin{aligned}
\mathrm{Coordinates} &:= [t, r, \theta, \phi] \\
g_{\mu\nu} &:= \mathrm{diag}\left(-A(r),\; B(r),\; r^2,\; r^2 \sin^2\theta\right)
\end{aligned}
$$
### The field equations
In vacuum the Ricci tensor vanishes. Three of its components carry the
information we need:
$$
\begin{aligned}
E_0 &:= R_{tt} \\
E_1 &:= R_{rr} \\
E_2 &:= R_{\theta\theta}
\end{aligned}
$$
This combination of the first two involves only first derivatives, and fixes
$B$ in terms of $A$:
$$
\begin{aligned}
B_1 &:= \mathrm{RHS}\left(\mathrm{dsolve}\left((E_0 B(r) + E_1 A(r))\, r\, B(r),\; B(r)\right)\right) \\
B_1
\end{aligned}
$$
$$
\frac{C1}{A\left(r\right)}
$$
Substituting into the third leaves an equation for $A$ alone:
$$
\begin{aligned}
A_1 &:= \mathrm{RHS}\left(\mathrm{dsolve}\left(\mathrm{simplify}\left(E_2 \big|_{B(r) = B_1}\right),\; A(r)\right)\right) \\
A_1
\end{aligned}
$$
$$
C1 + \frac{C2}{r}
$$
### The integration constants
Far from the star, the radial acceleration of a particle at rest must be
Newton's, $-GM/r^2$. With $A = 1 + C/r$ and $B = 1/A$:
$$
\begin{aligned}
g_{\mu\nu} &:= \mathrm{diag}\left(-(1 + \tfrac{C}{r}),\; \frac{1}{1 + \tfrac{C}{r}},\; r^2,\; r^2 \sin^2\theta\right) \\
\mathrm{solve}\left(\lim_{r \to \infty} r^2\, \Gamma^{r}_{tt} - G M,\; C\right)
\end{aligned}
$$
$$
[- 2 G M]
$$
So $C = -2GM$, and spacetime around any spherical mass is the Schwarzschild
metric. Its curvature invariant shows that $r = 2GM$ is no singularity at all,
while $r = 0$ is:
$$
\begin{aligned}
g_{\mu\nu} &:= \mathrm{diag}\left(-(1 - \tfrac{2 G M}{r}),\; \frac{1}{1 - \tfrac{2 G M}{r}},\; r^2,\; r^2 \sin^2\theta\right) \\
R_{abcd} R^{abcd}
\end{aligned}
$$
$$
\frac{48 G^{2} M^{2}}{r^{6}}
$$
## The Kretschmann scalar, from scratch
Built-in tensors are a convenience, not a requirement. Here every step of the
calculation of $K = R_{abcd} R^{abcd}$ is written out by hand, in the
plain-text notation, and checked against the built-in result.
```bash
relativisticpy examples/kretschmann.md --render
```
Schwarzschild spacetime, with $G$ and $c$ kept explicit:
$$
\begin{aligned}
Coordinates &:= [t, r, \theta, \phi] \\
g_{\mu\nu} &:= \mathrm{diag}\left(-(1 - \frac{2 G M}{c^2 r}),\; \frac{1}{1 - \frac{2 G M}{c^2 r}},\; r^2,\; r^2 \sin^2\theta\right)
\end{aligned}
$$
The Christoffel symbols, from their definition:
$$
\Gamma^{a}_{c f} := \frac{1}{2} g^{a b} \left(\partial_{c} g_{b f} + \partial_{f} g_{b c} - \partial_{b} g_{c f}\right)
$$
The Riemann tensor, from the Christoffel symbols:
$$
Riemann^{a}_{m b n} := \partial_{b} \Gamma^{a}_{n m} - \partial_{n} \Gamma^{a}_{b m} + \Gamma^{a}_{b l} \Gamma^{l}_{n m} - \Gamma^{a}_{n l} \Gamma^{l}_{b m}
$$
Its indices raised and lowered by hand, then contracted:
$$
\begin{aligned}
Upper^{a f h s} &:= g^{s q} g^{h c} g^{f b} \, Riemann^{a}_{b c q} \\
Lower_{a f h s} &:= g_{a n} \, Riemann^{n}_{f h s} \\
K &:= \mathrm{simplify}\left(Upper^{a f h s} Lower_{a f h s}\right) \\
K
\end{aligned}
$$
$$
\frac{48 G^{2} M^{2}}{c^{4} r^{6}}
$$
The built-in Kretschmann scalar agrees:
$$
K - R_{abcd} R^{abcd}
$$
$$
0
$$
## The Friedmann equations
A homogeneous, isotropic universe has the FLRW metric, with spatial curvature
$k$ and a scale factor $a(t)$ to be found:
```bash
relativisticpy examples/friedmann.md --render
```
$$
\begin{aligned}
Coordinates &:= [t, r, \theta, \phi] \\
ds^2 &= -dt^2 + a(t)^2 \left(\frac{dr^2}{1 - k r^2} + r^2 d\Omega^2\right)
\end{aligned}
$$
Fill it with a perfect fluid at rest, of density $\rho(t)$ and pressure $p(t)$:
$$
\begin{aligned}
u^{\mu} &:= [1, 0, 0, 0] \\
T^{\mu\nu} &:= (\rho(t) + p(t))\, u^{\mu} u^{\nu} + p(t)\, g^{\mu\nu}
\end{aligned}
$$
Einstein's equations $G_{\mu\nu} = 8 \pi G\, T_{\mu\nu}$ then hold component by
component. The time component is the first Friedmann equation,
$\left(\dot a / a\right)^2 = \frac{8\pi G}{3}\rho - k/a^2$:
$$
\begin{aligned}
F_1 &:= G_{tt} = 8 \pi G\, T_{tt} \\
\mathrm{solve}(F_1, \rho(t))
\end{aligned}
$$
$$
[\frac{3 \left(k + \left(a'\left(t\right)\right)^{2}\right)}{8 \pi G a\left(t\right)^{2}}]
$$
and a radial component gives the second, for the acceleration $\ddot a$:
$$
\begin{aligned}
F_2 &:= G^{r}{}_{r} = 8 \pi G\, T^{r}{}_{r} \\
\mathrm{solve}(F_2, \ddot{a(t)})
\end{aligned}
$$
$$
[\frac{- 8 \pi G a\left(t\right)^{2} p\left(t\right) - k - \left(a'\left(t\right)\right)^{2}}{2 a\left(t\right)}]
$$
Energy conservation, $\nabla_\mu T^{\mu\nu} = 0$, is the continuity equation
$\dot\rho + 3 \frac{\dot a}{a}(\rho + p) = 0$:
$$
\nabla_{\mu} T^{\mu t}
$$
$$
\frac{a\left(t\right) \rho'\left(t\right) + 3 p\left(t\right) a'\left(t\right) + 3 \rho\left(t\right) a'\left(t\right)}{a\left(t\right)}
$$
## Geodesics from a Lagrangian
A free particle in curved spacetime extremises
$L = g_{\mu\nu} \dot x^\mu \dot x^\nu$. Its Euler-Lagrange equations are the
geodesic equations.
```bash
relativisticpy examples/geodesics.md --render
```
$$
\begin{aligned}
g_{\mu\nu} &:= \mathrm{Schwarzschild}(M) \\
x^{\mu} &:= [t(\tau), r(\tau), \theta(\tau), \phi(\tau)]
\end{aligned}
$$
The Lagrangian, along the path:
$$
L := g_{\mu\nu} \dot{x}^\mu \dot{x}^\nu \Big|_{t = t(\tau),\; r = r(\tau),\; \theta = \theta(\tau),\; \phi = \phi(\tau)}
$$
The Euler-Lagrange equations, one per coordinate:
$$
EL_{\mu} := \frac{d}{d\tau} \frac{\partial L}{\partial \dot{x}^\mu} - \frac{\partial L}{\partial x^\mu}
$$
The $\theta$ equation, for example:
$$
EL_{\theta}
$$
$$
2 r\left(\tau\right)^{2} \theta''\left(\tau\right) - 2 r\left(\tau\right)^{2} \sin{\left(\theta\left(\tau\right) \right)} \cos{\left(\theta\left(\tau\right) \right)} \left(\phi'\left(\tau\right)\right)^{2} + 4 r\left(\tau\right) r'\left(\tau\right) \theta'\left(\tau\right)
$$
> note: r and θ are taken along the path, as r(τ) and θ(τ), in g_{\mu\nu} \dot{x}^\mu \dot{x}^\nu
Each is twice the geodesic equation
$\ddot x^\nu + \Gamma^\nu{}_{\alpha\beta}\, \dot x^\alpha \dot x^\beta = 0$
with its index lowered, which RelativisticPy confirms component by component:
$$
EL_{\mu} = \left. 2 g_{\mu\nu} \left( \ddot{x}^{\nu} + \Gamma^{\nu}_{\alpha\beta}\, \dot{x}^{\alpha} \dot{x}^{\beta} \right) \right|_{t = t(\tau),\; r = r(\tau),\; \theta = \theta(\tau),\; \phi = \phi(\tau)}
$$
$$
EL_{\mu} = \left. 2 g_{\mu\nu} \left( \ddot{x}^{\nu} + \Gamma^{\nu}_{\alpha\beta}\, \dot{x}^{\alpha} \dot{x}^{\beta} \right) \right|_{t = t(\tau),\; r = r(\tau),\; \theta= \theta(\tau),\; \phi= \phi(\tau)} \tag*{holds in all 4 components}
$$
> note: EL_{\mu} already has a value, so = compares it; to give EL_{\mu} a new value, write EL_{\mu} := ...
> note: r and θ are taken along the path, as r(τ) and θ(τ), in g_{\mu\nu} \dot{x}^\mu \dot{x}^\nu
> note: r and θ are taken along the path, as r(τ) and θ(τ)
## Light near a black hole
```python
"""Light near a black hole.
Rays of light pass a Schwarzschild black hole of mass M (with G = c = 1). A ray
passing far away is bent by 4M/b, Einstein's deflection of starlight; a ray
passing closer than b = 3√3 M is captured. Both numbers come out of the
geodesic equation, integrated numerically.
python examples/light.py
This needs NumPy and SciPy: pip install "relativisticpy[numeric]".
"""
import numpy as np
from relativisticpy import spacetimes
from relativisticpy.numeric import four_velocity, geodesic
M = 1.0
SCHWARZSCHILD = spacetimes.schwarzschild()
def ray(b, r0, length):
"""Light sent inwards from radius r0 with impact parameter b, until it falls in
(reaches r = 2.5M, inside the photon sphere) or has travelled ``length``."""
start = [0.0, r0, np.pi / 2, 0.0] # t, r, θ, φ
inward = -np.sqrt(1 - (1 - 2 * M / r0) * b**2 / r0**2)
u = four_velocity(SCHWARZSCHILD, start, [inward, 0.0, b / r0**2], kind="null", M=M)
return geodesic(SCHWARZSCHILD, start, u, (0.0, length), M=M, stop=lambda x, _: x[1] - 2.5 * M)
def deflection(b, r0=10_000.0):
"""How far a ray passing at impact parameter b is bent from a straight line."""
path = ray(b, r0, length=2 * r0)
r, phi = path["r"][-1], path["phi"][-1]
straight = np.pi - np.arcsin(b / r0) - np.arcsin(b / r) # the angle a straight line sweeps
return phi - straight
def critical_impact_parameter(low=4.0, high=7.0, steps=30):
"""The impact parameter dividing captured rays from escaping ones, by bisection."""
for _ in range(steps):
middle = (low + high) / 2
if ray(middle, r0=1000.0, length=3000.0).stopped:
low = middle
else:
high = middle
return (low + high) / 2
def main():
b = 100 * M
einstein = 4 * M / b
next_order = einstein + 15 * np.pi / 4 * (M / b) ** 2
print(f"Light passing at b = {b:g}M is bent by {deflection(b):.5f} rad.")
print(f" Einstein's 4M/b: {einstein:.5f} rad")
print(f" with the next order, + 15π/4 (M/b)²: {next_order:.5f} rad")
critical = critical_impact_parameter()
print(f"Light is captured below b = {critical:.5f}M,")
print(f" as the photon sphere predicts: 3√3 M = {3 * np.sqrt(3) * M:.5f}M.")
if __name__ == "__main__":
main()
```
It prints:
```text
Light passing at b = 100M is bent by 0.04122 rad.
Einstein's 4M/b: 0.04000 rad
with the next order, + 15π/4 (M/b)²: 0.04118 rad
Light is captured below b = 5.19615M,
as the photon sphere predicts: 3√3 M = 5.19615M.
```
## Two spins
Quantum mechanics in index notation. The state of a spin is a vector in a complex
space of two dimensions, $\mathcal{H} = \mathbb{C}^2$, and an operator on it is a
tensor with one index up and one down:
```bash
relativisticpy examples/spins.md --render
```
$$
\begin{aligned}
\mathcal{H} &:= \mathbb{C}^{2} \\
i, j, k, l &\in \mathcal{H}
\end{aligned}
$$
The Pauli matrices:
$$
\begin{aligned}
X^{i}{}_{j} &:= [[0, 1], [1, 0]] \\
Y^{i}{}_{j} &:= [[0, -i], [i, 0]] \\
Z^{i}{}_{j} &:= [[1, 0], [0, -1]]
\end{aligned}
$$
Two spins with a Heisenberg coupling $J$: an operator on $\mathcal{H} \otimes
\mathcal{H}$ is simply a tensor with two indices of each kind,
$H = J\, \vec\sigma_1 \cdot \vec\sigma_2$:
$$
H^{ik}{}_{jl} := J \left( X^i{}_j X^k{}_l + Y^i{}_j Y^k{}_l + Z^i{}_j Z^k{}_l \right)
$$
Its spectrum, exactly: the singlet at $-3J$ and the triplet at $J$, three times.
$$
\operatorname{spec}(H^{ik}{}_{jl})
$$
$$
\begin{aligned}
\operatorname{spec}(H^{i0}{}_{jl}) &= - 3 J \\
\operatorname{spec}(H^{i1}{}_{jl}) &= J \\
\operatorname{spec}(H^{i2}{}_{jl}) &= J \\
\operatorname{spec}(H^{i3}{}_{jl}) &= J
\end{aligned}
$$
The trace of $H$ vanishes, as it must for a sum of traceless products:
$$
\operatorname{tr}(H^{ik}{}_{jl})
$$
$$
0
$$
A single spin in a magnetic field precesses: the operator of its evolution over a time
$t$ is the exponential of the map $Z$, written without indices as a matrix is.
$$
U := \exp\left(-\frac{i \omega t}{2} Z\right)
$$
$$
U^{i}{}_{j}
$$
$$
\begin{aligned}
U^{0}{}_{0} &= e^{- \frac{i \omega t}{2}} \\
U^{1}{}_{1} &= e^{\frac{i \omega t}{2}}
\end{aligned}
$$
## A portfolio of 500 assets, in index notation
```python
r"""A portfolio of 500 assets, in index notation.
Ten years of daily returns on 500 assets, driven by five hidden factors and noise,
are bound to the tensor R_{ta}: t ranges over 2,520 days and a over 500 assets. From
there everything is notation, as it would be written on a page:
- the expected returns and the covariance, as expectations over the days;
- the tangency portfolio of Markowitz, computed with linear solves, never an inverse;
- risk as geometry, with the covariance as the metric of the assets;
- the spectrum of the correlation matrix against the Marchenko–Pastur law of random
matrices, which tells the five real factors from the noise.
python examples/portfolio.py
This needs NumPy and SciPy: pip install "relativisticpy[numeric]".
"""
import numpy as np
from relativisticpy import Workbook
DAYS, ASSETS, FACTORS = 2520, 500, 5
rng = np.random.default_rng(7)
factors = rng.normal(0, 0.01, (DAYS, FACTORS))
loadings = rng.normal(0, 1, (FACTORS, ASSETS))
loadings /= np.linalg.norm(loadings, axis=0) # every asset equally exposed
returns = 0.0004 + 0.6 * factors @ loadings + rng.normal(0, 0.01, (DAYS, ASSETS))
wb = Workbook()
wb["R_{ta}"] = returns
wb.exe(r"""
\mu_a := \mathbb{E}_t[R_{ta}]
\Sigma_{ab} := \mathbb{E}_t[(R_{ta} - \mu_a)(R_{tb} - \mu_b)]
m^a := \frac{(\Sigma^{-1})^{ab} \mu_b}{1_c (\Sigma^{-1})^{cd} \mu_d}
""")
tangency = wb["m"].to_numpy()
print(f"the tangency portfolio's weights sum to {tangency.sum():.6f}")
# Signal and noise: the spectrum of the correlation matrix.
wb["Z_{ta}"] = (returns - returns.mean(axis=0)) / returns.std(axis=0)
wb.exe(r"C_{ab} := \mathbb{E}_t[Z_{ta} Z_{tb}]")
spectrum = wb.expr(r"\operatorname{spec}(C^a{}_b)").to_numpy()
edge = (1 + np.sqrt(ASSETS / DAYS)) ** 2 # the largest eigenvalue of pure noise
real = int((spectrum > edge).sum())
print(f"{real} eigenvalues stand above the Marchenko–Pastur edge of {edge:.2f}")
# Risk as geometry: with the covariance as the metric of the assets, w^a w_a is a
# variance. (Raising an index of an asset uses the metric from now on.)
wb["w^a"] = np.full(ASSETS, 1 / ASSETS)
wb.exe(r"g_{ab} := \Sigma_{ab}")
variance = wb.expr(r"w^a w_a")
print(f"the variance of the equally weighted portfolio is {variance:.3e}")
```
It prints:
```text
the tangency portfolio's weights sum to 1.000000
5 eigenvalues stand above the Marchenko–Pastur edge of 2.09
the variance of the equally weighted portfolio is 2.372e-07
```
**Next:** [Jupyter and notebooks](jupyter.md), to write notebooks of your own, or the
[guides](language.md) behind each step.
# How it works
> **For:** contributors, and the curious. **You will learn:** how text becomes results,
> stage by stage, and where to add a function, a command, a spacetime or an operation.
```text
source text ─▶ lexer ─▶ tokens ─▶ parser ─▶ syntax tree ─▶ compiler ─▶ IR graph ─▶ executor ─▶ results
```
Each stage has one job, its own tests, and a module of its own:
| Stage | Module | Job |
|---|---|---|
| Lexer | `relativisticpy.language.lexer` | text to tokens; plain text, LaTeX and Unicode become one stream |
| Parser | `relativisticpy.language.parser` | tokens to a syntax tree that records what was written |
| Reader | `relativisticpy.reading` | what each name and each ambiguous form means, with a note where it could surprise |
| Typer | `relativisticpy.typing` | the rules of index notation and spaces: free and summed indices, positions, spaces |
| Lowerer | `relativisticpy.lowering` | the IR of each statement, a closed graph of named operations, computing nothing |
| Compiler | `relativisticpy.compiler` | the three passes over a statement, the session and the scope, and the data bound into them |
| IR | `relativisticpy.ir` | a graph of typed operations, interned |
| Executor | `relativisticpy.runtime` | computes the values outputs need, cached, in parallel |
| Algebra | `relativisticpy.tensors`, `relativisticpy.diffgeom` | tensors, contraction, curvature, simplification |
You can watch the pipeline at work:
```python
>>> from relativisticpy import Workbook
>>> from relativisticpy.language import parse, to_sexpr, tokenize
>>> [token.value for token in tokenize(r"\Gamma^{\mu}_{\nu\rho}")][:6]
['Gamma', '^', '{', 'mu', '}', '_']
>>> to_sexpr(parse(r"\frac{1}{2} g^{ab}(\partial_c g_{bd})"))
'(* (* (/ 1 2) (g ^[a b])) (* (∂ _[c]) (g _[b d])))'
>>> print(Workbook().ir(r"""
... Coordinates := [x, y]
... g_{ab} := diag(1, x^2)
... \Gamma^{x}_{yy}
... """))
%0 = const 1 Scalar
%1 = const x Scalar
%2 = const 2 Scalar
%3 = pow(%1, %2) Scalar
%4 = call diag(%0, %3) Value
%5 = to-array (2, 2)(%4) Value
%6 = metric(%5) Tensor_{ab}
%8 = inverse(%6) Tensor^{ab}
%11 = christoffel(%6, %8) Tensor^{#v0}_{#v1 #v2}
%12 = select 0=0, 1=1, 2=1(%11) Scalar
out %12
```
## The lexer
The lexer is where the two dialects become one. Greek letters in every
spelling (`\theta`, `theta`, `θ`, `\vartheta`) become the identifier `theta`;
operator commands become operators (`\cdot` is `*`, `\leq` is `<=`,
`\coloneqq` is `:=`); `\left`/`\right` pairs are matched, with display
brackets becoming grouping parentheses; and everything typographic is
absorbed: spacing, sizing, labels, math delimiters, alignment markers. Each
token records whether whitespace preceded it, whether that included explicit
LaTeX spacing such as `\,`, and whether it was written inside `\mathrm{...}`.
The LaTeX and Unicode vocabulary is data, in `relativisticpy.language.vocabulary`.
## The parser
A Pratt parser with one table of binding powers. It recognises notation, not
meaning: implicit multiplication, scripts and index lists, every derivative
notation, integrals that end at their differential, big operators, matrices,
`cases`, evaluation bars, function definitions and blocks.
Where notation is ambiguous, the tree keeps every reading. A script such as
`^{a}` is stored both as an expression (a power) and as an index list (a
component), and the compiler, which knows whether the base is a tensor,
chooses. When a script cannot be an index list, the reason is kept too, so
that if the compiler needs indices it can say precisely why they are wrong.
Errors point at the source and suggest fixes, and `to_sexpr` prints any tree
as an S-expression, which is how the parser's tests state what notation means.
## The compiler
The compiler gives the tree meaning, using a symbol table of what each name
is: a variable, a function, a tensor (with its index positions), the metric,
or nothing yet. It reads a statement in three passes, each a package with one job:
- the *reader*, `relativisticpy.reading`, decides what each name and each ambiguous
form means, and says so in a note where it takes the less likely reading;
- the *typer*, `relativisticpy.typing`, holds the rules of index notation and spaces,
each with one message;
- the *lowerer*, `relativisticpy.lowering`, emits the IR: notation, tensors and their
derivatives, statistics, linear algebra, expressions and definitions, each a module.
They are one walk of the syntax tree, as reading a form may need what was made of the
forms before it: the lowerer walks, and asks the reader and the typer. The `Compiler`
in `relativisticpy.compiler` is the three together, and orchestrates statements, with
the session and the scope. The reader records each decision it takes, with why, as the
statement's *reading*: `Workbook.explain` shows the readings of a program, computing
nothing.
The reader decides
- whether `x^{a}` is a power or a component, and whether `r_{s}` names a symbol;
- which built-in tensor a name means, by name and number of indices (`R` with
four indices is Riemann, with two Ricci, with none the Ricci scalar);
- whether `=` defines (`y = 2`, `ds^2 = ...`, a new tensor) or states an equation;
- what a run of letters means: one name in plain text, a product in LaTeX;
- what an operator such as `\partial_\mu` or `\frac{d}{dx}` acts on.
What a name with a subscript means, as `c_1`, `x_i`, `f_x`, `H_n` and `X_k`, and a name
with brackets after it, as `x[n]`, is decided by one resolver,
`relativisticpy.reading.subscripts`. It lists every reading in the order they are tried, a
user's definition first: a name the program defines, an index of a tensor, an entry of a
matrix, a member of a family, an element of a list, a member of a sample, a sequence at a
point, a partial derivative, a built-in tensor's index, a book name of an integer, and a
label. Each layer that lowers one of them asks the resolver, and holds no test of its own;
where the program defines a base as two things, the reading says which was taken.
It checks index notation before anything is computed, so a mistake costs
milliseconds rather than a Riemann tensor. Every value has a static type,
`Scalar`, `Tensor[indices]`, `Equation` or `Value`, and the index rules are
checked on these types: free indices of a sum must agree, an index may appear
at most twice, a summed index once up and once down.
The rule of one term, that an index is written once and is free, or twice, once up and
once down, and is summed, is `relativisticpy.typing.written.contraction`. The typer
keeps it as notation is compiled, and a check of a paper asks the typer whether a
statement surely breaks the rules as it is written, from its syntax alone, whatever its
tensors are, with `broken_rule`: what may be read otherwise, as a derivative or a Latin
index twice in one position, is not blamed, and a statement that does break them is
*ill-formed*.
The compiler computes nothing. What it needs to know comes from what is written or
from a declaration: a spacetime declares the coordinates its metric is in, a space
written `\mathbb{R}^{3}` its dimension, and a number of eigenvalues is written as one.
A definition that needs something of the value it makes, as a metric must be one, makes
a *check*: a node of the IR that the workbook computes as it runs the statement, before
the next is compiled. A metric that is degenerate, of the wrong size or not symmetric
is so refused where it is defined, saying why, and the definition is undone.
Tensor notation is lowered to a small core of operations. Raising or lowering
an index is a contraction with the metric; a covariant derivative is a partial
derivative plus one contraction with the Christoffel symbols per index; a trace
is a contraction of a tensor with itself; `T_{(ab)}` is a symmetrisation.
User functions are inlined at their call sites, in a child of the scope they
were defined in, which gives lexical scoping. A fork of the session, which a copy of a
workbook is made with, and in which `Workbook.ir` and `Workbook.explain` compile, gives
each function the fork's scope, so that it sees the names of the fork.
A tensor without components, such as \(T_{\mu\nu}\) in Einstein's equations,
is kept as notation instead: operations of the IR, `notation.tensor`, `notation.add`,
`notation.mul`, `notation.solve`, `notation.subs`, `notation.trace`,
`notation.simplify` and the rest, which the engines compute as SymPy tensor
expressions, from `relativisticpy.abstract`, through canonical forms computed by the
Butler–Portugal algorithm, with the identities of General Relativity added. What the
compiler needs to know of notation comes from each operation's type rule, in
`relativisticpy.typing.notation`: whether it is an equation, and the free indices of
each side, as they are written. Notation is computed as the statement that writes it
runs, as a check is, in the order it is written, so that what cannot be computed, as a
solve for a tensor the equation does not contain, is refused there. Each scalar factor
of notation, as \(8\pi G\), is an operation of the IR too; one computed from tensors is
refused.
Where notation meets components, as when a tensor is defined from it with a metric in
force, its terms are known only once it is computed. So the lowering is staged:
`notation.lower`, as the statement runs, has the lowerer write each term in the
language, its scalar coefficient bound to a fresh name, and compile it, in the
coordinates and with the metric and tensors in force where it is written; and
`notation.components` is the value of that IR. Its type comes from its rule: the free
indices of the notation, in the order they are written, over their spaces. This is the
one type that the computed value could have told otherwise: notation that vanishes has
zero components, with the free indices it is written with.
Every index ranges over a space, and a tensor's type records the space of each
axis: spacetime in General Relativity, or assets, days, a qubit (see
[Beyond spacetime](spaces.md)). An index label takes its space from a declaration,
`a, b \in \mathcal{A}`, or from the first tensor it is written on in a statement;
labels that do neither range over spacetime. The rules of summation follow each
space's metric: where it is the identity, an index may be summed in any position.
Expectations bind their index, so that factors share it, and are contracted with the
measure of its space in the same contraction as the factors. Products with an inverse
become linear solves.
Data bound from Python, as `wb["R_{ta}"] = returns`, and the data of a Python object a
definition names, as `P_{ta} := \texttt{prices}`, are bound into the session by
`relativisticpy.compiler.binding`: each axis over a space, by the rules of
`Workbook.__setitem__`, and data labelled by pandas in the order of its space's basis.
The spaces `Workbook.space` declares are declared there too, and the workbook only
orchestrates: it compiles text bound to a name, and hands everything else to the module.
## The IR
The IR is a graph of nodes, each an operation applied to other nodes, with a
static type. Operations are frozen data: `Contract`, `Permute`, `Select`,
`Partial`, `Symmetrize`, `Map`, `Add`, `Mul`, `Scale`, `Pow`, `Call`, `MakeArray`,
`ToArray`, `Equation`, `Inverse`, `LineElement` and `Geometry`.
No operation holds a Python function. A `Call`, or a `Map` over every component of a
tensor, holds the name of what it computes and its attributes, values known when
compiling. The registry of implementations, `relativisticpy/runtime/registry.py`, maps
each name to the function that computes it, with how many arguments it takes, whether it
applies to each component of a tensor and what kind of value it gives. A builtin has the
name the language calls it by, as `sin` or `solve`; what the compiler emits for notation
has a name of its own, as `core.sum` for a sum, `core.subs` for an evaluation bar,
`linalg.solve` for an inverse times a vector or `notation.solve` for a solve in index
notation. So the whole program can be read, printed and compared before anything is
computed.
The same operations compute symbolic components with SymPy and numerical ones with
NumPy: the kernels look at what they are given. A contraction of numbers is
`numpy.einsum`, in the order its optimiser finds cheapest, in slices when its
operands are too large to hold at once, as a matrix product for a SciPy sparse
matrix, and with `jax.numpy` for JAX arrays, through which `Workbook.grad`
differentiates.
The graph interns nodes: asking for the same operation on the same arguments
returns the existing node, so common subexpressions are shared. Each node also
has a *computation key* that ignores its type. Index names are part of the
type, so `A_{ab}B^{b}{}_{c}` and `A_{xy}B^{y}{}_{z}` are different nodes with
different types, but they share one key and one computed value. Renaming
indices is therefore free. A constant's key is its own, its number in its graph with the
graph's token, so that two constants are never one, and a workbook pickled for another
process, as the editor's worker takes one in, meets no key of that process's.
## The executor
The workbook runs a program a statement at a time: it compiles the statement, has
the executor compute its checks, and then the values it shows. The executor computes a
node by first computing whatever it depends on, and remembers every value by
computation key. Nothing is computed that no output or check needs, and nothing is
computed twice: asking for the Ricci tensor and then the Einstein tensor computes the
Ricci tensor once.
A statement runs as one step, a chain of relations, `a = b = c`, as one for each link,
and a statement that cannot be read as one, its error. `relativisticpy.steps` lists the
statements and the steps of a program before any runs, and says what came of each step:
what it defined, in words, and the step as data. The command line, the MCP server and
the editor list and describe steps with it alone.
What an executor holds is read with its `values()`, by computation key, and an
executor made with them need not compute them again: so the editor carries a workbook
to its worker process, with what it has computed.
Component-wise work, such as simplifying every component of a tensor or the
curvature kernels' simplification passes, goes through the executor's `map`.
With `Workbook(workers=N)`, large batches are spread over a pool of `N`
processes; SymPy expressions travel between them by pickling.
## Contraction
`relativisticpy.tensors.arrays.contract` is a sparse Einstein summation.
Curvature tensors are mostly zeros, so it multiplies only nonzero components,
and it contracts operands pairwise in a greedy order that keeps intermediate
results small. The Kretschmann scalar \(R_{abcd} R^{abcd}\), six operands with
the metric contractions, is a few hundred multiplications rather than the
\(4^8\) a dense product would need.
## Simplification
Components are kept in a normal form that suits relativity: trigonometric
functions are written with `sin` and `cos` only, and multiple angles are
expanded. This is how papers write Christoffel symbols (\(\cot\theta\) appears as
\(\cos\theta/\sin\theta\)), and it makes identities decidable by algebra.
Deciding whether a component vanishes is the most common question, so it has a
fast, exact answer: combine the expression into one fraction, expand the
numerator, and use \(\cos^2 x = 1 - \sin^2 x\) until no cosine has a power above
one. The numerator is then zero exactly when the component vanishes. This never
computes a polynomial GCD, the step that makes general simplification crawl.
It is why verifying that the Kerr metric is a vacuum solution takes seconds
rather than tens of minutes.
## Extending RelativisticPy
- **A function, or anything a library computes**: write an integration, a module of
`relativisticpy/integrations/` that declares capabilities, each checked by the
conformance suite; [Integrations](integrations.md) says how, step by step. The registry
in `relativisticpy/runtime/registry.py` registers each capability under its names.
- **A kind of Python object**, read by name as `\texttt{prices}`: an object integration
of the same package says what it becomes, data, a number, an expression or a function;
[Integrations](integrations.md#python-objects) says how.
- **A LaTeX command or symbol**: add it to `relativisticpy/language/vocabulary.py`;
structural commands need a case in the parser's `_command`.
- **A spacetime**: add a function to `relativisticpy/spacetimes.py`, declaring the
coordinates its metric is in, which the compiler reads without computing it, and
declare it as a constructor in `relativisticpy/integrations/spacetimes.py`.
- **An operation**: register what computes it in `relativisticpy/runtime/registry.py`
and have the lowerer, in `relativisticpy/lowering/`, emit a `Call` of its name; one
that is not a function of values, as a contraction is, is an op in
`relativisticpy/ir/ops.py` with a kernel in `relativisticpy/runtime/kernels.py`. A
rule of index notation it keeps goes in the typer, `relativisticpy/typing/`, and a new
reading of what is written in the reader, `relativisticpy/reading/`.
[The language reference](reference.md) is written from these tables, and from the
declarations of the integrations, by `relativisticpy/reference.py`, which says what each
name means. A new command needs a line there too; the tests say which, and
`uv run python -m relativisticpy.reference --write docs/reference.md` writes the page
again.
Every stage has its own tests under `tests/`, and every example in these pages
runs as part of the test suite.
**Next:** the [roadmap](roadmap.md), for what comes next.
# Roadmap
> **For:** anyone deciding whether RelativisticPy will do what they need, and anyone
> who would like to help. **You will learn:** what is done, what is being done now, and
> what comes next.
RelativisticPy began with one idea: Einstein's equations should look exactly as they do
in papers, with an engine that can compute them. It grew into a language that reads
mathematics in general, as it is written. These are its plans, and where each stands.
What was left on purpose, and why, is in `design/debt.md` in the repository.
## Done
- **Mathematics as it is written.** LaTeX, plain text and Unicode, mixed freely. Plain
text and Unicode are read as the LaTeX they spell, or refused. An equation pasted from
a paper runs as it is.
- **The core**: algebra; calculus, with derivatives in every notation, integrals,
limits, sums, products, series, `solve` and `dsolve`; linear algebra; and index
notation over any space, its rules checked before anything is computed.
- **Fields in their books' notation**, [each with a page](language.md#fields): special
functions, vectors and matrices, probability, signals, optimisation, number theory and
combinatorics, and quantum mechanics, with Dirac's notation and operators.
- **General Relativity**: metrics from line elements; the Christoffel symbols and the
Riemann, Ricci, Einstein and Weyl tensors; covariant and Lie derivatives; geodesics,
symbolic and numerical; eight known spacetimes; and tensor equations solved as tensor
equations, before there are components.
- **Nothing guessed silently.** A reading that could have been another carries a note,
and `explain` shows how each statement was read. What cannot be read or decided is
refused, saying where, why and what to write instead. What has no value, as 1/0 or an
integral that never settles, is refused too, and a closed form that numbers refute is
not given.
- **Data, and Python**: indices over assets, days or the states of a qubit; data from
NumPy, pandas, SciPy and SymPy; JAX for gradients; and Python objects by name,
`\texttt{name}`.
- **Checking papers**: `relativisticpy check` runs a paper's equations and says which
hold. Sean Carroll's lecture notes are the benchmark: 98.6% of their equations parse,
and the check finds three mistakes in them.
- **For agents**: an MCP server, to compute, verify a step, check a paper and read the
documentation. Each value says whether it is a complete answer, and whether it is
approximate; each refusal says why. The habits of NumPy and MATLAB, `A @ B`, `A.T` and
`eig(A)`, and `||x||_1` typed in plain text, are read as they mean, with a note.
- **Tools**: the command line, Markdown notebooks, Jupyter and marimo, and an editor
that computes as it is typed. The documentation is offline, in `relativisticpy help`.
- **A pipeline with one job for each pass**, from the lexer to the engines, and
**integrations to one pattern**: every function a capability that a module declares,
held to the pattern by a conformance suite, with no configuration.
- **Known answers**: a curriculum of 734 problems in 32 fields, and a notation matrix of
44 constructs of the core, each written every way books write it. Each answer is
computed without RelativisticPy, and the tests keep what passes passing.
## Now
- **No silent wrong answer.** A wrong answer known in the core, algebra, calculus,
linear algebra and index notation, is fixed before the next release, or refused with
what to write instead; those of other fields are fixed too, or listed in the notes of
the release. One is known as this is written that says nothing: units are
names, so \(\mathrm{Mpc}\,\mathrm{s}/(70\,\mathrm{Gyr}\,\mathrm{km})\) is not
converted (`design/debt.md`). Two say so in a note, and are not computed as meant: `j`,
which nothing defines, is a name in \(\left|\frac{1}{1 + j}\right|\), where an
engineer means the imaginary unit (decision 24 of `design/notation.md`); and a claim
after equations that hold its names, as Mandelstam's \(s + t + u = \sum_i m_i^2\)
after \(p_1 + p_2 = p_3 + p_4\) and \(p_i^2 = m_i^2\), is shown as an equation, not
decided under them (decision 3).
No program known gives an internal error: not in the docs, the curriculum, the
notation matrix, the tests, nor the seven papers the check is measured on.
`uv run python benchmarks/curriculum.py --failures` and
`uv run python benchmarks/notations.py --failures` list every wrong answer they find.
- **Climbing the curriculum.** What it refuses most, by cause, is in its own
[roadmap](https://github.com/cottrellashley/relativisticpy/blob/main/curriculum/ROADMAP.md).
## Next
- **A core with no SymPy in it**: an IR of plain terms, one elaborator that ranks the
readings of a form, and the notation of each field declared as data by its
integration; then the core rebuilt in Rust.
- **Results as terms, and other engines**: SymPy's answers translated back into the IR,
so that other engines can compute too, and two engines check each other.
- **Derivatives in index notation**: \(\nabla_\mu\) and \(\partial_\mu\) as part of the
notation, with the Leibniz rule, metric compatibility and the contracted Bianchi
identity \(\nabla^\mu G_{\mu\nu} = 0\), so that conservation laws can be derived
rather than only checked.
- **Abstract definitions**: `T_{\mu\nu} := (\rho + p) u_\mu u_\nu + p g_{\mu\nu}`
with a velocity that has no components yet, kept as notation until it has.
- **More of physics' implicit conventions**: \(x^\mu\) as the coordinates themselves,
coordinates along a curve, \(x^\mu(\lambda)\), and \(\eta_{\mu\nu}\) as the
Minkowski metric, so that more of a paper can be checked; and a field met with a path
taken along it in the IR, in every sum.
- **Premises in papers**: a premise a derivation states in prose, as
\(R_{\mu\nu} = 0\), and an identity that holds at a point, as in Riemann normal
coordinates, so that neither reads as a mistake. An equation for the functions a
metric is written with relates already.
- **Equations a program means to solve**: a design for which equations to solve unasked,
and which only state; and a claim decided under the equations stated before it.
- **What an agent reads**: a note that carries its kind, which a value's `reasons` are
read from, and `compute`'s claims judged as `verify` judges them.
- **Units**: quantities with units, converted and checked for dimensions.
- **Optimisation over a vector written with its index**: minimise
\(w^a \Sigma_{ab} w^b\) subject to constraints, with gradients from JAX.
- **Coordinate transformations**, with the Jacobian; **energy-momentum tensors** for
perfect fluids and the electromagnetic field; and **more spacetimes**:
Oppenheimer–Snyder collapse, Lemaître–Tolman–Bondi dust, Schwarzschild–de Sitter.
- **A visual engine, with [Manim](https://www.manim.community)**: derivations that
animate step by step, orbits and light rays, light cones, embedding diagrams and
Penrose diagrams, behind an optional `relativisticpy[visual]` extra.
- **Fields on grids**, for numerical relativity and for pictures, and the ADM
formalism.
- **A language server**, for highlighting, errors and "compute this" in editors; and
**pages that compute with no server**, in the reader's browser.
- **An evaluation**: how a model does with the `verify` tool and without it.
## Someday
Hawking radiation and the Penrose process as worked modules; analysis of real
data from gravitational-wave observatories; interactive tutorials for people new
to the subject.
Ideas and contributions are welcome:
[open an issue](https://github.com/cottrellashley/relativisticpy/issues).