Metadata-Version: 2.4
Name: dmipy-sim
Version: 3.0.0
Summary: dmipy-sim: GPU Monte-Carlo diffusion-MRI simulator (the forward-truth engine)
Author-email: Rutger Fick <fick.rutger@gmail.com>
License: AGPL-3.0-only OR LicenseRef-Commercial
Project-URL: Homepage, https://dmipy.org
Project-URL: Repository, https://github.com/dmrai-lab/dmipy-sim
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: GNU Affero General Public License v3
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: jax>=0.6.2
Requires-Dist: numpy>=2.0
Requires-Dist: dmipy-replay<0.3,>=0.2
Requires-Dist: dmipy-analytic[jax,special]<4,>=3
Requires-Dist: scipy>=1.11
Requires-Dist: safetensors>=0.4
Requires-Dist: threadpoolctl>=3.1
Provides-Extra: bank
Requires-Dist: huggingface_hub>=0.20; extra == "bank"
Provides-Extra: torch
Requires-Dist: dmipy-replay[torch]<0.3,>=0.2; extra == "torch"
Provides-Extra: cuda12
Requires-Dist: jax[cuda12]>=0.6.2; extra == "cuda12"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: matplotlib>=3.5; extra == "dev"
Requires-Dist: dmipy-sim[images,mesh]; extra == "dev"
Provides-Extra: interop
Requires-Dist: dipy>=1.8; extra == "interop"
Provides-Extra: mesh
Requires-Dist: trimesh[easy]>=4.0; extra == "mesh"
Requires-Dist: networkx>=2.8; extra == "mesh"
Provides-Extra: images
Requires-Dist: nibabel>=5.0; extra == "images"
Requires-Dist: tifffile>=2023.1; extra == "images"
Requires-Dist: h5py>=3.8; extra == "images"
Provides-Extra: examples
Requires-Dist: dmipy-fit<4,>=3; extra == "examples"
Provides-Extra: pulseq
Requires-Dist: pypulseq>=1.5.0; extra == "pulseq"
Dynamic: license-file

# dmipy-sim

**Diffusion Microstructure Imaging in Python** — the Monte-Carlo **replay engine**. Spins random-walk
through an explicit tissue substrate. A Monte Carlo walk's natural output is neither an acquisition-specific
signal nor a trajectory history but an acquisition-independent set of sufficient projections, accumulated while
the physics is simulated: the engine encodes as it goes, and the same walk answers any gradient waveform
`G(t)`. Wall physics (surface relaxivity, membrane permeability, magnetization transfer), per-compartment
relaxation and susceptibility fields are part of the walk. Everything is JAX (`vmap`/`scan`) and runs on CPU or a
CUDA-12 GPU.

