Python API#

Running MPAT#

mpat.run(afq, n_proc, max_mem='auto', bundles=None, moments=False, tol=1e-06, angle=35.0, double_odf=True, cores=True, viz=True, synthseg_thalamus=True, max_length=250.0, viz_rois=False, no_midline=(), midline_tol=None, out_dir=None, verbose=False, fornix=True, flux=False, fixels=False, viz_colormap=None, ptt=False, step=1.0, stop_mass=None, fod_thresh=None, fod_power=None, curv_sigma=None, probe_radius=None, sift2=False, arbor=False, arbor_branches=5, save_transitions=False)[source]#

Segment pyAFQ’s bundles with MPAT.

afq         ``ParticipantAFQ`` or ``GroupAFQ`` (every participant in turn)
n_proc      threads
max_mem     memory budget, bytes, e.g. "16GB", or "auto" (default): sets how many bundles
            share each solve.  "auto" reads the job's limit (cgroup / SLURM / physical),
            keeps min(80%, limit - 10 GB) of it and subtracts what is already held
bundles     pyAFQ bundle names (default: all in the bundle dictionary)
moments     spatial first moments (narrower, more accurate bundles; ~5x slower)
tol         remaining walker mass at which the solves stop (relative)
angle       maximum turn per one-voxel hop (degrees)
double_odf  weight each hop by the fODF where it lands (False: singleODF, like pyAFQ's
            first-order probabilistic tracker)
cores       also write each bundle's ridge-path core (mpat.core)
viz         also write a MIP collage of all bundles (PNG), a viewer page of all bundles
            (densities and cores; both of every bundle in the output folder, so a run of
            some bundles keeps the others), and one page per bundle with its visitation-ODF glyphs
            and the fODF (mpat.viewer.save_html).  Pages load NiiVue from a CDN.
viz_rois    the viewer pages also show each bundle's include / exclude ROIs
viz_colormap  NiiVue colour map of the density on the per-bundle viewer pages (default
            actc; e.g. "turbo", "hot"), the all-bundles page included ("bundle": one hue per bundle)
no_midline  bundle names whose cross_midline=False is ignored (no other-hemisphere exclusion)
midline_tol mm past the midline the corticospinal tracts may go before the other hemisphere

is excluded (default: their rule, 10; 0: a strict cut); every other one-sided bundle follows its own rule (mpat.bundles; default a strict cut at x = 0)

max_length  soft maximum streamline length (mm; 0: none).  Before any bundle is solved,
            direction states from which most walkers would still be walking after this
            long -- traps where they circle, unable to turn out under the angle limit --
            become invalid ends for every bundle (mpat.solve.overlength_states); the
            survival per voxel is written to <stem>_desc-overlength_map.nii.gz
out_dir     write MPAT's outputs here instead of <pyAFQ output_dir>/mpat (mpat-moments);
            pyAFQ's derivatives are only read.  For a GroupAFQ: <out_dir>/sub-<s>/ses-<t>
fornix      the anterior thalamic radiations exclude the fornix / septum on the midline
            (FORNIX_BOX_MNI; False: as pyAFQ defines them)
verbose     log timing inside the solves (ms per power step: matrix product / mask and
            sum); the time per stage is logged at the end anyway
synthseg_thalamus  with pyAFQ's SynthSeg tissue (pve unset or "synthseg"), a template start / end
            ROI that is the thalamus is replaced by SynthSeg's thalamus (see bundle_specs)
flux        also write each bundle's edge flux (mpat.fields): the expected streamline steps
            from every voxel into each of its 26 neighbours, and the flux through each
            voxel.  Not with moments.  The fields themselves are not kept here; use
            ``segment_bundles(keep_fields=True)`` to work with them.
fixels      also write an MRtrix fixel directory, <stem>_desc-mpat_fixels/ (mpat.fixels):
            the subject's fixels from the fODF, and per fixel each bundle's expected
            streamlines through it (<bundle>_streamlines), the streamlines of the
            unconditioned chain (all_streamlines: every walk from every seed, no ROIs, one
            extra solve), the bundle's share of them (<bundle>_share) and its share of the
            solved bundles' streamlines (<bundle>_share_of_bundles).  For fixel-based
            analysis without tractography.
ptt         use Parallel Transport Tractography (PTT) defaults (fod_thresh=0.08,
            fod_power=1.5, curv_sigma=18.0, probe_radius=0.5, stop_mass=1e-4) unless
            explicitly overridden.
