larmor.tractography#

Tractography: seeds, stopping rules, the tracker, and working with tractograms.

EditOptions

The selections and edits of one whole edit, for edit and edit_files.

EndStatus

Status of a given streamline.

MaskSeeds

Class for seeding from a mask.

Region

A sphere, or a 3D mask Volume on any grid (or 4D with one volume).

Seeds

The seeds of a tracking: where each streamline starts, and optionally how.

SeedStrategy

Seeding strategy protocol.

Sphere

A sphere in world coordinates.

TractographyRun

Results of a tractography run.

Tracker

Tracks streamlines through a field of FODs.

TractProfile

The profile of a bundle: one value per map at each of its points.

Weighting

How the streamlines' values at one profile point are averaged.

build_connectome

Builds a connectome matrix from the regions of the streamlines' endpoints.

concatenate_tractograms

Joins tractograms into one, their streamlines one after the other.

crop

Cuts the streamlines to the parts inside (or outside) the regions.

density_grid

A grid of smaller (or larger) voxels over the field of view of a reference grid.

edit

Runs a whole edit: selection, cropping, counting and resampling.

edit_files

Edits tractogram files into one output file, as edit does in memory.

endpoint_nodes

Assigns the two endpoints of every streamline to regions of a parcellation.

load_region

Reads a region given as text: a sphere x,y,z,r or the path of a mask image.

node_names

The names of the nodes of a connectome built on a parcellation.

parcellation_labels

The labels of a parcellation as an (X, Y, Z) int64 array, 0 for no region.

passes_in_order

Tests which streamlines pass through the regions in the given order.

passes_through

Tests which streamlines pass through a region.

points_inside

Tests which points lie inside a region.

read_seeds

Reads seeds written by write_seeds.

resample

Resamples every streamline to a step size or to a number of points.

sample_volume

Samples an image at every point of a tractogram, with trilinear interpolation.

write_connectome

Writes a connectome matrix as text, with the region names.

write_node_assignments

Writes the regions of each streamline's endpoints, one streamline per line.

seeds_per_voxel

Draws n seeds per voxel from the given mask.

select_length

Selects the streamlines whose length is within limits.

select_weight

Selects the streamlines whose weight is within limits.

stays_within

Tests which streamlines stay within a region.

streamline_lengths

Returns the length of each streamline.

track_density

Counts the streamlines that pass through each voxel of a grid.

tract_profile

Computes the profile of maps (FA, MD, ...) along a bundle.

write_seeds

Writes seeds as text, one row per seed, for read_seeds.

class larmor.tractography.EditOptions(min_length=None, max_length=None, min_weight=None, max_weight=None, include=(), include_ordered=(), exclude=(), within=(), ends_only=False, inverse=False, mask=(), skip=None, every=None, number=None, subsample=None, seed=None, step_size=None, num_points=None)#

The selections and edits of one whole edit, for edit and edit_files.

Every field defaults to “not given”: None, False or no regions. The regions may be given as any sequence and are stored as tuples; each is a Sphere, a mask Volume, or text that load_region reads (x,y,z,r or a mask image’s path), which edit_files reads after its checks. edit says in which order the options apply.

Parameters:
  • min_length (float | None) – The shortest length kept, in mm (inclusive).

  • max_length (float | None) – The longest length kept, in mm (inclusive).

  • min_weight (float | None) – The smallest weight kept (inclusive); needs streamline_data["weight"].

  • max_weight (float | None) – The largest weight kept (inclusive).

  • include (Sequence[Region | str | Path]) – Regions every kept streamline passes through.

  • include_ordered (Sequence[Region | str | Path]) – Regions every kept streamline passes through in this order, see passes_in_order.

  • exclude (Sequence[Region | str | Path]) – Regions no kept streamline passes through.

  • within (Sequence[Region | str | Path]) – Regions every kept streamline stays within, see stays_within.

  • ends_only (bool) – Test only the two endpoints against include, include_ordered, exclude and within.

  • inverse (bool) – Keep the streamlines that fail at least one of the length, weight and region tests, and crop to the parts outside mask.

  • mask (Sequence[Region | str | Path]) – Crop the streamlines to the parts inside these regions.

  • skip (int | None) – Drop the first skip selected streamlines.

  • every (int | None) – Keep every every-th selected streamline, starting with the first.

  • number (int | None) – Keep the first number selected streamlines.

  • subsample (int | None) – Keep subsample selected streamlines chosen at random.

  • seed (int | None) – Seed of the random choice of subsample.

  • step_size (float | None) – Resample the result to this step size, in mm.

  • num_points (int | None) – Resample the result to this many points per streamline.

Raises:

ValueError – If both number and subsample are given, or both step_size and num_points; if step_size <= 0, num_points < 2, a minimum is above its maximum or a limit is NaN, every < 1, skip, number or subsample is negative, seed is given without subsample, or ends_only is given with no include, ordered, exclude or within region or with more than two ordered regions.

class larmor.tractography.EndStatus#

Status of a given streamline.

NONE = 0#
MAX_LENGTH = 1#
LEFT_VOLUME = 2#
LEFT_MASK = 3#
LOW_FOD = 4#
SHARP_TURN = 5#
NO_DIRECTION = 6#
class larmor.tractography.MaskSeeds(mask)#

Class for seeding from a mask.

draw(n, rng)#

Draws n seeds from a mask.

Parameters:
  • n (int) – The number of seeds.

  • rng (Generator) – The random generator to draw with.

Returns:

Seeds – The seeds, positions in world coordinates, each in a voxel of the mask drawn at random.

Return type:

Seeds

type larmor.tractography.Region = Sphere | Volume#

A sphere, or a 3D mask Volume on any grid (or 4D with one volume).

class larmor.tractography.Seeds(positions, directions=None, indices=None)#

The seeds of a tracking: where each streamline starts, and optionally how.

Seeding can be either a simple set of positions from which to start from, or also by specifying the direction from which to start from. Optionally, if an indices array is specified, the order of seeding is matched 1 to 1 to the indices, for reproducibility purposes.

Parameters:
  • positions (NDArray[float64]) – Seed positions, shape (N, 3), in mm, world coordinates.

  • directions (NDArray[float64] | None) – Direction to start along for each seed, shape (N, 3); vectors that are not unit length are normalised. Defaults to None: the tracker finds one.

  • indices (NDArray[int64] | None) – The global index of each seed, shape (N,), non-negative integers. Defaults to None.

Raises:

ValueError – If a shape does not match, a value is not finite, a direction is zero, or the indices are not non-negative integers.

class larmor.tractography.SeedStrategy(*args, **kwargs)#

Seeding strategy protocol.

draw(n, rng)#

Draws n seeds.

Parameters:
  • n (int) – The number of seeds.

  • rng (Generator) – The random generator to draw with.

Returns:

Seeds – The n seeds.

Return type:

Seeds

class larmor.tractography.Sphere(centre, radius)#

A sphere in world coordinates.

A point is inside when its squared distance to the centre is at most the squared radius, computed in float32 like the points of a tractogram.

Parameters:
  • centre (ndarray) – (3,) the centre in world coordinates (RAS+), mm. Stored as a read-only float64 array.

  • radius (float) – The radius in mm, finite and not negative.

Raises:

ValueError – If centre is not three finite values or radius is negative or not finite.

class larmor.tractography.TractographyRun(path, seeds_path, parameters, num_seeds, num_streamlines, num_rejected, sampling=None, inputs=None, tractogram=None)#

Results of a tractography run.

path#

The tractogram written, or None if it was kept in memory.

Type:

pathlib.Path | None

seeds_path#

The seeds file written, or None.

Type:

pathlib.Path | None

parameters#

The values the run used, defaults resolved, as plain values that can be saved as JSON.

Type:

dict[str, object]

num_seeds#

The number of seeds tried.

Type:

int

num_streamlines#

The number of streamlines accepted.

Type:

int

num_rejected#

The seeds that gave no streamline, counted by reason: “no_start” (no direction to start) and “too_short”.

Type:

dict[str, int]

sampling#

Figures about the sampling of the steps (mean samples per step, steps per truncation, largest truncation and their counts), or None if no step was sampled.

Type:

dict[str, float | None] | None

inputs#

What the caller tracked from (files, seed source), recorded as it chose; None if not recorded.

Type:

dict[str, object] | None

tractogram#

The accepted streamlines when the run had no output file, else None.

Type:

larmor.types.tractogram.Tractogram | None

write_json(path)#

Saves a run results into a json.

Parameters:

path (str | Path) – Output path.

class larmor.tractography.Tracker(algorithm, *, step_size=None, max_angle=None, cutoff='auto', min_length=None, max_length=None, bidirectional=True, progress=False)#

Tracks streamlines through a field of FODs.

The settings are fixed here and track runs one tracking, from seeds to a tractogram. The algorithm is “det” (deterministic, default maximum angle 60 degrees) or “prob” (probabilistic, 15 degrees). Lengths are in mm.

References

Deterministic (“det”): Tournier J-D, Calamante F, Gadian DG, Connelly A. Direct estimation of the fiber orientation density function from diffusion-weighted MRI data using spherical deconvolution. NeuroImage 23 (2004) 1176-1185. doi:10.1016/j.neuroimage.2004.07.037

Probabilistic (“prob”): Tournier J-D, Calamante F, Connelly A. MRtrix: diffusion tractography in crossing fiber regions. Int J Imaging Syst Technol 22 (2012) 53-66. doi:10.1002/ima.22005

track(fod, output, seeds, *, num_streamlines=None, mask=None, basis='tournier', seed=None, output_seeds=None, n_jobs=-1)#

Tracks streamlines from the seeds, batch by batch.

Parameters:
  • fod (Volume) – The FOD, SH coefficients (X, Y, Z, C): the even degrees of a symmetric FOD, or all degrees of an asymmetric one, read from C.

  • output (str | Path | None) – The tractogram to write, .tck or .trk, batch by batch. Each streamline carries the EndStatus of both ends as end_status in its streamline data (kept by TRK only). None keeps the streamlines in memory and returns them in the run record: for small runs only, a whole brain takes tens of GB.

  • seeds (Seeds | SeedStrategy) – Where streamlines start: fixed seeds, tracked in order, or an endless source drawn batch by batch. Seeds without directions get one from the algorithm’s first-direction search; a seed where none is found counts as no_start.

  • num_streamlines (int | None) – Track until this many are accepted. Defaults to None: track every seed of a Seeds.

  • mask (Volume | None) – Tracking mask; a streamline stops where it leaves it. Defaults to None: no mask.

  • basis (str) – The FOD’s SH basis. Defaults to “tournier”.

  • seed (int | None) – The run seed, in [0, 2^64), which fixes the seeds drawn and every random number. Defaults to None: one is drawn and recorded.

  • output_seeds (str | Path | None) – A text file for the seeds of the accepted streamlines, in output order, which read_seeds reads back. Defaults to None.

  • n_jobs (int) – Threads to track with: -1 (default) for every core, or a positive number (at most the number of cores is used).

