Metadata-Version: 2.1
Name: treetensor
Version: 0.5.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: notebook
Requires-Dist: anywidget>=0.11,<1; extra == "notebook"
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.

## Write equations in Python

Declare states, compose expressions and add equations to a model.
Ordinary Python functions can return symbolic operators:

```python
import math
import ttn as tt

x = tt.periodic("x", 32, [0, 2 * math.pi])
v = tt.periodic("v", 64, [-6, 6])
initial = tt.profiles.normalized(
    tt.profiles.cosine(x, offset=1, amplitude=0.04) * tt.profiles.gaussian(v),
    2 * math.pi,
)

def phase_advection(f, x, v, acceleration):
    return -v * tt.diff(f, x) - acceleration * tt.diff(f, v)

model = tt.Model()
f = model.state("f", [x, v], initial=initial)
# Free streaming: acceleration is zero. It may also be a symbolic field.
kinetic = model.group("kinetic", tt.ddt(f) == phase_advection(f, x, v, 0))
mass = model.observable("mass", tt.integrate(f, [x, v]))
simulation = tt.simulate(model, dt=0.01, steps=5000, max_rank=12)
simulation.advance()
values = simulation.tensor(f)
```

The expressions above build the C++ model directly.
Functions, loops and conditions use normal Python; they need no decorators or registry.
`simulate()` compiles the model, chooses its TTN representation and returns a simulation.

| Module | Role |
|---|---|
| `tt` | Equation grammar, axes, algebra, calculus, `Model`, `simulate` and `widget` |
| `tt.domains` | Physical domains: `flux_tube` and its metric-aware operators |
| `tt.geometry` | Magnetic equilibrium geometry: `s_alpha` and `miller` |
| `tt.profiles` | Composable initial values: `maxwellian`, `gaussian`, `cosine`, `samples`, `sampled`, `tree_sampled`, `vector` and `normalized` |
| `tt.physics` | Optional species, field closures and assembled `vlasov` recipes |
| `tt.collisions` | Typed BGK and Dougherty collision models |
| `tt.integrators` | Time integration methods and compositions |
| `tt.maps` | Transported coordinate maps |

## Optional recipe: Landau damping

A physics recipe builds the same `Model`, states, equation groups and observables.
Its result exposes them as `plasma.model`, `plasma.species`, `plasma.groups`, `plasma.fields` and `plasma.energy`.

```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.profiles.cosine(x, 0.5, offset=1, amplitude=0.04)
electrons = tt.physics.species("electrons", charge=-1, mass=1, velocity=velocity,
                      initial=tt.profiles.normalized(tt.profiles.maxwellian(velocity, density=density), space.volume))
fields = tt.physics.maxwell(c_squared=16, electric=tt.profiles.vector(x=-0.08 * tt.profiles.sine(x, 0.5)))
plasma = tt.physics.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
```

## Live notebook controls

Install notebook support for local Jupyter (this installation also works in Colab):

```sh
pip install "treetensor[notebook]"
```

The original web demo's heatmap, diagnostic plots and tensor tree are shared with notebooks.
Create a simulation and display its live widget:

```python
simulation = tt.simulate(plasma, dt=0.01, steps=5000, method=tt.integrators.strang(), max_rank=12)
viewer = tt.widget(simulation, model=plasma, plot=electrons.f, slice=[x, v])
viewer.show()
```

In Jupyter and Colab, Play starts a task on the Python kernel’s asyncio event loop.
It advances independently of browser requests and samples a new snapshot about five times per second.
The browser requests the latest frame with at most one snapshot request in flight; a slow transfer skips intermediate images without stalling the simulation.
Canvas painting is scheduled through requestAnimationFrame and coalesces updates.
The numerical time step is unchanged; diagnostics sample the viewer updates.
Single-step controls always take exactly one step through the Python kernel.
Backward controls call `simulation.retreat()`; irreversible methods reject backward evolution.
The task yields between roughly 20 ms compute chunks so controls and other notebook cells can run.
Pause takes effect once its command reaches the kernel, after the current chunk or an individual slow numerical step finishes.
Snapshots and advancement run on the same kernel thread. Snapshot extraction still costs CPU time, but rendering and network transfer need no simulation acknowledgment.
Reset calls `simulation.restart()` to recompile the original model and settings.
After advancing in another Python cell, call `viewer.capture()` to update the displayed result.
The kernel must stay connected for live controls.
Colab emits the bundled renderer as plain application/javascript output. It uses native Python callbacks and loads no viewer modules, Blob URLs, stylesheets or CDN scripts.
Live replies include the current frame and changed history samples, without resending static metadata or the full history.
The browser-only Pyodide demo uses bounded batches on its browser event loop; notebook playback runs on the remote or local Python kernel.