step        hop length in voxels (of the smallest voxel side; default 1.0).
stop_mass   MITTENS stopping regularizer tau (default 1e-4 if ptt else 0.0).
fod_thresh  relative fODF floor (default 0.08 if ptt else 0.05).
fod_power   fODF sharpening exponent p (default 1.5 if ptt else 1.0).
curv_sigma  PTT parallel-transport curvature & co-circularity sigma in degrees (default
            18.0 if ptt else 0.0; 0 = flat cone).
probe_radius  PTT cylindrical probe radius in voxels (default 0.5 if ptt else 0.0).
sift2       calibrate seed launch weights globally with path-consistent SIFT2
            (mpat.quantify.sift2_optimize_launches) before bundle segmentation.
arbor       also extract and write 3-D multi-branch cross-section ridge arbors
            (<stem>_bundle-<Name>_desc-arbor.{trx,json,tsv}) for each bundle.
arbor_branches  maximum cortical endpoint branches per side for arbor extraction (default 5).
save_transitions  persist transition probabilities: False/None (default), "odx" (or True)
            for <stem>_desc-transitions_dwimap.odx, "nifti" for 4-D NIfTI + codi/coasy maps,
            or "both".

Returns {bundle: BundleResult} (a dict per participant for a GroupAFQ).

mpat.view(*args, **kwargs)[source]#

ipyniivue widget with bundle densities and cores (see mpat.viewer.view).

mpat.save_html(path, folder, title=None, niivue_js=None, **kwargs)[source]#

A standalone web page with the same scene as view (kwargs: scene’s options), with controls for the layout, each bundle’s density / core / glyphs, and the

opacities.  The data are embedded.  NiiVue loads from a CDN, or from ``niivue_js``, a

local niivue.umd.js (npm package @niivue/niivue, dist/) embedded too, so the page

works offline.  Returns the path.

The chain and the solves#

class mpat.ChainConfig(angle: 'float' = 35.0, step: 'float' = 1.0, double_odf: 'bool' = True, moments: 'bool' = False, moment_closure: 'str' = 'standard', stop_mass: 'float' = 0.0, fod_thresh: 'float' = 0.05, fod_power: 'float' = 1.0, curv_sigma: 'float' = 0.0, probe_radius: 'float' = 0.0, chunk: 'int' = 256)[source]#

Bases: object

angle = 35.0#
step = 1.0#
double_odf = True#
moments = False#
moment_closure = 'standard'#
stop_mass = 0.0#
fod_thresh = 0.05#
fod_power = 1.0#
curv_sigma = 0.0#
probe_radius = 0.0#
chunk = 256#
classmethod ptt(angle=35.0, fod_thresh=0.08, fod_power=1.5, curv_sigma=18.0, probe_radius=0.5, stop_mass=0.0001, **kw)[source]#

Parallel-Transport Tractography (PTT / Trekker-informed) Markov chain configuration.

key()[source]#
class mpat.Chain[source]#

Bases: object

ncomp = 1#
classmethod build(sh, zooms, transient, absorb_class, cfg=ChainConfig(angle=35.0, step=1.0, double_odf=True, moments=False, moment_closure='standard', stop_mass=0.0, fod_thresh=0.05, fod_power=1.0, curv_sigma=0.0, probe_radius=0.0, chunk=256), cache=None)[source]#
sh            (X, Y, Z, C) SH coefficients (DIPY descoteaux07; symmetric or full basis)
zooms         voxel sizes (mm)
transient     (X, Y, Z) bool: white matter, where walkers move
absorb_class  (X, Y, Z) int: 0 outside, 1 GM, 2 CSF, 3 brain edge (where not transient).
              GM and edge absorb walkers; CSF has zero transition probability (walkers
              never step there; their other hops are renormalised)
cache         optional .npz: transitions are loaded from it when inputs and config
              match, else built and saved there
save_odx(path, affine=None, **kwargs)[source]#

Persist this chain’s transitions, fixel lobes and per-voxel metrics to an .odx archive.

classmethod load_odx(path, return_extras=False)[source]#

Load a Chain directly from an .odx archive without needing the fODF NIfTI.

save_nifti(prefix, affine=None)[source]#

Write 4-D (X, Y, Z, 26) voxel-to-neighbour transition NIfTI + codi/coasy maps.

classmethod from_nifti(nifti_path_or_prefix, absorb_class=None)[source]#

Build a 26-class Chain from a 4-D (X, Y, Z, 26) transition NIfTI.

lin(ijk)[source]#
seed_peaks(vlin)[source]#

fODF peak vertices of a (padded, linear) voxel; empty if it has no fODF.