Returns:

TractographyRun – The record of the run.

Raises:

ValueError – If an endless seed source has no number of streamlines, num_streamlines is not positive, the mask is not 3D, seed or n_jobs is out of range, the FOD’s lmax is above the supported maximum or its coefficient count fits no SH layout, the resolved min length is not below the max length, the automatic cutoff cannot be measured (no voxel with a positive DC term or with a peak), or no seed lies on the FOD’s grid or in the mask. A seed with no start direction is not an error: it is counted in num_rejected["no_start"].

Return type:

TractographyRun

class larmor.tractography.TractProfile(values, core, reversed)#

The profile of a bundle: one value per map at each of its points.

Parameters:
  • values (dict[str, ndarray]) – For each map’s name, the (N,) float64 profile, from the start of the bundle to its end; NaN where no streamline has a finite value.

  • core (ndarray) – (N, 3) float64, the mean position of the streamlines at each profile point, in world coordinates (mm).

  • reversed (ndarray) – (S,) bool, the streamlines of the bundle that were reversed so that all run from the start to the end.

property num_points: int#

The number of profile points, N.

segments(bundle)#

The profile point each point of the bundle belongs to.

A point at a fraction f of its streamline’s length, measured from the streamline’s start (after the orientation), belongs to profile point round(f * (N - 1)). Use it to colour the bundle by segment, or, as profile.values[name][profile.segments(bundle)], by the profile’s value.

Parameters:

bundle (Tractogram) – The bundle the profile was computed from.

Returns:

np.ndarray –

(P,) int64, a profile point index from 0 to N - 1 for each

point of the bundle, in the order of bundle.points.

Raises:

ValueError – If the bundle does not have as many streamlines as the profile was computed from.

Return type:

ndarray

write_csv(path)#

Writes the profile as a CSV table, one row per profile point.

The columns are point (0 at the start of the bundle), core_x, core_y, core_z (the core, in mm) and one column per map, named after it.

Parameters:

path (str | Path) – The CSV file to write.

class larmor.tractography.Weighting#

How the streamlines’ values at one profile point are averaged.

GAUSSIAN = 'gaussian'#
MEAN = 'mean'#
larmor.tractography.build_connectome(nodes, num_nodes, *, weights=None, values=None, symmetric=False, zero_diagonal=False)#

Builds a connectome matrix from the regions of the streamlines’ endpoints.

Every streamline whose two endpoints are both in a region (nodes 1 to num_nodes) adds to the edge between its two regions, an entry of the upper triangle (row <= column); one that ends twice in the same region adds to the diagonal. Streamlines with an endpoint in no region (node 0) are left out. Without values, an edge holds the number of its streamlines, or the sum of their weights. With values, it holds their mean value, weighted by the weights if given, and 0 where no streamline connects the two regions.

Parameters:
  • nodes (ndarray) – (S, 2) the regions of each streamline’s endpoints, as from endpoint_nodes.

  • num_nodes (int) – The number of regions: the matrix has one row per label from 1 to num_nodes, usually the largest label of the parcellation (len(node_names(parcellation))). Relabel sparse labels to consecutive ones first, or the matrix holds a row for every unused label.

  • weights (ndarray | None) – (S,) one weight per streamline, such as SIFT2’s. Defaults to None: every streamline counts 1.

  • values (ndarray | None) – (S,) one value per streamline, such as its length (streamline_lengths), to average over each edge. Defaults to None.

  • symmetric (bool) – Fill the lower triangle with the upper one. Defaults to False: the lower triangle is 0.

  • zero_diagonal (bool) – Set the diagonal (connections of a region to itself) to 0. Defaults to False.

Returns:

(num_nodes, num_nodes) float64; row and column i are region i + 1.

Raises:

ValueError – If nodes is not (S, 2) with labels from 0 to num_nodes, or weights or values does not have S finite values.

Return type:

ndarray

References

Hagmann P, Cammoun L, Gigandet X, Meuli R, Honey CJ, Wedeen VJ, Sporns O. Mapping the structural core of human cerebral cortex. PLoS Biol 6 (2008) e159. Follows MRtrix3’s tck2connectome (version 3.0.8) with the default -stat_edge sum, and -stat_edge mean with -scale_length or -scale_file.

larmor.tractography.concatenate_tractograms(tractograms)#

Joins tractograms into one, their streamlines one after the other.

The data entries (point_data and streamline_data) that every input has, with the same kind of dtype (float, signed int, unsigned int, …) and the same shape after the first axis, are joined, their dtypes promoted to a common one (np.result_type); the others are dropped with a warning. The reference is kept when every input has one and they all match (Grid.matches); it is None, with a warning, when some inputs have one and others do not or the references differ, and None without a warning when no input has one. Inputs with no streamlines add nothing, so both rules leave them out unless every input is empty.

Parameters:

tractograms (Sequence[Tractogram]) – The tractograms, in order. Any of them may be empty.

Returns:

Tractogram –

The joined tractogram, with the reference of the first input

that has streamlines (or of the first input, if all are empty) when it is kept.

Raises:

ValueError – If no tractogram is given.

Return type:

Tractogram

larmor.tractography.crop(tractogram, regions, *, keep_inside=True)#

Cuts the streamlines to the parts inside (or outside) the regions.