> One `G(t)` and one substrate across the whole loop — **design** the sequence, **simulate** the
> signal, **fit** the tissue:
> **[dmipy-design](https://github.com/dmrai-lab/dmipy-design)** · sequence design &nbsp;·&nbsp;
> **dmipy-sim** · Monte-Carlo forward *(you are here)* &nbsp;·&nbsp;
> **[dmipy-fit](https://github.com/dmrai-lab/dmipy-fit)** · analytical inverse &nbsp;·&nbsp;
> **[dmipy](https://github.com/dmrai-lab/dmipy)** · umbrella + docs at **[dmipy.org](https://dmipy.org)**.

## What this is: a representation, not just a signal

The proposal is a chain of declared, portable objects. A **substrate generator** (CACTUS, CATERPillar, a
DiSCo strand list, the calibrated white matter of `Substrate`, or an analytic geometry) is written down as a
**substrate spec**: where the walls are, which pool is on which side, what each wall does to a spin, where
walkers are seeded. The **engine** walks that spec once and freezes the walk as a **replay pack**: the walk
itself and nothing about how it will be read. Every physical value and every acquisition is then a **replay
knob**: the same pack answers any gradient waveform, any RF schedule, any tissue value, any pose, without
another simulation. Packs tile into a **replay phantom**, where the macroscopic layer lives: fibre
distributions and fractions per voxel, and the maps a scanner adds on top of the microstructure.

```mermaid
flowchart LR
    subgraph gen["substrate generators"]
        direction TB
        G1["CACTUS · CATERPillar · DiSCo strands"]
        G2["Substrate.canonical(...).request(...)"]
        G3["analytic geometries: Cylinder, Sphere, Mesh, ..."]
    end
    SPEC["SubstrateSpec (.sub.json)<br/>domain · pools · walls and their physics<br/>seeding · request vs realisation · nominal values"]
    ENGINE["dmipy-sim engine<br/>walk / simulate<br/>sub-steps from the spec's smallest feature<br/>the envelope gives the band, the band gives the block<br/>accumulated in the walk"]
    RPK["Replay Pack (.rpk)<br/>positions as bridge + K sine bands<br/>occupancy · wall contact · field basis<br/>+ the spec, no tissue value"]
    subgraph knobs["replay knobs"]
        direction TB
        K1["tissue: T2 / T1 per pool · rho2 · chi<br/>scanner: B0 · pose: the field's direction"]
        K2["acquisition: any G(t) exactly · RF schedule (vector Bloch) · b-tensors · CPMG"]
        K3["pose: one rotation · or a distribution of rotations (SO(3) composition)"]
    end
    SIG["signal · any scanner, any sequence"]
    RPH["Replay Phantom (.rph)<br/>packs over a voxel grid · poses + fractions per voxel<br/>peaks · ODF · frames · Bingham fans<br/>per-voxel layers (B1 transmit, field map)"]
    gen --> SPEC --> ENGINE --> RPK --> knobs --> SIG
    RPK --> RPH --> knobs
```

The formats are open specifications, versioned together in
[replay-pack-spec](https://github.com/dmrai-lab/replay-pack-spec): `SUBSTRATE.md` (the spec), `RPK.md`
(the pack), `RPH.md` (the phantom). A pack from the substrate bank reproduces its paper by firing a pulse
at it, and the same pack serves a fitting framework, an acquisition designer and a tractography phantom.

## Two ways to get a signal

**In one call**: `simulate` walks the substrate to coefficients (the producer, at the band the acquisition reads) and
contracts them with the acquisition (the replay), and returns the signal.

```python
from dmipy_sim import simulate, Cylinder, sequences

seq  = sequences.pgse([[1, 0, 0]] * 3, 0.01, 0.04, bvalues=[0, 1e9, 2e9])                     # exact G for the requested b
spec = Cylinder(radius=5e-6, orientation=(0, 0, 1)).spec           # the situation, written out: an open box,
spec.save("cylinder.sub.json")                                    #   one lumen pool seeded, a reflecting wall
E    = simulate(n_walkers=100_000, diffusivity=2e-9, waveform=seq, geometry=spec, seed=0)
```

Every driver takes the substrate as a **spec** (`SubstrateSpec`; a spec dict is `SubstrateSpec.from_dict(d)` and a
`.sub.json` is `load_spec(path)` first) or as the
geometry object that is one spelling of it; `geometry.spec` writes out what a constructor leaves implicit, and a
substrate with no spec spelling is refused.

**Walk once**: keep the walk, replay any acquisition on it. The walk records every replay
tier the substrate supports — positions (C0), compartment occupancy for per-pool T2/T1 (C1), the
boundary local time for surface relaxivity (C2), and, through a field basis, the susceptibility field
(C3) — each as the band projections of its running integral. A `.rpk` replay pack is that walk, certified
without a raw path; it is what the substrate bank distributes and what dmipy-fit fits against.

```python
from dmipy_sim.substrate import Substrate
from dmipy_replay import envelope_of
from dmipy_sim import walk
from dmipy_replay import ReplayPack
from dmipy_sim.replay.bank import build_replay_pack
from dmipy_sim.replay.container import save_pack
from dmipy_replay import sequences
# the substrate: histology-calibrated white matter, realised as a SPEC -- domain, pools, walls, seeding,
# what was requested and what was achieved, all written out (replay-pack-spec/SUBSTRATE.md)
sub  = Substrate.canonical(field_T=3.0)          # diameter law (floored at d_min), g-ratio, f_axon, D, T2, rho, kappa
spec = sub.request(n_fibres=300, seed=0)         # refuses an infeasible packing; records the realised fraction and gaps
spec.save("wm.sub.json")

# 1. walk once, from the spec and nothing else -- positions, occupancy and boundary local time are recorded
# the envelope is what the pack is certified for: a scanner class's band and amplitude, the field and tissue bounds
env = envelope_of("connectom", B0_list=(3.0,), chi_max=1.06e-6, rho2_max=1e-4)
w = walk(spec, 200_000, T_max=0.05, seed=0, envelope=env)   # the walk accumulates the envelope's band

# 2. compress into a pack: channels (positions, occupancy, local time, field basis) and the spec -- not one
#    T2, rho2 or chi value lives in the pack; those are what a replay applies
pack = build_replay_pack(w, id="wm/canonical", license="CC-BY-4.0", citation="...")   # states the walk's envelope
save_pack(pack, "wm.rpk")                         # dmipy_sim.replay.container

# 3. anywhere, later: load it and fire a pulse at it
pack = ReplayPack.load("wm.rpk")
seq  = sequences.pgse([[1, 0, 0]], 0.01, 0.03, bvalues=[1e9])
E    = pack.replay(seq)                             # the bare diffusion signal: no tissue, no field
E1   = pack.replay(seq, tissue=pack.nominal, scanner=pack.nominal_field_T)      # the paper's replay: the spec's
                                                    # T2 / T1 per pool, rho2 and chi at its calibration field (3 T here)
E2   = pack.replay(seq, tissue=pack.nominal.replace(T2={"intra": 0.08}), scanner=7.0, orientation=(1, 0, 0))
                                                    # every value is a knob: same walk, one T2 changed, another scanner, another pose
```

Three things describe a replay setting, each stated once. `tissue=` is **what the material is**: a `Tissue`
(T2 / T1 as `{"intra": 0.05, ...}` over every pool of the pack's spec, `rho2`, `D`, `chi_iso`, `chi_aniso`) or
`None`, the bare diffusion signal; the spec the pack embeds carries the substrate's nominal values as
`pack.nominal`, so a published pack reproduces its paper with no second file, and `.replace(...)` changes one
pool and keeps the rest. `scanner=` is **what
the scanner is**: its static field, from the catalogue (`ScannerLimits.of("connectom")`) or in tesla. A tier
runs when its inputs are given and the pack carries it; `compartment=1` restricts the mean to one pool. The
pose is the third: `orientation=` takes either **one pose** — a rotation, or the lab direction the substrate axis points
along, exact by pose covariance since the gradient and the field rotate together — or **a distribution of
poses**, composed on SO(3). A pose is a rotation and not an axis, so nothing assumes the substrate is axially
symmetric: `pack.pose_response(seq)` expands the response in the real Wigner basis, and
`Distribution.watson(...)` / `.bingham(frame, (k1, k2))` / `.axis(direction)` / an `FOD` in a **named** basis
are its counterpart, so an anisotropically fanned population composes as easily as a cone. A distribution over
directions alone says nothing about the substrate's own azimuth, and that azimuth is then integrated away
exactly rather than sampled. A bare coefficient array is refused: the basis must be named, and the expansion
refuses a truncation that cannot hold the response. A tier that is requested but not carried
raises; nothing is silently skipped.

**By reference, and in one pass.** A pack too large to load (DiSCo: 150 million walkers, 190 GB) is opened where
it is and read by range: `ReplayPack.open("hf://SubstrateCommons/disco-replay/disco")` or a directory of the
columnar layout, `pack.plan(seq)` says which bands, tiers and bytes an acquisition needs before any transfer,
`pack.view(voxels=...)` is an ordinary pack of some voxels' rows, and `pack.image(...)` replays a whole grid in
one pass over the rows. A `Study` names a protocol (acquisitions, each a sequence in a pose), the tissues and the
scanners, and is replayed once: the bands are contracted per acquisition, every tissue and scanner is arithmetic
on the result, and an image of every pair comes from one read with a certified floor per volume.

```python
from dmipy_replay.replay.study import Acquisition, StudyProtocol, Study
study = Study(StudyProtocol([Acquisition(seq)]), tissues=[None, pack.nominal], scanners=[None, 3.0, 7.0],
              pairs=[(0, 0), (1, 1), (1, 2)])                    # bare, white matter at 3 T, white matter at 7 T
S = pack.study(study)                                            # (pairs, n_meas) on a loaded pack
S, floor, plan = big.image(study)                                # (pairs, *grid, n_meas) on a pack opened by reference
```

**[The replay guide](docs/replay-guide/README.md)** is the manual for all of this: one page per object (pack,
sequence, tissue, scanner, orientation), the knob table that says what each one touches in the contraction and
which channel it needs, the operations from `replay` down to the per-walker primitives a study reuses, images
from the hub, and two recipes. Every code block on its pages runs in the test suite.

**[The step law, shown](docs/step-law.md)** is the evidence for the walk's step: the two-length step that carries the
Gaussian step's moments, the operator of the engine's own reflection on the analytic pores, the oracle against it,
the two-walk certificate every build records, and what the step costs. `tools/gen_step_law.py` regenerates every number
on it from the code; `tests/test_step_law_report.py` runs its small tier.

## Replay phantoms: voxels from packs

A pack answers for one microstructure at any pose. A **replay phantom** (`.rph`, spec in
[RPH.md](https://github.com/dmrai-lab/replay-pack-spec)) is a voxel grid that cites packs, and there are two ways to
arrive at one:

* **Composition** places solved packs into voxels you declare: which substrate is where, in what volume fraction,
  at what pose, with what proton density. One pack serves every voxel and every pose that cites it, so the file is
  the arrangement rather than the physics — the ring below is 77 kB citing an 11 MB pack.
* **Partition** cuts **one walk** of a substrate larger than a voxel (a DiSCo strand phantom, a whole mesh) into the
  voxels each walker started in. The grid is free — coarsen, refine, shift, no re-walk — and the fractions are
  measured, not declared.

Both are a `Phantom`, replayed the same way, and composition is the voxel-averaged projection of a partition.

![circular white-matter phantom](examples/rph/circular_wm.gif)

A CACTUS bundle of 366 tortuous strands, walked once, arranged as an annulus of tangentially oriented fibres
around a free-water core with inert background outside. **Left**: the substrate the walk saw, and the poses the
phantom replays — a tight cone around most of the ring, and one sector where the population fans out
anisotropically. **Middle and right**: a diffusion-weighted acquisition at 7 T. First the gradient turns through
360° with the field pointing north, giving the diffusion contrast everyone knows. Then the gradient is held fixed
through the plane and **B0** turns instead: what still moves is the susceptibility, the myelin field each walker
samples depending on the angle between the field and the fibre.

### Composition

```python
import numpy as np
from dmipy_replay import sequences
from dmipy_replay.phantom import Fan, FreeWater, Grid, Inert, PackSubstrate, Phantom
from dmipy_replay.spec.tissue import Tissue

n = 40
grid = Grid(shape=(n, n, 1), voxel_size_m=(1.5e-3,) * 3)          # centred on the isocenter unless origin_m= says otherwise
f_wm, f_csf = annulus(n)                                            # volume fractions on the grid (examples/rph/circular_wm_phantom.py)
R, kappa = frames(n)                                                # a rotation per voxel: the fibre axis and the fan plane

wm = PackSubstrate("cactus.rpk", m0=0.75, tissue=Tissue(chi_iso=-1e-7))   # m0 is required: proton density is relative; the tissue is the substrate's
ph = Phantom.compose(grid,
                     fractions={wm: f_wm, FreeWater(m0=1.0, tissue=Tissue(D=3e-9)): f_csf},
                     remainder=Inert(),                             # a voxel is always full: no unmodelled slack
                     orientation={wm: Fan(R, kappa=kappa)})
ph.write("wm.rph", id="phantoms/circular-wm", license="CC-BY-4.0", citation="...")   # provenance only when publishing

seq = sequences.pgse(dirs, 0.006, 0.015, bvalues=[1.5e9] * len(dirs), TE=0.030)
S = ph.replay(seq, scanner=7.0)                                   # (n, n, 1, n_dirs), NaN where the phantom has no voxel
```

Every piece is an object with named, unit-bearing arguments, and the phantom is keyed by those objects:

| piece | what it is |
|---|---|
| `PackSubstrate(pack_or_path, *, m0, tissue=)` | a solved pack; its `Tissue` (`pack.nominal`, or `Tissue(T2={...by pool name}, rho2=, chi_iso=)`) is what it replays at, none for the bare diffusion signal |
| `FreeWater(*, m0, tissue=Tissue(D=, T2=, T1=))` | the one closed form: a pack cannot stand in for free water (its Monte-Carlo floor does not decay with b) |
| `Inert()` | fills a voxel and emits nothing, so it has no `m0`; not air |
| `Peaks(directions, weights=)`, `ODF(coeffs, *, basis)`, `Watson(*, mu, kappa)`, `Frames(rotations)`, `Fan(rotations, *, kappa)` / `Fan.from_axis(*, axis, fan_towards, kappa_fan, kappa_perp)` | a pose per voxel, from a direction to a whole rotation; `ODF` names its **source** basis (`"mrtrix3"`, `"mrtrix-legacy"`, `"dmipy-fit"`, ...), keeps a CSD's integral on `.integral` |
| `Grid(*, shape, voxel_size_m, origin_m=, isocenter_m=, axes=)`, `Grid.from_affine(nifti_affine, shape)`, `Grid.from_oblique_affine(nifti_affine, shape)` | the voxels in the scanner, each where the image's affine puts it (`axes` signs every index: `"LAS"` runs i along -x) |

`fractions=` also takes an integer label volume with `labels={value: substrate}`; `remainder=` takes `1 - sum`
where the fractions leave a gap. `m0` is required on every signal-bearing substrate, because a proton density
of 1 only means "the reference the others are stated against". The replayed signal is `sum_p f_p m0_p E_p`.

**A pose is a rotation, not an axis.** `Peaks` and `ODF` state a direction and leave the substrate's own azimuth
unstated, which the replay integrates away; `Frames` states the whole rotation; `Fan` a frame with a
concentration about each of its first two axes, a population dispersed anisotropically. Each cited pack is
expanded once into its response over SO(3), and every voxel is an inner product with its own distribution.

**Maps at replay time.** `ph.replay(seq, transmit=kappa_map)` scales every flip angle per voxel and goes through
the RF-aware route (one propagation per distinct pose; frames mode); `off_resonance=dB0_map` (T) is a uniform
precession through the acquisition's own coherence gate; `proton_density=pd_map` scales every slot's `m0`. Each
is a scalar, a volume of the grid, or a callable of scanner coordinates, and composes with the same layer baked
into the file. A layer the replay cannot carry raises rather than being dropped.

### Partition

```python
from dmipy_replay import Prescription
from dmipy_replay.phantom import Grid, Inert, FreeWater, PackSubstrate, Phantom, Pose

pack = PackSubstrate("disco.rpk", m0=1.0)                           # ONE walk of a 1 mm^3 anatomy, spin_weights carried
ph = Phantom.partition(pack, Grid(shape=(40, 40, 40), voxel_size_m=(25e-6,) * 3, attach="substrate"),
                       declared={Inert(name="myelin"): f_myelin},   # the walker-less slot declares its fraction
                       outside=FreeWater(m0=1.0, tissue=Tissue(D=0.6e-9)))    # voxels the walk did not seed

ph50 = ph.regrid(voxel_size_m=(50e-6,) * 3)                         # exact rebin of r(0): no re-walk, no re-encode
ph_r = ph.with_pose(Pose(rotation))                                 # attach="substrate": physics only; "lab": walkers rebinned
S = ph.replay(seq, transmit=kappa_map)                              # per-walker B1 through one propagation of the walk

scanner = Phantom.partition(pack, outside=Inert())                  # no grid: the scanner decides the voxels
S = scanner.replay(seq.with_prescription(Prescription(voxel_size_m=(50e-6,) * 3, matrix=(20, 20, 20))))
```

Membership is derived from the pack's stored start positions (`ReplayPack.r0`, exact at any `K`), never stored;
a pack slot's fraction is emergent from the walkers' weights, `(1 - declared) · W_p / ΣW`, so weighted counts
*are* the fractions at any grid and any pose. The anatomy rotates as a block: `Grid.attach` says whether the grid
follows the tissue (a pose changes the physics only, membership is invariant) or is the bore's (the posed starts
are rebinned). A `ScannerSequence` can carry a `Prescription` — isocenter, axes, voxel size, matrix — and a
partition with no grid of its own bins on it. Every pack is replayed once per acquisition whatever the voxel
count; a walker's signal belongs to the voxel it **started** in.

## Substrates

All lengths in metres, diffusivities in m²/s, times in seconds. Compartment ids are the same
everywhere: 0 extra-cellular, 1 intra (the lumen / inside a closed surface), 2 myelin.

| family | classes |
|---|---|
| analytic | `FreeDiffusion`, `Box1D`, `Sphere`, `Cylinder`, `Ellipsoid`, `PermeableSlab1D`, `PermeableShell` |
| packed, periodic | `PackedCylinders`, `PackedSpheres`, `PackedMyelinatedCylinders` (+ `pack_*` RSA packers) |
| myelinated | `MyelinatedCylinder`, `PackedMyelinatedCylinders` — three pools, two walls |
| curved fibres | `CurvedCylinder`, `CurvedMyelinatedCylinder`, `PackedCurvedCylinders` — sphere-swept polylines |
| meshes | `Mesh` / `Mesh.from_ply` — any closed or 3-D-periodic triangle mesh, grid-accelerated |
| sphere-grown cells | `SphereUnion` — the outer boundary of a union of overlapping spheres (CATERPillar), no meshing |
| segmented images | `LabelVolume` — a label grid, where the wall is every face between voxels of different pools; no isosurface, and the Manhattan surface of the segmentation is what relaxes |

Datasets enter as **specs**: `spec.cactus_spec(run_dir)`, `spec.winther_spec(inner, outer)`,
`spec.caterpillar_spec(csv)`, `spec.label_volume_spec(image)` (a segmented micro-CT / EM / mask volume in NRRD,
MetaImage, NIfTI, TIFF or HDF5), `spec.strands_spec(txt)` / `spec.disco_spec(tracks, diameters)` (the MRtrix track file and the strand-diameter list) read the files and write down
domain, pools, walls and seeding; `walk(spec, ...)` walks them pool by pool and the pack embeds the spec.
The envelope gives the band, the band gives the block: `walk` accumulates the band of its envelope
(`envelope=envelope_of("prisma" | "magnus" | "connectom" | ...)`, the class's certified band times the storage margin,
or an `Envelope` stated directly), `K` sine bands per 100 ms storage window, in blocks of
`h = 0.8 T / (pi K)`, while the walk runs -- the positions, the wall contact and the field as band projections of
their running integrals, the occupancy as events exact in time -- so the walk's memory and the pack's size are set
by `K`, never by the walk's length or resolution, and the pack certifies itself without a raw path (the block
quadrature, the field read, the truncation and the rounding are closed-form terms of `fidelity.terms`).

Wall and pool properties are set on the geometry and baked into the walk:

```python
Cylinder(5e-6, (0, 0, 1), surface_relaxivity_t2=1e-6)      # rho (m/s), Brownstein–Tarr at the wall
Cylinder(5e-6, (0, 0, 1), permeability=2e-5)               # kappa (m/s), Powles crossing
Mesh(V, F, pool="extra", compartments=Compartments(extra=Pool(T2=0.08, D=1.7e-9),
                                                   intra=Pool(T2=0.05, D=1.7e-9)))
```

`Compartments` is the one spelling of per-pool D / T2 / T1 / water fraction / side-dependent rho, for
every geometry and for `Substrate`. A `Mesh` also declares which pool a driver seeds (`pool=`) and is
placed in the bore by an acquisition rotation (`orientation=`), so the walk stays in the mesh frame.

### Meshes

```python
from dmipy_sim import Mesh
mesh = Mesh.from_ply("substrate.ply", scale=1e-5, periodic=True,
                     voxel_min=[-10e-6] * 3, voxel_max=[10e-6] * 3, feature_radius=1.7e-6)
mesh.quality_report()          # per-effect resolution verdict; permeability needs edge/feature <~ 0.04
```

Per step a walker tests only the triangles in its 27-cell neighbourhood, so a 10⁶-triangle mesh is
tractable. Reflection uses smooth vertex normals; permeation is one Powles decision at the first hit
and then a multi-bounce reflection; the voxel faces are periodic wrap planes or specular walls, never
teleports. Loading needs `pip install "dmipy-sim[mesh]"`.

## Acquisitions

A `ScannerSequence` is the one acquisition object: what the scanner does from t = 0 to the readout --
the physical gradient `G(t)` of shape `(n_measurements, n_t, 3)` on a `dt` grid, the RF schedule `rf`,
the `readout`, a timing budget and the per-measurement `Encoding`. One builder per family -- `pgse`,
`pgste` (the stimulated echo), `ogse` (trapezoid or cosine trains), `cpmg`, `gre`, `ste`, `pte` -- takes the
directions and either `bvalues=` (the exact b to realise) or `gradient_strengths=` (the amplitude to play),
the family's parameters, an optional `TE=`, `slew_rate=` and a `timing=` budget, and refuses what cannot be
played. Everything else is derived from `G` and `rf`, never carried as a flag: the effective gradient
`G_eff`, `chi_perp`, `TM`, `stimulated_echo`, the `echoes`, `b()`.
B-tensor encoding (LTE / PTE / STE) and multi-echo CPMG are included. The vector-Bloch replay
(`ReplayPack.replay_bloch`) propagates M = (Mx, My, Mz) through the actual RF, gradient, relaxation, exchange
and MT operators when the transverse-only picture is not enough; the single-pass vector-Bloch walk it is held
to is an internal oracle (`engine/bloch.py`).

## Physics is the specification

Correctness is defined by the test suite: analytical solutions, eigenfunction series, Brownstein–Tarr
relations, exchange laws and MISST reference signals. Every parameter the engine tunes for speed
(bounce budgets, sub-steps, grid cells) is derived from the most adversarial situation a walker can
meet in that substrate, not validated on an average case.

## Layout

The reader side -- the acquisition object and its builders, the Pulseq and b-table readers, the one `ReplayPack` and
every route that turns a pack into a signal or an image (the replay, the plan before a read, the vector-Bloch
propagator, the pose expansion, the study, the RF train as gates, the columnar and time-segment layouts' images, the
replay phantoms), the Hub client -- is [dmipy-replay](https://github.com/dmrai-lab/dmipy-replay) (its core numpy only,
Apache-2.0), a dependency: dmipy-sim imports it and re-exports none of its names (`dmipy_sim.pgse` is refused, naming
`dmipy_replay.pgse`). dmipy-sim is the producer: the walk, the encoding and the certificate, the packs and layouts it
writes, the operations that re-encode a pack (`dmipy_sim.replay.reencode`), publishing.

```
dmipy_sim/
  geometry/     substrates: base, analytic, packed, myelin, packing, curved_cylinder, mesh, mesh_shapes
  engine/       core (simulate, _walk_geometry), accumulate, physics, pulse_sequence, mt, mt_walk, gpu;
                _fused and bloch: the single-pass oracles the replay is held to
  replay/       bank (build_replay_pack), compression (the codec), container (write_rpk, save_pack), reencode
                (truncate_pack, rewindow_pack, prefix_pack, stated_envelope, restate_surface_envelope), continuation
                (end_state, extend_pack), trajectories (the dense oracle), time_segments (writes the layout),
                consolidate (shards -> the columnar layout), publish, hub (the dataset repository behind publish),
                reference (the reference-pack protocol)
  acquisition/  noise, coil (ScannerSequence, RFSchedule, ScannerLimits and the integrals are dmipy-replay's)
  sequences/    pulseq (export; the reader is dmipy-replay's)
  fields/       susceptibility, susceptibility_field (FieldGrid, field_grid_of)
  substrate/    Substrate (calibrated white matter), biophysical constants
  compartments.py  coefficient_walk.py   viz/  io/  math/
```

`CLAUDE.md` is the operational guide for agents and contributors: the geometry contract, the step
rules, the replay invariant, and how to add physics. `docs/replay-guide/` is the user's manual for the replay side.

## Examples

- **[Canonical white matter](examples/canonical_wm_flagship.ipynb)** — the calibrated packed-myelinated
  substrate, forward signal with surface relaxivity, parity with dmipy-fit's analytical model.
- **[Mesh loading and visualisation](examples/mesh_ply_and_viz.ipynb)** — build or load a mesh, run
  diffusion, relaxivity and permeability, select permeated walkers, render the viewer.
- **[Validation ladders](examples/validation/)** — surface relaxivity and permeability from 1-D to 3-D,
  and [the Imperial micro-CT rocks](examples/validation/talabi_micro_ct_rocks.py) against Talabi 2008's
  random-walk NMR on the same voxels
  against exact eigenvalues; extra-axonal tortuosity scale sweep.
- **[Substrate bank](examples/substrate_bank/)** — building canonical-pore packs with a fidelity target.
- **[Circular white-matter phantom](examples/rph/circular_wm_phantom.py)** — one CACTUS pack composed into a
  replay phantom with a fanned sector, swept over gradient and field direction; writes the animation above.
- **[A brain from an MRtrix CSD result](examples/rph/brain_from_csd.py)** — the B.A.T.M.A.N. tutorial subject's own
  CSD FOD and five-tissue segmentation composed into a whole-brain phantom on the image's grid, replayed on the
  tutorial's multi-shell table, written back as a DWI; `brain_from_csd_check.py` deconvolves it and recovers the FOD.

## Install

```bash
pip install dmipy-sim                 # CPU, any platform (installs dmipy-replay)
pip install "dmipy-sim[cuda12]"       # NVIDIA GPU, CUDA 12
```

From a checkout:

```bash
pip install -e ".[dev]" && pip install "jax[cpu]>=0.6.2"     # CPU, any platform (installs dmipy-replay)
pip install -e ".[cuda12,dev]"                                # NVIDIA GPU, CUDA 12
```

On a GPU box, point the loader at the bundled CUDA libraries once in your venv's `activate`:

```bash
export LD_LIBRARY_PATH=$(find "$VIRTUAL_ENV/lib"/python*/site-packages/nvidia -name lib -type d | tr '\n' ':')$LD_LIBRARY_PATH
```

Large runs belong on the GPU in float32; `simulate` warns on a large CPU run unless `require_gpu=False`.

## Tests

```bash
JAX_PLATFORMS=cpu pytest tests/ -q -m "not slow and not gpu"   # fast tier: every PR (~7 min on a GPU)
pytest -q -m slow                                              # heavy statistical MC validation
```

`tests/geometry/` mirrors the geometry package; `tests/physics/` and `tests/validation/` assert
physics across modules.

## License

Dual-licensed: **GNU AGPL-3.0** for open-source use, or a **commercial license** for proprietary use.
See [LICENSE](LICENSE) and [LICENSING.md](LICENSING.md).