The numerical package requires only NumPy. The optional notebook extra adds anywidget and its Jupyter widget dependencies.
Pyodide connects directly to Python and does not install that extra.
`viewer.save("result.html")` exports the current visualization with controls disabled because it has no Python kernel.
The downloadable [demo notebooks](https://itsuwari.github.io/vlasov/) include physical definitions and editable Colab settings.

## Workflow

1. Declare axes with `tt.periodic(...)` or `tt.uniform(...)`; `tt.cartesian(x, y)` assigns physical components.
2. Create a `tt.Model`, then add states, equations with `model.group(...)`, and diagnostics with `model.observable(...)`.
   Initial profiles live in `tt.profiles`. All mathematical operators build native expressions that compose with normal arithmetic.
   Optional `tt.physics.vlasov(...)` recipes expose the same underlying `model`; add observables before the first `simulate()`.
3. Choose numerics with `tt.simulate(model, dt=..., steps=... | final_time=..., method=..., ...)`.
   The returned `Simulation` has `advance()`, `retreat()`, `time`, `steps`, `done`, `ranks`, `rank_capacity`, `rank_policy`, `tensor(...)`, `value(...)` and `report()`.
   A model can be simulated more than once.

For local gyrokinetic equations, create a domain with an explicit equilibrium:

```python
tube = tt.domains.flux_tube(
    nperp=9, ntheta=12, kymin=0.2,
    geometry=tt.geometry.s_alpha(q=1.4, shear=0.8, epsilon=0.18),
)
```

`tt.geometry.miller(...)` selects a shaped equilibrium.
Equilibrium parameters belong to the geometry object, rather than being repeated on `flux_tube()`.
The domain exposes its axes and metrics (`B`, `jacobian`, `mirror`, `drift_x`, `drift_y`) and symbolic operators.
Compose `parallel_streaming`, `mirror_force`, `magnetic_drift`, `diamagnetic_drive` and `bracket` to make the physical terms explicit.
`quasineutrality` and `ampere` provide field closures; `advection` remains an optional bundled expression.
The nonlinear ITG notebook shows the explicit composition.

## 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 live in `tt.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.
`tt.profiles.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.
`tt.profiles.sampled(indices, function)` and `tt.profiles.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=tt.integrators.ps_abug()` (default), or `tt.integrators.strang()`, `lie()`, `sgm()`, `pfg()`, `coupled_midpoint()`, or `rk4()` for dense states.
  All these factories live in the `tt.integrators` module. PFG's `core_flow` accepts `tt.integrators.CoreFlow.cayley`, `.pade22` or `.sdirk2`.
  A `Model` with several equation groups needs `scheme=`, built with `tt.integrators.advance(group, method)`, `tt.integrators.strang_split(a, b)` and `tt.integrators.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: tt.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.physics.vlasov)` and `help(tt.Model)` describe each call.
The package ships type stubs, so editors complete and check calls.

## Collision models and discovery

Collision physics and time integration use typed factory calls in separate modules:

```python
initial = tt.profiles.normalized(tt.profiles.maxwellian(velocity), space.volume)
electrons = tt.physics.species("electrons", charge=-1, mass=1, velocity=velocity,
                      initial=initial, collisions=tt.collisions.bgk(frequency=0.1))
plasma = tt.physics.vlasov(space=space, species=[electrons], fields=fields)
simulation = tt.simulate(plasma, dt=0.01, steps=5000, method=tt.integrators.strang())
```

`collisions=None` means collisionless evolution; `tt.collisions.dougherty(frequency=nu)` selects conservative drag and diffusion.
BGK options, such as `relative_tolerance`, `moment_tolerance` and `audit_positivity`, are explicit keyword arguments of `tt.collisions.bgk()`.
The resulting `BGK` and `Dougherty` objects are immutable and validated when constructed.
For explicit equations, `Dougherty.term(model, f, velocity, ...)` builds a kinetic term and `BGK.group(model, name, f, velocity, ...)` builds an exact relaxation group.
Both delegate to the same C++ collision physics used by `tt.physics.vlasov()`.

`tt.integrators` contains timestep methods and compositions; `tt.integrate(value, axes)` integrates over physical coordinates.
These are real Python modules with concrete signatures, return types and explicit exports, so completion shows available choices and their options.
`tt.physics.species()` also exposes its full keyword signature instead of an untyped `**settings` bag.

The 0.5 API groups predefined conveniences in real modules and removes their old root exports:

| Old call | New call |
|---|---|
| `tt.flux_tube(...)` | `tt.domains.flux_tube(...)` |
| `tt.s_alpha(...)`, `tt.miller(...)` | `tt.geometry.s_alpha(...)`, `tt.geometry.miller(...)` |
| `tt.maxwellian(...)`, `tt.gaussian(...)`, `tt.normalized(...)`, etc. | `tt.profiles.maxwellian(...)`, `tt.profiles.gaussian(...)`, `tt.profiles.normalized(...)`, etc. |
| `tt.species(...)`, `tt.vlasov(...)` | `tt.physics.species(...)`, `tt.physics.vlasov(...)` |
| `tt.maxwell(...)`, `tt.electrostatic(...)`, `tt.kinetic_alfven(...)` | The same constructors under `tt.physics` |

Move inline equilibrium parameters such as `flux_tube(q=..., shear=...)` into `geometry=tt.geometry.miller(q=..., shear=...)`.
The returned types live in their corresponding modules: `tt.profiles.Separable`, `tt.physics.Plasma`, `tt.domains.FluxTube` and `tt.geometry.FluxTubeGeometry`.
Axes, mathematical operators, `Model`, `simulate` and `widget` remain at the root.
The preceding 0.4 API also removed collision dictionaries and root-level integrator factories.
Replace `tt.strang()` with `tt.integrators.strang()` and `collisions={"model": "bgk", "frequency": nu}` with `collisions=tt.collisions.bgk(frequency=nu)`.
Replace PFG's string `core_flow="pade22"` with `core_flow=tt.integrators.CoreFlow.pade22`.

`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/.