Each streamline is cut into its runs of consecutive points inside any of the regions (outside all of them with keep_inside=False); runs of fewer than 2 points are dropped, so a streamline that leaves and re-enters gives several pieces, and one that is never inside gives none. The pieces come in the order of the input streamlines and of their points. Each piece keeps its points’ point_data and its streamline’s streamline_data.

Parameters:
  • tractogram (Tractogram) – The streamlines.

  • regions (Region | Sequence[Region]) – One or more spheres or 3D masks.

  • keep_inside (bool) – Keep the parts inside the regions; False keeps the parts outside all of them. Defaults to True.

Returns:

Tractogram – The pieces, with their data and the same reference.

Raises:
  • TypeError – If a region is neither a Sphere nor a Volume.

  • ValueError – If no region is given, or a mask is neither 3D nor 4D with a single volume.

Return type:

Tractogram

References

Follows MRtrix3’s tckedit (version 3.0.8). Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.density_grid(reference, voxel_size)#

A grid of smaller (or larger) voxels over the field of view of a reference grid.

The reference is first brought to RAS axis order (Grid.canonical), which does not move its voxels. Along each axis the new grid starts at the same outer corner of the field of view and has ceil(n * old / new) voxels of the new size, so it covers the reference’s field of view, overshooting it by less than one new voxel at the far end.

Parameters:
  • reference (Grid) – The grid whose field of view the new grid covers.

  • voxel_size (float | Sequence[float]) – The new voxel size in mm: one value for isotropic voxels, or one per axis (in RAS order: x, y, z).

Returns:

The new grid, in RAS axis order, with the reference’s axis directions.

Raises:

ValueError – If voxel_size is not one or three positive finite values.

Return type:

Grid

References

The grid of MRtrix3’s tckmap -template with -vox (version 3.0.8).

larmor.tractography.edit(tractogram, options)#

Runs a whole edit: selection, cropping, counting and resampling.

In this order:

  1. The length and weight limits and the include, ordered include, exclude and within regions give one selection: a streamline is kept when it passes all of them. With inverse the selection is flipped, keeping the streamlines that fail at least one test; with no test given, every streamline is kept.

  2. The kept streamlines are cropped to the mask regions (with inverse, to the parts outside them), see crop.

  3. skip, every and then number or subsample count the selected streamlines: the first skip are dropped, then every every-th is kept starting with the first, then the first number (or a random subsample) of those. A streamline cropped into several pieces counts as one, and one cropped to nothing is gone. When fewer streamlines are left than number or subsample asks for, all are kept; subsample logs a warning.

  4. The result is resampled when step_size or num_points is given, see resample.

Empty streamlines and negative weights are kept unless a length or weight limit drops them. Each piece keeps its points’ point_data and its streamline’s streamline_data; the reference is kept.

Parameters:
  • tractogram (Tractogram) – The streamlines, with streamline_data["weight"] when a weight limit is given.

  • options (EditOptions) – The selections and edits.

Returns:

Tractogram – A new tractogram with the edited streamlines, in input order.

Raises:
  • ValueError – If a weight limit is given and the tractogram has no “weight” entry, or a mask region is neither 3D nor 4D with a single volume.

  • TypeError – If a region is still text or a path (see load_region).

Return type:

Tractogram

References

Follows MRtrix3’s tckedit and tckresample (version 3.0.8). Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.edit_files(inputs, output, options, *, weights_in=None, weights_out=None, tsf_in=(), tsf_out=(), reference=None, force=False, lazy=False, batch_size=10000)#

Edits tractogram files into one output file, as edit does in memory.

The inputs are read and joined in order (see concatenate_tractograms), the weights and TSF values attached, the edit run and the result written with its weights and TSF files. Everything that can be checked from the paths and headers is checked before any streamline is read.

By default the inputs are read whole. With lazy, each input is read in batches of batch_size streamlines (iter_tractogram) and each batch is edited and written before the next is read, so memory stays at a few batches: the rules of the concatenation are decided on the first batch of every input before anything is written, the counts of skip, every and number carry from one batch to the next, and reading stops once number streamlines are written. An error during the run leaves the output marked as incomplete; the weights_out file then holds the weights written so far, with nothing marking it incomplete.

The regions of options may be given as text (x,y,z,r or a mask image’s path); they are read with load_region after every check above.

The weights are streamline_data["weight"]: those of weights_in, or else a TRK input’s weight property, which weights_in replaces with a warning. Each tsf_in file becomes the point_data entry named after its stem; each tsf_out entry is written as <output name>_<name>.tsf (see _tsf_output_path). A TCK output and the TSF files get one timestamp, so MRtrix pairs them: that of the input for a single TCK input that has one, else a new one.

Parameters:
  • inputs (Sequence[str | Path]) – The input tractograms, tck, trk or vtk/fib (each also gzipped), joined in this order.

  • output (str | Path) – The output tractogram, of any of these formats.

  • options (EditOptions) – The selections and edits.

  • weights_in (str | Path | None) – A weights file with one value per streamline of the single input. Defaults to None.

  • weights_out (str | Path | None) – Write the weights of the output streamlines to this file. Defaults to None.

  • tsf_in (Sequence[str | Path]) – TSF files with values per point of the single input. Defaults to none.

  • tsf_out (Sequence[str]) – Names of point_data entries to write as TSF files next to the output. Defaults to none.

  • reference (Grid | str | Path | None) – The grid of a TRK output when the inputs do not all have one, or an image whose grid it is (a NIfTI or MIF file, or an MRIToolkit fit mat, read after the checks); given to the readers as load_tractogram takes it. Needed for MRIToolkit tractography inputs (mat). Defaults to None.

  • force (bool) – Overwrite existing output files. Defaults to False.

  • lazy (bool) – Read, edit and write in batches. Defaults to False.

  • batch_size (int) – Streamlines per batch with lazy.