launch_halves(seed_vlin, dptr, dirs, out, dead)[source]#

First exits of half-walks; out (H, 26, nb, ncomp).

release_pmfs()[source]#

The bundle solves need only the transitions; on large grids the fODFs are big.

mul_forward(x, out)[source]#

out = Q^T x (walker mass one step on).

mul_backward(x, out)[source]#

out = Q x (completion probabilities one step back).

absorb_rhs(absw)[source]#

(n_states, C): probability of being absorbed next step into voxels weighted by absw.

absorbed_from(S)[source]#

(Na, C) absorbed mass from summed occupancy S.

to_volume(values, which='transient')[source]#
mpat.prepare_launches(chain, seeds, chunk=4096)[source]#

One streamline per seed voxel, split over its fODF peak pairs {p, -p}.

mpat.segment_bundles(chain, specs, launches, tol=1e-06, max_mem=8000000000.0, max_iter=5000, valid_classes=(1, 3), on_result=None, on_trapped=None, verbose=False, clock=None, keep_fields=False, accel=False, arc_length=False, zooms=None, on_step=None)[source]#
Segment bundles, sharing solves.  ``specs``: dicts with ``name`` and optional

include (list of masks), exclude, start, end (boolean volumes on the chain

grid).  Bundles are packed in order into groups whose columns fit in ``max_mem`` bytes;

each group costs one backward and one forward series. on_trapped(direction, names, volume): called when a solve stalls or runs out of steps, with the mass it could not finish per voxel (relative to the largest column’s start). verbose: timing inside the solves. clock: a Clock to add the time per stage to (default: a new one, reported at the end). keep_fields: also keep each bundle’s solution columns (occupancy, completion and launch mass per state) as result.fields (mpat.fields.BundleFields), for edge flux,

committors and conservation checks.  Three more float64 arrays of n_states x columns per

bundle; the plain chain only (not with spatial moments). accel: False (default), True / “mr” (Periodic Minimal Residual), or “aitken”. arc_length: weight class visits by physical intra-voxel chord lengths (in mm if zooms is provided, else in voxels). on_step(step): called with a SolveStep after every backward and forward iteration (e.g. to stream the solve as it converges). Returns {name: BundleResult}.

class mpat.solve.BundleResult(name: 'str', seed_vox: 'np.ndarray', seed_prob: 'np.ndarray', density_t: 'np.ndarray', endpoints_a: 'np.ndarray', info: 'dict' = <factory>, density_class: 'np.ndarray' = None, fields: 'object' = None, flux26: 'np.ndarray' = None, start_mask: 'np.ndarray' = None, end_mask: 'np.ndarray' = None)[source]#

Bases: object

name#
seed_vox#
seed_prob#
density_t#
endpoints_a#
info#
density_class = None#
fields = None#
flux26 = None#
start_mask = None#
end_mask = None#
class mpat.solve.Launches(seeds, seed_lin, pair_seed, pair_w, pair_d, hseed, lptr, lkey, lval, dead)[source]#

Bases: object

First exits of every half-walk of every seed (independent of the bundle).

seeds#
seed_lin#
pair_seed#
pair_w#
pair_d#
hseed#
lptr#
lkey#
lval#
dead#
property nbytes#
mpat.solve.solve_series(mul, x0, mask, tol, max_iter, what, ncomp=1, verbose=False, accel=False, krylov=True, on_step=None)[source]#

total = sum_t (M A)^t x0 per column (M = diag(mask)), A x = mul(x, out), by power iteration until the remaining mass (mass rows, relative to the largest column’s start) is below tol. Stops early when it stalls (mass circulating in states that almost never get absorbed) and reports where that mass sits as info["trapped"]. x0 is consumed. verbose: log the time per step (matrix product / masking and summing) every 100 steps. accel: False (default), True / “mr” (invariant-preserving Periodic Minimal Residual extrapolation), or “aitken” (scalar Aitken delta-squared extrapolation). on_step: optional callback on_step(it, res, total, term) invoked after each iteration (term: that iteration’s term of the series, i.e. the current wavefront). Returns (total, info).

Geometry#

mpat.geometry.build_geometry(zooms, angle_max=35.0, step_vox=1.0, curv_sigma=0.0)[source]#

Paths for hops of step_vox voxels (of the smallest voxel side) turning less than angle_max degrees, on DSI Studio’s 642-direction sphere; anisotropic voxels are exact.

