Python for Plasma In Cells
A Python toolkit for reading, analyzing, and plotting plasma simulation output from particle-in-cell (PIC) and magnetohydrodynamic (MHD) codes.
Every simulation code invents its own file layout, field names, and normalization. pypic maps them all onto one canonical schema, so an analysis written against iPIC3D output runs unchanged against BATSRUS or OpenGGCM. Computation happens in normalized code units using pure NumPy functions — xarray is the container, not the compute engine — and SI conversion is applied only at I/O and display boundaries.
Requires Python 3.13+.
uv add pypic-plasma # or: pip install pypic-plasmaThe distribution is named pypic-plasma; the import name is pypic. The core
install pulls in NumPy, SciPy, xarray, h5py, and pydantic — everything heavier
sits behind an extra, and extras compose:
uv add "pypic-plasma[plot,cli]" # what most installs want
uv add "pypic-plasma[plot,zarr,cli]" # ... plus modern I/O| Extra | Pulls in | Enables |
|---|---|---|
plot |
matplotlib | Field slices, comparisons, line plots, kymographs, quiver/streamlines, spectra, and the theme system |
3d |
pyvista | 3D rendering and field-line visualization |
cli |
typer, rich | the pypic command |
zarr |
zarr, numcodecs, virtualizarr, icechunk | Zarr v3 export/import, VirtualiZarr views over legacy HDF5, Icechunk storage |
icechunk |
icechunk, zarr, numcodecs | Icechunk versioned storage without the VirtualiZarr dependency |
arrow |
pyarrow | Parquet/Arrow particle I/O |
duckdb |
duckdb, pyarrow | SQL queries over particle Parquet |
server |
fastapi, uvicorn, pyarrow, websockets | the Arrow IPC server behind pypic serve
|
To work from a checkout instead:
git clone https://github.com/rusaitis/pypic.git && cd pypic
uv sync --all-extras --all-groupsfrom pypic import open_simulation, PlaneSelection
# Format is auto-detected — iPIC3D, BATSRUS, OpenGGCM, or generic HDF5.
sim = open_simulation("path/to/output")
print(sim.describe()) # code, grid, species
print(sim.steps) # available timesteps
# Vector shorthand: "B" loads B_1, B_2, B_3.
data = sim.read(step=0, fields=["B", "E", "P_s0"])
# Derived quantities dispatch through the field registry.
b_mag = data.compute("|B|") # magnetic field magnitude
beta = data.compute("beta") # plasma beta, 2P/B²
v_a = data.compute("v_A") # Alfvén speed
# Code units internally; convert at the display boundary.
b_nt = data.in_units("B_1", "nT")
v_kms = data.in_units("v_A", "km/s")
# Selections describe regions and return an ordinary FieldDataset.
midplane = PlaneSelection(normal="z").apply(data)Unmatched field names raise KeyError rather than warning — a typo fails at
the call site instead of surfacing as missing data three steps downstream.
- Multi-code readers — iPIC3D (parallel HDF5, serial HDF5, H5hut), BATSRUS (IDL cell + HDF5 BATL with AMR regridding), OpenGGCM (Fortran binary 3df), and a generic HDF5 reader. Auto-detection via confidence-based probing.
- Derived quantities — field magnitudes, plasma beta, Alfvén speed, Mach numbers, Poynting flux, energy densities, pressure tensor decomposition, characteristic scales (skin depths, gyroradii, frequencies), entropy, reconnection diagnostics, and more. All pure functions: arrays in, arrays out.
-
Unit system — PIC (electron- or ion-referenced), MHD (Alfvén-speed-based),
SI, or custom normalization. Round-trip
Normalization.normalize()/.to_si()with display unit conversion ("nT","km/s","eV", ...). - Geometry-aware operators — divergence, curl, gradient with coordinate metric factors. Cartesian implemented; spherical/cylindrical planned.
-
Selections —
PlaneSelection,BoxSelection, andSphereSelectionslice 3D data into lower-dimensional views or masked subregions. -
Reductions —
pypic.reduce(ds, axis, reduction=...)collapses fields along one or more axes (trapezoidalintegrate,mean/median/sum,argmax/argminreturning coordinate positions). Pairs with selections for column densities, slab averages, and density-weighted line averages. - Field-line tracing — adaptive Dormand-Prince 5(4) tracer with error-norm step control, batched and scalar paths, plus Poincaré sections.
- Modern I/O — Zarr v3 export/import (single-step and time-series), Icechunk versioned storage, VirtualiZarr views over legacy HDF5, and Parquet/Arrow for particle data with Morton-ordered spatial pushdown.
-
Field registry —
compute("beta"),compute("|B|"),compute("v_A")dispatch to the right derived function. Extensible viaregister_recipe(). -
Arrow IPC server —
pypic serveexposes simulations over JSON HTTP plus a WebSocket that streams fields as Arrow record batches, with selections and derived quantities applied server-side. Zero-copy into browser (apache-arrow) and Rust (arrow-rs) clients. -
Command line —
pypic info,fields,stats,validate,compare,plot,plot-compare,convert,reduce,serve,export, andschema(export/validate/diff) — inspection, conversion, and publication figures without writing a script.
pypic is the Python half of a three-part toolchain built around the shared
simulation.toml schema:
rustpic (a Rust PIC/MHD solver) writes the schema, pypic reads and analyzes
it, and webpic (Three.js/WebGPU) renders it in the browser over the Arrow
IPC server in pypic.server. Both siblings are in development and not yet
public — you will see them named in the roadmap, in a few docstrings, and in
the [webpic] block of the bundled plot themes. pypic is fully usable on its
own; nothing here depends on either of them.
Full documentation, including the physics reference, lives at rusaitis.github.io/pypic.
| Page | Contents |
|---|---|
| Getting Started | Installation, loading data, first derived quantities |
| Tutorial | End-to-end analysis walkthrough |
| Equations | Every derived quantity with its LaTeX form and SI conversion |
| Conventions | Thermal speed, γ, temperature-in-energy-units, and the other choices that differ between textbooks |
| Schema | The simulation.toml contract and canonical field names |
Runnable, self-contained scripts live in
examples/ —
a numbered on-ramp from "arrays to FieldDataset" up to a full
simulation.toml, plus a worked custom reader.
pypic is early-stage research software (0.1.x) under active development. The core is in daily use — load data, compute derived quantities, compare runs, select subregions, convert units, make figures — and is covered by ~2800 tests including Hypothesis property tests, hand-calculated physics values, and NRL Formulary cross-checks.
The public API may still change before 1.0. Non-Cartesian operators, several additional readers (Vlasiator, VPIC, ARMS, openPMD), and the field-line mapping module are planned rather than implemented — see TASKS.md for the roadmap and what is already done.
If pypic contributes to work you publish, please cite it. The concept DOI 10.5281/zenodo.22059414 always resolves to the latest release; each release also gets its own version DOI. Metadata lives in CITATION.cff, which GitHub renders as a ready-to-paste citation via the Cite this repository button.
Bug reports, reader contributions for new simulation codes, and physics corrections are all welcome. See CONTRIBUTING.md for the development setup, test commands, and code conventions, and the architecture page for the design rules behind the code.
Participation is governed by the Code of Conduct. Security issues go through SECURITY.md, not public issues. Release notes live in CHANGELOG.md.
MIT — see LICENSE.