Returns:

tuple[int, int] –

The number of streamlines read (fewer than in the inputs

when lazy reading stops early at number) and written. The read count is that of the streamlines passed to the edit: the first batches of later inputs, read before the stop to decide the join, are not counted.

Raises:
  • FileExistsError – If an output file exists and force is False.

  • FileNotFoundError – If the folder of an output file does not exist.

  • ValueError – Before any work: if no input is given, an extension is not a tractogram’s, weights_in or tsf_in is given with several inputs, two tsf_in files have the same stem, a weight limit or weights_out is given without weights, a tsf_out name is not provided by every input, a TRK output has no reference grid, or lazy is given with a VTK or compressed file, subsample, TSF files or an output that is also an input. During the work: if the weights or TSF values do not match the streamlines, a VTK input lacks the weights or TSF values asked for (VTK arrays are known only once read), or a file cannot be read or written.

Return type:

tuple[int, int]

References

Follows MRtrix3’s tckedit (version 3.0.8). Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.endpoint_nodes(tractogram, parcellation, *, radius=4.0, n_jobs=-1)#

Assigns the two endpoints of every streamline to regions of a parcellation.

Each endpoint is mapped to its nearest voxel (an endpoint exactly halfway between two voxels goes to the one further right, anterior or superior). With radius None, the endpoint’s region is that voxel’s label (0 outside the image). With a radius (the radial search), it is that voxel’s label when it is not 0; otherwise the label of the labelled voxel whose centre is nearest to the endpoint, if that centre is less than radius from it, and 0 if there is none. At equal distances any of the nearest voxels may be taken.

Parameters:
  • tractogram (Tractogram) – The streamlines, in world coordinates (mm).

  • parcellation (Volume) – The regions: a 3D image of integer labels, 0 for no region (see parcellation_labels), on any grid.

  • radius (float | None) – The search radius in mm, or None to use only the voxel the endpoint is in. Defaults to 4.0.

  • n_jobs (int) – Threads for the radial search: -1 (default) for every core.

Returns:

(S, 2) int64 – the regions of the first and the last point of each streamline, 0 where an endpoint is in no region; both 0 for an empty streamline.

Raises:

ValueError – If radius is negative or not finite, or the parcellation is not valid (see parcellation_labels).

Return type:

ndarray

References

Smith RE, Tournier JD, Calamante F, Connelly A. The effects of SIFT on the reproducibility and biological accuracy of the structural connectome. NeuroImage 104 (2015) 253-265 (the radial search). Follows MRtrix3’s tck2connectome (version 3.0.8) with -assignment_radial_search and -assignment_end_voxels.

larmor.tractography.load_region(spec)#

Reads a region given as text: a sphere x,y,z,r or the path of a mask image.

Parameters:

spec (str | Path) – Four comma-separated numbers, the centre in world coordinates (RAS+) and the radius, in mm; anything else is the path of a mask image (nii, nii.gz, mif, mif.gz or mih).

Returns:

Region – A Sphere, or the mask as a Volume.

Raises:

ValueError – If the sphere’s radius is negative, the text has commas but is neither four numbers nor an image’s name, or the image cannot be read.

Return type:

Region

larmor.tractography.node_names(parcellation, *, lookup_table=None)#

The names of the nodes of a connectome built on a parcellation.

The nodes are the labels 1 to the largest label of the parcellation, so the length of the list is the number of nodes (build_connectome’s num_nodes). The matrix grows with the largest label, not with the number of regions: relabel a parcellation with sparse labels (such as FreeSurfer’s, up to about 14,000) to consecutive ones first, for example with MRtrix3’s labelconvert.

Parameters:
  • parcellation (Volume) – The regions: a 3D image of integer labels (see parcellation_labels).

  • lookup_table (Mapping[int, Label] | None) – Names by label, as from read_lookup_table. Defaults to None: every node is named by its label.

Returns:

One name per label from 1 to the largest; a label missing from the table is named by its number.

Raises:

ValueError – If the parcellation is not valid (see parcellation_labels).

Return type:

list[str]

larmor.tractography.parcellation_labels(parcellation)#

The labels of a parcellation as an (X, Y, Z) int64 array, 0 for no region.

The values (after the image’s scaling) are rounded to the nearest integer, so a parcellation stored as floats is read as its labels.

Parameters:

parcellation (Volume) – A 3D image of region labels (or 4D with a single volume).

Returns:

The labels, one per voxel.

Raises:

ValueError – If the image is not 3D (or 4D with one volume), or has a negative or non-finite value.

Return type:

ndarray

larmor.tractography.passes_in_order(tractogram, regions, *, ends_only=False)#

Tests which streamlines pass through the regions in the given order.

Each point is assigned to the first region, in the given order, that contains it. Along the streamline, ignoring the points in no region, the assigned regions must start at the first region, then either stay in the same region or move to the next one, and end at the last region. So a streamline may leave a region into no region and come back to it, but never go back to an earlier region or skip one. With ends_only, only the first and then the last point are assigned, which allows at most two regions. Empty streamlines never pass. mask is the opposite selection.

Parameters:
  • tractogram (Tractogram) – The streamlines.

  • regions (Sequence[Region]) – One or more spheres or 3D masks, in order.

  • ends_only (bool) – Test only the two endpoints. Defaults to False.

