Skip to main content

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.

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:

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.

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):

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:

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 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:

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:

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:

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

Metadata

Release files for treetensor 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for treetensor 0.5.0
File Actions
treetensor-0.5.0-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.12 abi3 Linux glibc 2.17+ x86-64 Details for treetensor-0.5.0-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
treetensor-0.5.0-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.12 abi3 Linux glibc 2.17+ ARM64 Details for treetensor-0.5.0-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
treetensor-0.5.0-cp312-abi3-macosx_14_0_arm64.whl CPython 3.12 abi3 macOS 14.0+ ARM64 Details for treetensor-0.5.0-cp312-abi3-macosx_14_0_arm64.whl
treetensor-0.5.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.11 CPython 3.11 Linux glibc 2.17+ x86-64 Details for treetensor-0.5.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
treetensor-0.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.11 CPython 3.11 Linux glibc 2.17+ ARM64 Details for treetensor-0.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
treetensor-0.5.0-cp311-cp311-macosx_14_0_arm64.whl CPython 3.11 CPython 3.11 macOS 14.0+ ARM64 Details for treetensor-0.5.0-cp311-cp311-macosx_14_0_arm64.whl

Total release size: 47.2 MB

Release files / treetensor-0.5.0-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL treetensor-0.5.0-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 11.1 MB
Tags CPython 3.12 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
fdf3fe59d7c2fbbc87dd734fd61d61a5ab5c5def5445b93a3e0c1288a825d453
BLAKE2b-256 checksum
How to use checksums
e549da252978b3ee9d5b09ad0080e86f062116e70004b0b147183d587a3950b5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Release files / treetensor-0.5.0-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL treetensor-0.5.0-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Size 7.0 MB
Tags CPython 3.12 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
f118c576e2c5ffcf2b75a0cb65bde3035d83a15b55fb7b73af142ed059652e0e
BLAKE2b-256 checksum
How to use checksums
0fd96870f13eb78706fc5d20ba9fe02dd1aa64a4c53b796bbf2a2688accf0f56
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Release files / treetensor-0.5.0-cp312-abi3-macosx_14_0_arm64.whl

Download URL treetensor-0.5.0-cp312-abi3-macosx_14_0_arm64.whl
Size 5.4 MB
Tags CPython 3.12 abi3 macOS 14.0+ ARM64
SHA-256 checksum
How to use checksums
dae48d5dcc186d56e4ec108992e58e02c04c222dd7988211735eeece23b82dc8
BLAKE2b-256 checksum
How to use checksums
327d93ddaab609ef76c04871f7ddf3663f87a0fa448c31199bc57185326d42c9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Release files / treetensor-0.5.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL treetensor-0.5.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 11.1 MB
Tags CPython 3.11 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
e0805a917eb712c24466d48f6b872f922adf3665fa8dc6c823b1cc36105507fa
BLAKE2b-256 checksum
How to use checksums
aa4be30061a7f384464c8e2a849e4d490f0217d68b51544b583e578d733cb9b6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Release files / treetensor-0.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL treetensor-0.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Size 7.0 MB
Tags CPython 3.11 Linux glibc 2.17+ ARM64
SHA-256 checksum
How to use checksums
b8da80f4823ffae304a41a80dac38c8c934fbe14dd1739f243b3e05e97e641c9
BLAKE2b-256 checksum
How to use checksums
c8e217f74798921d24c3cd852646c5a1aef8a8fbc9abc1eedbcbafe54d038c3e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Release files / treetensor-0.5.0-cp311-cp311-macosx_14_0_arm64.whl

Download URL treetensor-0.5.0-cp311-cp311-macosx_14_0_arm64.whl
Size 5.4 MB
Tags CPython 3.11 macOS 14.0+ ARM64
SHA-256 checksum
How to use checksums
2b1feca1038197f697e8a6c8dc96885e622d12de5c8134cf3afb30b915c2c166
BLAKE2b-256 checksum
How to use checksums
04b653a8997dc1ec002ff366f31933c442f4dd7bcb60ad31707a68fb27bb76ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Security for treetensor 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page