mpat.geometry.pmf_and_cone_mass(sh_rows, geo, chunk=20000, fod_thresh=0.05, fod_power=1.0, cyl_nbr=None, probe_radius=0.0)[source]#

X: fODF on the sphere, clipped at 0, values below fod_thresh x max zeroed, raised to fod_power (PTT dataSupportExponent), normalised to sum 1 per voxel; Y: X summed over each cone (weighted by geo.cone_w).

mpat.geometry.visitation_odf(density_class, sh_rows, geo, sh_order=8, chunk=20000)[source]#

A bundle’s visitation ODF: the directions its walkers travel in each voxel, as SH coefficients in the fODF’s basis (DIPY descoteaux07, legacy, symmetric).

density_class (n, 26): expected visits by direction class, per voxel; sh_rows (n, ncoef):

the fODF there.  Within a class the direction is spread as the chain assumes,

q ~ X Y (kernel.class_q; vertex_visits). The ODF is antipodally symmetrised and in expected visits per steradian, so it integrates to the voxel’s density (c_00 = density / (2 sqrt(pi))).

Cores#

mpat.bundle_core(density, affine, endpoints, start=None, end=None, n_nodes=100, floor=1e-06, body=0.01, smooth=1.5, anchor='centroid', include=None)[source]#

Cross-section ridge path of one bundle (see module docstring).

density, endpoints  3-D arrays on the same grid (MPAT ``density_map``, ``endpoints_map``)
start, end          optional boolean endpoint ROIs (MPAT ``start_mask``, ``end_mask``)
include             optional include ROIs labelled 1, 2, ... in pyAFQ's order (MPAT ``include_mask``)
floor               voxels with density below floor x peak are left out of the graph
body                anchors are placed on voxels with density >= body x peak
anchor              "centroid" (default) or "mode": where in each end's endpoints to anchor
mpat.core.write_cores(folder, n_nodes=100, anchor='centroid')[source]#

Compute and save the core of every bundle under folder (MPAT outputs).

pyAFQ integration#

mpat.afq.tissue_labels(sh_img, pve_img, brain_mask_img=None)[source]#

As pyAFQ’s tracker: walkers move where WM PVE > 0.4 inside the fODF mask; the mask’s inner boundary counts as grey matter (“edge”, so fibres leaving the field end validly); other in-mask voxels are GM (GM PVE >= CSF PVE), which absorbs walkers, or CSF, which

walkers never enter (zero transition probability).  White matter that cannot reach any

ending – a pocket walled in by CSF and the edge of the fODF field (in a tumour, say) – would trap walkers seeded in it forever and stall the solves: it is taken out of the walk (treated as CSF, never entered), labelled 5 in dseg, and logged. Returns transient, absorbing class (0 outside, 1 GM, 2 CSF, 3 edge), dseg (1 WM, 2 GM, 3 CSF, 4 edge, 5 isolated WM).

mpat.afq.bundle_specs(afq, ref_img, transient, names=None, thalamus=None, no_midline=(), midline_tol=None, fornix=True)[source]#

bundle_specs_iter as a list (every bundle’s ROIs at once).

mpat.afq.seal_26(mask)[source]#
Make a thin ROI impassable for 26-connected walks.  Streamlines cannot slip through a

one-voxel sheet; walkers stepping diagonally can. Adding the sheet’s 6-neighbours closes those gaps.

Spatial moments#

Spatial first moments: the chain also carries each state’s mean sub-voxel position.

The default chain restarts every voxel’s paths from a uniform position, which makes

bundles several times too wide.  Here a state carries (M, Q) with Q = M x the mean position

(voxel units, from the centre), and the within-voxel density is reconstructed linearly, rho(y) = 1 + 12 Q.y / M (Prather 1986). Every MITTENS path has an axis-aligned box of start points (centre c, widths w) and lands at l in the next voxel, so per path exactly

mass        = vol (1 + 12 c.x)
landing Q   = vol (l + (12 l c^T + diag(w^2)) x),    x = Q / M.

The closure is linear, so the chain stays linear (adjoints, inclusion-exclusion and the forward-backward products are unchanged), but it is not positivity-preserving: masses can go

slightly negative, and a few loops of states can amplify.  ``stabilize`` finds such loops

and falls back to the uniform closure there.

mpat.moments.stabilize(chain, max_rate=0.95, iters=150, max_rounds=12, cover=0.99, seed=0)[source]#

Find loops of states where the moment closure amplifies (the operator decays slower than max_rate per step and slower than its mass channel alone) and drop the moment inputs of the voxels carrying cover of that mode (uniform closure there). Repeats until fine.