Returns:

np.ndarray –

(S,) bool, True for the streamlines that pass through all the

regions in order.

Raises:
  • TypeError – If a region is neither a Sphere nor a Volume.

  • ValueError – If no region is given, more than two with ends_only, or a mask is neither 3D nor 4D with a single volume.

Return type:

ndarray

References

Follows MRtrix3’s tckedit (version 3.0.8). Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.passes_through(tractogram, region, *, ends_only=False)#

Tests which streamlines pass through a region.

A streamline passes through the region when at least one of its points is inside it (see points_inside); with ends_only, only its first and last points are tested. Empty streamlines never pass. Combine masks with & and | for several include or exclude regions; mask is the opposite selection, and t[mask] the selected streamlines.

Parameters:
  • tractogram (Tractogram) – The streamlines.

  • region (Region) – A Sphere, or a 3D mask Volume on any grid.

  • ends_only (bool) – Test only the two endpoints. Defaults to False.

Returns:

np.ndarray – (S,) bool, True for the streamlines that pass through.

Raises:
  • TypeError – If the region is neither a Sphere nor a Volume.

  • ValueError – If the mask is neither 3D nor 4D with a single volume.

Return type:

ndarray

References

Follows MRtrix3’s tckedit (version 3.0.8). Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.points_inside(points, region)#

Tests which points lie inside a region.

For a sphere, a point is inside when its squared distance to the centre is at most the squared radius. For a mask, each point is mapped to voxel coordinates with the inverse of the mask’s affine and rounded to the nearest voxel, halves away from zero; it is inside when that voxel is in the image and its value (scaled), rounded to an integer the same way, is not zero. Only the given points are tested: there is no interpolation between them.

Parameters:
  • points (ndarray) – (P, 3) points in world coordinates (RAS+), mm.

  • region (Region) – A Sphere, or a 3D mask Volume on any grid.

Returns:

np.ndarray – (P,) bool, True where the point is inside the region.

Raises:
  • TypeError – If region is neither a Sphere nor a Volume.

  • ValueError – If points is not (P, 3) or the mask is not 3D (a 4D mask with a single volume counts as 3D).

Return type:

ndarray

References

Follows MRtrix3’s region tests in tckedit and tckgen. Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.read_seeds(path)#

Reads seeds written by write_seeds.

The header line tells which columns the file has: x y z, optionally preceded by index and followed by dx dy dz.

Parameters:

path (str | Path) – The text file.

Returns:

Seeds – The seeds, in the file’s order; empty if the file has only its header.

Raises:

ValueError – If the header is missing or names other columns, or the rows do not have as many columns as the header.

Return type:

Seeds

larmor.tractography.resample(tractogram, *, step_size=None, num_points=None, n_jobs=-1)#

Resamples every streamline to a step size or to a number of points.

The new points lie on a cubic Hermite spline (tension 0.1) through each streamline’s points, extended by one mirrored point beyond each end. With num_points, they are at equal arc lengths of the polyline. With step_size, they start from the middle point and go outward to each end, each at step_size (straight-line distance) from the previous one, found by bisection on the spline parameter. With step_size both end points are kept exactly; with num_points they are kept up to float32 rounding (the last is the spline at a parameter of about 1), except when the first or last segment has zero length (a repeated end point): that end is then a spline point near it. Streamlines of fewer than 2 points are kept as they are. Floating-point point_data is interpolated linearly at the same spline parameter and keeps its dtype; other entries (integers, labels, booleans) take the value of the nearer of the two original points (the earlier one at a tie). streamline_data and reference are kept. Non-finite points give non-finite points with num_points; with step_size, a pass that meets one ends at the streamline’s end point. The work runs in C++ on n_jobs threads; the result does not depend on their number.

Parameters:
  • tractogram (Tractogram) – The tractogram to resample.

  • step_size (float | None) – The distance between consecutive new points, in mm. Defaults to None.

  • num_points (int | None) – The number of points of every new streamline, at least 2. Defaults to None.

  • n_jobs (int) – Threads to use: -1 (default) for every core, or a positive number (at most the number of cores is used).

Returns:

Tractogram –

A new tractogram with the resampled streamlines, in the same

order.

Raises:

ValueError – If neither or both of step_size and num_points are given, step_size is not a positive finite number, num_points is not an integer >= 2, or n_jobs is not an integer, 0 or below -1.

Return type:

Tractogram

References

Follows MRtrix3’s tckresample (version 3.0.8), options -step_size and -num_points. Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.sample_volume(tractogram, volume)#

Samples an image at every point of a tractogram, with trilinear interpolation.

Each point is mapped to voxel coordinates with the image’s affine. A point whose nearest voxel is inside the image gets the value interpolated from the eight voxels around it, where a neighbour beyond the edge takes the edge voxel’s value; a point whose nearest voxel is outside (a voxel coordinate at most -0.5, or at least the axis size minus 0.5) gets 0. The values are scaled by the image’s slope and intercept. Pair the result with the tractogram, for example as tractogram.point_data["fa"], or write it with write_tsf.

Parameters:
  • tractogram (Tractogram) – The streamlines, in world coordinates (mm).

  • volume (Volume) – A 3D image, or a 4D one with a single volume.

Returns:

The (P,) float32 values, one per point, in the order of tractogram.points.

Raises:

ValueError – If the image is 4D with more than one volume.

Return type:

ndarray

References

Follows MRtrix3’s tcksample with its default (trilinear) interpolation. Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137.

larmor.tractography.write_connectome(matrix, path, *, names=None)#

