Metadata-Version: 2.1
Name: treetensor
Version: 0.3.0
Summary: Kinetic plasma simulation on tree tensor networks
Requires-Python: >=3.11
Project-URL: Homepage, https://itsuwari.github.io/vlasov/
Requires-Dist: numpy>=2
Provides-Extra: test
Requires-Dist: scipy>=1.17; extra == "test"
Description-Content-Type: text/markdown

# treetensor

Kinetic plasma simulation on tree tensor networks.
The `ttn` module calls a C++20 runtime in double precision.
The same Python API runs in double precision in Pyodide through the npm package [`@tensortree/plasma`](../web/npm/README.md).

```sh
pip install treetensor
```

Wheels exist for Linux x86_64 and aarch64 (glibc 2.17 or later) and for macOS 14 or later on Apple silicon.
Python 3.11 and later are supported.

## Landau damping

```python
import math
import ttn as tt

# Axes: tt.periodic(name, number of points, [start, end]).
x, v = tt.periodic("x", 48, [0, 4 * math.pi]), tt.periodic("v", 64, [-6, 6])
space, velocity = tt.cartesian(x), tt.cartesian(v)

# Electrons start as a Maxwellian with a small density wave.
density = tt.cosine(x, 0.5, offset=1, amplitude=0.04)
electrons = tt.species("electrons", charge=-1, mass=1, velocity=velocity,
                      initial=tt.normalized(tt.maxwellian(velocity, density=density), space.volume))
fields = tt.maxwell(c_squared=16, electric=tt.vector(x=-0.08 * tt.sine(x, 0.5)))
plasma = tt.vlasov(space=space, species=[electrons], fields=fields)
Ex = plasma.observable("Ex", tt.component(plasma.fields.electric, "x"))

# Step 0.05 up to t = 40, with TTN ranks chosen automatically up to 48.
simulation = tt.simulate(plasma, dt=0.05, final_time=40, max_rank=48)
while not simulation.done:
    simulation.advance()
    field = simulation.tensor(Ex)                      # NumPy copy over x
    energy = simulation.value(plasma.energy.total)     # float
    rank = simulation.max_rank                         # largest TTN rank
```

## Workflow

1. **Axes.** `periodic(name, cells, bounds)` and `uniform(...)` create axes; `cartesian(x, y)` groups them into a frame with x, y, z components.
2. **Model.** `vlasov(space=..., species=[...], fields=...)` returns a `Plasma` with the distribution `species.f`, the equation `groups`, and the `mass`, `energy` and `fields` observables.
   For gyrokinetic or custom equations, create a `Model` and call `state`, `group`, `observable`, `dougherty`, `pitch_angle_scattering` and `bgk` on it; `flux_tube(..., geometry=s_alpha(...) | miller(...))` provides the local magnetic chart (`B`, `jacobian`, `mirror`, `drift_x`, `drift_y`) and symbolic operators (`maxwellian`, `gyroaverage`, `quasineutrality`, `ampere`, `advection`, `bracket`, `flux_average`, `volume_average`).
   Add every observable to the model (`plasma.observable(...)` or `model.observable(...)`) before the first `simulate()`.
3. **Simulation.** `simulate(model, dt=..., steps=... | final_time=..., ...)` returns a `Simulation` with `advance()`, `retreat()`, `time`, `steps`, `done`, `max_rank`, `ranks`, `rank_capacity`, `rank_policy`, `total_steps`, and `tensor(x)` / `value(x)` for any state or observable of the model.
   A model can be simulated more than once, for example to compare methods.

## Values

Axes, states and expressions combine with `+ - * / **`; an axis stands for its coordinate, so `-v * tt.diff(f, x)` is the free-streaming term.
Elementary functions (`exp`, `cos`, `sqrt`, `bessel_j0`, ...) and calculus (`diff`, `grad`, `curl`, `integrate`, `average`, `dot`, `cross`, `component`) accept any of them.
`diff(value, axis, stencil=4)` uses centered differences of order 2, 4 or 6; across an axis linked by `Axis.identify` it reads the shifted coordinate.
`wave(axis)` is the Fourier wavenumber of a periodic axis, so `bessel_j0(...) * phi` applies a spectral multiplier, and `solve(operator, source, space)` inverts such operators on the modes selected by `space`.
Comparisons (`<`, `<=`, `>`, `>=`) of state-independent values give 0/1 indicators, which combine with `&`, `|` and `~`.

Initial values are usually profiles: `gaussian(axis, mean, sigma)`, `cosine(axis, k, amplitude=, offset=, phase=)`, `sine(...)`, `profile(axis, function)`, `samples(axis, values)` and `vector(x=..., y=..., z=...)`.
Profiles combine with `+`, `-`, `*` and `/` by a number, and stay separable, so a TTN state starts without sampling the full grid.
`normalized(profile, integral)` fixes the integral of an initial value and cannot be combined further.
A profile used in an expression becomes a coefficient table.
`sampled(indices, function)` and `tree_sampled(axes, function)` give nonseparable initial values; an expression also works.

## Numerics

All numerical settings are keyword arguments of `simulate()`:

- Time: `dt` and one of `steps` and `final_time`; `adaptive_error=[observables]` with `adaptive_tolerance` adapts the step.
- Method: `method=strang()` (default), `lie()`, `ps_abug()`, `sgm()`, `pfg(core_flow="cayley" | "pade22" | "sdirk2")`, `coupled_midpoint()`, or `rk4()` for dense states.
  A `Model` with several equation groups needs `scheme=`, built with `advance(group, method)`, `strang_split(a, b)` and `compose(a, b)`.
- Storage: states are tree tensor networks unless listed in `dense=[...]`.
  `tree={f: [[x, y], [z, v]]}` sets the tree of a state; `max_rank` (96 by default) caps the ranks, `rank_tolerance` selects them by a tolerance, and `fixed_rank` fixes them.
- Coordinates: `transport={f: maps.gyromotion(...)}` moves a state's coordinates; `split_streaming=False` advances free streaming with `method` instead of an exact substep.

Invalid settings raise `ValueError` with the path of the offending argument.
`help(tt.simulate)`, `help(tt.vlasov)` and `help(tt.Model)` describe each call.
The package ships type stubs, so editors complete and check calls.

`TTN_CPU_THREADS` sets the persistent CPU executor's thread count, including the calling thread.
Set it before the first simulation; it defaults to one.
Use one BLAS thread when enabling the executor's parallelism:

```sh
TTN_CPU_THREADS=4 OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 VECLIB_MAXIMUM_THREADS=1 MKL_NUM_THREADS=1 python simulation.py
```

Native Python links the same `ttn_runtime` library as the C++ benchmarks through `ttn_api` and the nanobind extension.
To rebuild the extension from the current source, enable `TTN_BUILD_PYTHON` in the native CMake configuration and build `_ttn` and `_ttn_stub` with `-j8`.
The build-tree package is under `build/ttn-native/python` at the repository root.
The Pyodide wheel is compiled from the same runtime source for WebAssembly; its current executor supports one worker.
The live browser demo is at https://itsuwari.github.io/vlasov/.
