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.

Landau damping

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

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

Collision models and discovery

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

initial = tt.normalized(tt.maxwellian(velocity), space.volume)
electrons = tt.species("electrons", charge=-1, mass=1, velocity=velocity,
                      initial=initial, collisions=tt.collisions.bgk(frequency=0.1))
plasma = tt.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 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. species() also exposes its full keyword signature instead of an untyped **settings bag.

This API removes collision dictionaries and the old root-level method 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.4.1

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.4.1
File Actions
treetensor-0.4.1-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.4.1-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
treetensor-0.4.1-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.12 abi3 Linux glibc 2.17+ ARM64 Details for treetensor-0.4.1-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
treetensor-0.4.1-cp312-abi3-macosx_14_0_arm64.whl CPython 3.12 abi3 macOS 14.0+ ARM64 Details for treetensor-0.4.1-cp312-abi3-macosx_14_0_arm64.whl
treetensor-0.4.1-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.4.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
treetensor-0.4.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.11 CPython 3.11 Linux glibc 2.17+ ARM64 Details for treetensor-0.4.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
treetensor-0.4.1-cp311-cp311-macosx_14_0_arm64.whl CPython 3.11 CPython 3.11 macOS 14.0+ ARM64 Details for treetensor-0.4.1-cp311-cp311-macosx_14_0_arm64.whl

Total release size: 47.1 MB

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

Download URL treetensor-0.4.1-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
6076fe0a03a9d9c9d1bb0e9a8627e03654b29777052cefc161de8c9a1284c191
BLAKE2b-256 checksum
How to use checksums
05cbc795b1ff69c50a391c1413dde20dac11fb5141efd56e7ab424180147bd35
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.4.1-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL treetensor-0.4.1-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
230f2b3b7070b444324028078725cffac21425f7ba0b31b2964fb5d789f31986
BLAKE2b-256 checksum
How to use checksums
523fe6868b7ddc85af1ca28d04edd0415e0e66939df4c258de49abeefb30dd86
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.4.1-cp312-abi3-macosx_14_0_arm64.whl

Download URL treetensor-0.4.1-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
f3c5cacd786d0569c2391438d29cbe81246456a88212cbd400917a99912172fb
BLAKE2b-256 checksum
How to use checksums
8155598425fe00cd1a7d27c7ea6e9e9b51f568b2f5f479263ab9fe2a6fc19230
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.4.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL treetensor-0.4.1-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
e6ae8ef102a37edc89272d7624aa562e7bedcb7be66936d394baac64bdae42c0
BLAKE2b-256 checksum
How to use checksums
bba3b5153f22147c455d90e76c61554f7234419598a306e25232ffb8d5e3fa1b
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.4.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL treetensor-0.4.1-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
c8abdf3b28ba552dbab127670d332ea0d8b905db41f6656ca9530770f1a87db5
BLAKE2b-256 checksum
How to use checksums
bb550b0448279287cad9e3177dfce97753d8fe3231395b6a930ba55588189f26
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.4.1-cp311-cp311-macosx_14_0_arm64.whl

Download URL treetensor-0.4.1-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
0c5ff49e464be44cfa62d23ad5fe5793dc0befce39303bb620d47fc0095249cd
BLAKE2b-256 checksum
How to use checksums
f45b8fd0bae9cd17e96535bef1a2f562236176be9f497447a297d750054dfa4e
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.4.1

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