Writes a connectome matrix as text, with the region names.

A csv file is comma-separated, with the names as its first row and first column (an empty first cell), as spreadsheets and pandas’ read_csv(path, index_col=0) read it. Any other extension gives a matrix separated by spaces after one comment line # names: <name> <name> ..., which numpy.loadtxt skips. Values are written with 10 significant digits.

Parameters:
  • matrix (ndarray) – (N, N) the connectome.

  • path (str | Path) – The output file.

  • names (Sequence[str] | None) – N region names, without whitespace or commas, such as those of read_lookup_table. Defaults to None: the labels 1 to N.

Raises:

ValueError – If matrix is not square or names does not have one name per row without whitespace or commas.

larmor.tractography.write_node_assignments(nodes, path)#

Writes the regions of each streamline’s endpoints, one streamline per line.

Each line holds the two labels separated by a space, in the order of the streamlines, as MRtrix3’s tck2connectome -out_assignments writes them.

Parameters:
Raises:

ValueError – If nodes is not an (S, 2) integer array.

larmor.tractography.seeds_per_voxel(mask, n, rng)#

Draws n seeds per voxel from the given mask.

Parameters:
  • mask (Volume) – The voxels to seed.

  • n (int) – Seeds per voxel.

  • rng (Generator | int) – A generator, or a run seed in [0, 2^64): then the seeds come from np.random.default_rng([rng, PER_VOXEL_STREAM]), so the same run seed gives the same seeds.

Returns:

Seeds – The seeds, n in each voxel of the mask, at random positions in it.

Raises:

ValueError – If n is not positive, or the mask is not 3D or has no voxel above 0.

Return type:

Seeds

larmor.tractography.select_length(tractogram, *, min_length=0.0, max_length=inf)#

Selects the streamlines whose length is within limits.

The length is that of streamline_lengths; both limits are inclusive.

Parameters:
  • tractogram (Tractogram) – The streamlines.

  • min_length (float) – The shortest length kept, in mm. Defaults to 0.

  • max_length (float) – The longest length kept, in mm. Defaults to infinity.

Returns:

np.ndarray – (S,) bool, True for the streamlines kept.

Raises:

ValueError – If a limit is NaN or min_length is larger than max_length.

Return type:

ndarray

References

Follows the -minlength and -maxlength options of MRtrix3’s tckedit. Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.select_weight(tractogram, *, min_weight=-inf, max_weight=inf)#

Selects the streamlines whose weight is within limits.

The weights are streamline_data["weight"], compared in float64; both limits are inclusive. A NaN weight is never selected.

Parameters:
  • tractogram (Tractogram) – The streamlines, with a “weight” entry in streamline_data, for example read with read_streamline_weights.

  • min_weight (float) – The smallest weight kept. Defaults to minus infinity.

  • max_weight (float) – The largest weight kept. Defaults to infinity.

Returns:

np.ndarray – (S,) bool, True for the streamlines kept.

Raises:

ValueError – If the tractogram has no “weight” entry, the entry is not one value per streamline, a limit is NaN or min_weight is larger than max_weight.

Return type:

ndarray

References

Follows the -minweight and -maxweight options of MRtrix3’s tckedit. Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.stays_within(tractogram, region, *, ends_only=False)#

Tests which streamlines stay within a region.

A streamline stays within the region when every one of its points is inside it (see points_inside); with ends_only, when both its first and last points are. Empty streamlines have no point inside, so they never stay within. Combine masks with & for several regions; t[mask] keeps the selected streamlines.

Parameters:
  • tractogram (Tractogram) – The streamlines.

  • region (Region) – A Sphere, or a 3D mask Volume on any grid.

  • ends_only (bool) – Test only the two endpoints. Defaults to False.

Returns:

np.ndarray – (S,) bool, True for the streamlines that stay within.

Raises:
  • TypeError – If the region is neither a Sphere nor a Volume.

  • ValueError – If the mask is neither 3D nor 4D with a single volume.

Return type:

ndarray

larmor.tractography.streamline_lengths(tractogram)#

Returns the length of each streamline.

The length is the sum of the distances between consecutive points, computed in float64; a streamline of 0 or 1 points has length 0.

Parameters:

tractogram (Tractogram) – The streamlines.

Returns:

np.ndarray – (S,) float64, the lengths in mm.

Return type:

ndarray

References

Follows MRtrix3’s tckstats. Tournier, J.-D. et al. MRtrix3: A fast, flexible and open software framework for medical image processing and visualisation. NeuroImage 202, 116137 (2019). doi:10.1016/j.neuroimage.2019.116137

larmor.tractography.track_density(tractogram, grid, *, weights=None, ends_only=False, upsample=None, n_jobs=-1)#

Counts the streamlines that pass through each voxel of a grid.

Each streamline is first upsampled: upsample - 1 points are added between each pair of consecutive points, on the cubic Hermite spline (tension 0.1) that resample uses. Every point is mapped to its nearest voxel (a point exactly halfway between two voxels goes to the one further right, anterior or superior), and the streamline adds 1, or its weight, once to each voxel it reaches, however many of its points fall there. Points outside the grid are skipped. With ends_only the image is the endpoint density instead: each of the two endpoints adds 1 (or the weight) to its voxel, so a streamline that ends twice in one voxel adds 2 there (a streamline of one point adds 1).

The grid may be finer than the image the streamlines were tracked on (see density_grid), which gives super-resolution track density imaging. Without upsampling, a fine grid misses voxels between points spaced more widely than its voxels, so by default the ratio is the smallest whole number that brings the median distance between consecutive points (of the first 10,000 streamlines), divided by the ratio, below a third of the smallest voxel size.

Parameters:
  • tractogram (Tractogram | Iterable[Tractogram]) – The streamlines, in world coordinates (mm); or an iterable of tractograms, such as the batches of iter_tractogram, whose densities are added up, for files too large for memory.

  • grid (Grid) – The grid of the image to fill.

  • weights (ndarray | None) – (S,) one weight per streamline, in the order of the streamlines (across all batches), such as SIFT2’s. Defaults to None: every streamline counts 1.

  • ends_only (bool) – Map only the two endpoints of each streamline. Defaults to False.

  • upsample (int | None) – The upsampling ratio, at least 1 (1 maps only the stored points). Defaults to None: chosen from the point spacing of the first 10,000 streamlines (across batches) and the grid. Not used with ends_only.

  • n_jobs (int) – Threads to use: -1 (default) for every core. The result does not depend on it.

Returns:

A 3D volume on grid – uint32 counts without weights, float32 sums of the weights with them.

Raises:

ValueError – If weights does not have one finite value per streamline, upsample is not an integer of at least 1, or n_jobs is 0 or below -1.

Return type:

Volume

References

Calamante F, Tournier JD, Jackson GD, Connelly A. Track-density imaging (TDI): super-resolution white matter imaging using whole-brain track-density mapping. NeuroImage 53 (2010) 1233-1243. The mapping follows MRtrix3’s tckmap (version 3.0.8) with its default TDI contrast, and -ends_only.

larmor.tractography.tract_profile(bundle, maps, *, num_points=100, weighting=Weighting.GAUSSIAN, start=None, n_jobs=-1)#

Computes the profile of maps (FA, MD, …) along a bundle.

The streamlines are first oriented so that all run the same way, then each is resampled to num_points points at equal arc lengths (resample), so that point n of every streamline lies at the same fraction of the bundle’s length. Each map is sampled at those points with trilinear interpolation (sample_volume), and the profile at point n is the average of the streamlines’ values there. Points outside a map (whose nearest voxel is outside its grid) and non-finite values are left out of the average.

Orientation. Without start, the bundle’s main axis is the direction that best fits the vectors from each streamline’s first point to its last (the leading eigenvector of the sum of their outer products), with its sign chosen so that its largest component, x, y or z, is positive. Each streamline is reversed if its end-to-end vector points against that axis. The start of the profile is therefore the bundle’s end that is left, posterior or inferior (in world coordinates, RAS+) along the main axis: the brainstem end of a corticospinal tract, the left end of the corpus callosum. When the axis’s two largest components are within 20% of each other in size, a small change in the bundle can move the start to the other end, and a warning says so. With start, each streamline is reversed only when its last point is nearer to start than its first point; group studies should pass start (the same anatomical point, or one per subject), so that every subject’s profile starts at the same end.

Weighting. With “gaussian”, the streamlines’ values at point n are weighted by the probability that each streamline belongs to the bundle there, under a 3D Gaussian fitted to the streamlines’ points (Yeatman et al. 2012): the squared Mahalanobis distance d^2 of each streamline’s point from the mean of all of them, under their covariance (normalised by S - 1 for S streamlines; its pseudo-inverse when singular), gives the weight exp(-d^2 / 2), and the weights are normalised to sum to 1. With “mean”, all streamlines weigh the same.

Parameters:
  • bundle (Tractogram) – The streamlines of one bundle, in world coordinates (mm), each of at least 2 points.

  • maps (Mapping[str, Volume]) – The maps to profile, by name; each a 3D image, or a 4D one with a single volume.

  • num_points (int) – The number of profile points, N, at least 2. Defaults to 100.

  • weighting (Weighting | str) – “gaussian” or “mean”. Defaults to “gaussian”.

  • start (ArrayLike | None) – A point (x, y, z) in mm near the end of the bundle where the profile should start. Defaults to None: the rule above.

  • n_jobs (int) – Threads for the resampling: -1 (default) for every core.

Returns:

TractProfile –

The profile of each map, the core and the reversed

streamlines.

Raises:

ValueError – If the bundle is empty or has a streamline of fewer than 2 points, num_points is below 2, weighting is unknown, start is not three numbers, or a map has several volumes.

Return type:

TractProfile

References

Yeatman JD, Dougherty RF, Myall NJ, Wandell BA, Feldman HM. Tract profiles of white matter properties: automating fiber-tract quantification. PLoS One 7, e49790 (2012). doi:10.1371/journal.pone.0049790. Chandio BQ, Risacher SL, Pestilli F, et al. Bundle analytics, a computational framework for investigating the shapes and profiles of brain pathways across populations. Sci Rep 10, 17149 (2020). doi:10.1038/s41598-020-74054-4.

larmor.tractography.write_seeds(seeds, path, *, header=True)#

Writes seeds as text, one row per seed, for read_seeds.

The columns are [index] x y z [dx dy dz]: the index and the directions only if the seeds have them. The header line, starting with ‘#’, names the columns. Positions and directions are written with 17 significant digits, which gives back every float64 exactly, so seeds read back track exactly as before.

Parameters:
  • seeds (Seeds) – The seeds to write.

  • path (str | Path | TextIO) – The text file, whose content is overwritten, or a file open for writing, to which the rows are added; the tracker writes its seeds batch by batch this way.

  • header (bool) – Whether to write the header line first. Defaults to True; False for every batch after the first.