larmor.io#

Loading and saving the core data types by path, and the gradient files.

SURFACE_EXTENSIONS

The surface format chosen by the file name ending; other surfaces are FreeSurfer's.

TRACTOGRAM_EXTENSIONS

The tractogram formats, and the file name endings that select each.

VOLUME_EXTENSIONS

The volume formats, and the file name endings that select each.

BatchWriter

A tractogram file written batch by batch, finished by close.

MRIToolkitFit

A DTI or DKI fit read from MRIToolkit's mat file, in world space.

MatlabEntry

One variable of a mat file, or a struct field or cell inside one.

MatlabFile

A mat file: its variables, listed, and read one at a time.

Progress

ReadCancelledError

Raised by a progress callback to stop a read; the read then raises it too.

file_kind

Whether a file is a volume or a tractogram, from its extension.

has_mif_gradients

Checks whether a MIF file's header has a gradient table (dw_scheme).

iter_tractogram

Reads a tractogram batch by batch, for files too large to hold in memory.

load_dwi

Loads a diffusion volume and its gradients.

load_grid

Reads only the grid of a file, without the data.

load_header

Reads only the header of a volume file, without the data.

load_surface

Reads a surface, and optionally files of values per vertex for it.

load_tractogram

Reads a tractogram, in the format given by the file's extension.

load_tractogram_subset

Reads a tractogram, keeping at most max_streamlines, and says which.

load_volume

Reads a volume, in the format given by the file's extension.

open_tractogram_writer

Opens a tractogram file to be written batch by batch, by its extension.

output_files

Returns every file that save_volume writes for path.

read_b_matrix

Reads a b-matrix file written by write_b_matrix.

read_bvals_bvecs

Reads bvals and bvecs files into a gradient table in world coordinates.

read_lookup_table

Reads a lookup table in the FreeSurfer or the MRtrix layout.

read_matlab

Opens a MATLAB mat file (version 4, 5 to 7, or 7.3) for listing and reading.

read_mritoolkit_fit

Reads MRIToolkit's DTI or DKI fit (EDTI.PerformDTI_DKIFit) in world space.

read_mritoolkit_frame

Reads the (3, 3) matrix taking MRIToolkit's vectors to world coordinates.

read_mritoolkit_grid

Reads the image grid of an MRIToolkit fit from the NIfTI header it stores.

read_mritoolkit_kind

Reads what kind of MRIToolkit result a mat file holds, from its variables.

read_mritoolkit_map

Reads one map an MRIToolkit fit stores, as MRIToolkitFit.maps holds it.

read_mritoolkit_peaks

Reads a peaks image in MRIToolkit's layout and frame, as world peaks.

read_mritoolkit_tracts

Reads MRIToolkit's tractography (Tracts and its per-point values).

read_mritoolkit_volume

Reads an image of an MRIToolkit mat file as a Volume, its values as stored.

read_mrtrix_gradients

Reads an MRtrix gradient table file (b, as given to MRtrix's -grad).

read_streamline_weights

Reads a streamline weights file, such as those of tcksift2 and tckedit.

read_track_timestamp

Reads the timestamp in the header of a TCK or TSF file, without its data.

read_tsf

Reads a TSF file (MRtrix track scalar file): one value per streamline point.

save_surface

Writes a surface: GIfTI for a gii name, FreeSurfer for any other name.

save_tractogram

Writes a tractogram, in the format given by the file's extension.

save_volume

Writes a volume, in the format given by the file's extension.

write_b_matrix

Writes the table's b-matrix as an Larmor b-matrix file.

write_bvals_bvecs

Writes a gradient table as bvals and bvecs files: one row, and 3 rows.

write_mrtrix_gradients

Writes a gradient table as an MRtrix gradient file (b).

write_streamline_weights

Writes streamline weights as text, for read_streamline_weights or MRtrix.

write_tsf

Writes values per streamline point as a TSF file (MRtrix track scalar file).

larmor.io.SURFACE_EXTENSIONS = {'gifti': ('.gii',)}#

The surface format chosen by the file name ending; other surfaces are FreeSurfer’s.

larmor.io.TRACTOGRAM_EXTENSIONS = {'tck': ('.tck', '.tck.gz'), 'trk': ('.trk', '.trk.gz'), 'vtk': ('.vtk', '.vtk.gz', '.fib', '.fib.gz')}#

The tractogram formats, and the file name endings that select each.

larmor.io.VOLUME_EXTENSIONS = {'mif': ('.mif', '.mif.gz', '.mih'), 'nifti': ('.nii', '.nii.gz')}#

The volume formats, and the file name endings that select each.

class larmor.io.BatchWriter#

A tractogram file written batch by batch, finished by close.

Used as a context manager: leaving the block normally finishes the file (writes the streamline count into its header); leaving it with an exception, as an interrupted run does, only closes it, so the file keeps the count that marks it as unfinished and readers report it as incomplete.

write(tractogram)#

Appends the streamlines of a tractogram to the file.

Parameters:

tractogram (Tractogram) – The streamlines to append.

close()#

Writes the final streamline count and closes the file.

class larmor.io.MRIToolkitFit(dt, kt, dwi, gradients, mask, maps=<factory>)#

A DTI or DKI fit read from MRIToolkit’s mat file, in world space.

dt#

Diffusion tensor, (X, Y, Z, 6) float32, elements xx, xy, xz, yy, yz, zz in world coordinates (as DTIFit.dt), in mm^2/s; 0 outside the mask.

Type:

larmor.types.volume.Volume

kt#

Kurtosis tensor, (X, Y, Z, 15) float32, in the element order of DKIFit.kt, in world coordinates; None for a DTI fit.

Type:

larmor.types.volume.Volume | None

dwi#

The diffusion-weighted data, (X, Y, Z, N), in the file’s volume order (sorted by b-value) and type.

Type:

larmor.types.volume.Volume

gradients#

The gradient table of dwi, from the file’s b-matrix.

Type:

larmor.types.gradient_table.GradientTable

mask#

The fitted voxels (where the file’s tensor is finite), (X, Y, Z) bool.

Type:

larmor.types.volume.Volume

maps#

The maps the file stores (read_mritoolkit_map), float32 and 0 outside the mask: “FA” (the usual FA; the file’s is sqrt(3) times it), “MD”, “AD”, “RD”, “eigenvalues” (X, Y, Z, 3, descending), “FE” (the first eigenvector in world coordinates, (X, Y, Z, 3)) and “b0” (the file’s DWIB0), each when the file has what it needs.

Type:

dict[str, larmor.types.volume.Volume]

class larmor.io.MatlabEntry(path, shape, matlab_class, sparse=False)#

One variable of a mat file, or a struct field or cell inside one.

path#

Where it is: a variable name, then field for a struct field, {i} for a cell element and (i) for a struct array element, with MATLAB’s 1-based linear indices (for example results.FOD, Tracts{3}).

Type:

str

shape#

Its MATLAB size; empty for an object whose size is not stored.

Type:

tuple[int, …]

matlab_class#

Its MATLAB class (double, logical, char, struct, cell, or the class of an object such as string).

Type:

str

sparse#

Whether it is a sparse matrix.

Type:

bool

class larmor.io.MatlabFile(path)#

A mat file: its variables, listed, and read one at a time.

Values come back as plain Python and numpy values, the same for every version: numeric and logical arrays as numpy arrays with MATLAB’s shape, so a[i, j, k] is MATLAB’s a(i+1, j+1, k+1) (MATLAB stores arrays column-major, so they are Fortran-ordered); complex arrays as complex arrays; sparse matrices as scipy.sparse.csc_array; a char row as str and a char matrix as a list of its rows; a scalar struct as a dict of its fields; struct arrays and cell arrays as lists in MATLAB’s linear (column-major) order, their shape given by entries. Empty numeric arrays keep their shape, an empty char is "" and an empty cell or struct is []. MATLAB objects (strings, tables, function handles, …) cannot be read; reading one raises an error naming its class.

Version 4 to 7 files are read with scipy, version 7.3 files (HDF5) with h5py; either way a variable is read when it is first read or listed. Opening a version 4 to 7 file reads only its names, unless scipy cannot list it (a file holding MATLAB objects), when it is read whole.

Parameters:

path (str | Path) – The mat file.

property names: list[str]#

The names of the file’s variables, in the file’s order.

entries(recursive=True)#

Lists the variables with their shape and class, without reading their data.

Parameters:

recursive (bool) – Also list the fields of structs and the elements of cells and struct arrays (those with at most MAX_LISTED_ELEMENTS elements), after the entry that holds them.

Returns:

The entries, in the file’s order.

Return type:

list[MatlabEntry]

entry(path)#

The shape and class of the value at a path, without reading its data.

Parameters:

path (str) – A variable name, optionally followed by field, {i} and (i) steps as in MatlabFile.read.

Returns:

MatlabEntry – Its shape and class.

Return type:

MatlabEntry

read(path)#

Reads a variable, or a struct field or cell element inside one.

Parameters:

path (str) – A variable name, optionally followed by field, {i} and (i) steps as in MatlabEntry.path.

Returns:

The value, converted as described in the class.

Raises:
  • KeyError – If there is nothing at the path.

  • ValueError – If the value is a MATLAB object, or holds one.

Return type:

MatlabValue

read_array(path)#

Reads a numeric or logical array; raises ValueError for any other value.

Parameters:

path (str) – As in MatlabFile.read.

Returns:

The array, with MATLAB’s shape.

Raises:

ValueError – If the value is not a numeric or logical array.

Return type:

ndarray

larmor.io.Progress#

alias of Callable[[int, int], None]

exception larmor.io.ReadCancelledError#

Raised by a progress callback to stop a read; the read then raises it too.

larmor.io.file_kind(path)#

Whether a file is a volume or a tractogram, from its extension.

Parameters:

path (str | Path) – The file path; only its name is read.

Returns:

“volume” or “tractogram”.

Raises:

ValueError – If the extension is neither, listing both kinds’ extensions.

Return type:

Literal[‘volume’, ‘tractogram’]

larmor.io.has_mif_gradients(path)#

Checks whether a MIF file’s header has a gradient table (dw_scheme).

Only the presence of the table is checked, not whether it can be read.

Parameters:

path (str | Path) – The MIF file.

Returns:

True if the header has a dw_scheme.

Raises:

ValueError – If the file is not a MIF file Larmor can read.

Return type:

bool

larmor.io.iter_tractogram(path, *, batch_size=10000, reference=None)#

Reads a tractogram batch by batch, for files too large to hold in memory.

The file is read in chunks of a fixed number of bytes and its streamlines are handed out in order, batch_size at a time; a streamline is never split between batches. Memory stays at about two batches while one is built, plus the one the caller holds and one chunk (16 MB), whatever the file size. Joined in order, the batches are the tractogram load_tractogram returns, with the same data, point_data and streamline_data (a TRK’s scalars and properties) and reference in each batch. A file without streamlines gives one empty batch.

Parameters:
  • path (str | Path) – An uncompressed tck or trk file.

  • batch_size (int) – The most streamlines per batch; every batch but the last has exactly this many.

  • reference (Grid | None) – As for load_tractogram.

Returns:

An iterator over the batches.

Raises:

ValueError – At the call, if the file is not tck or trk, is compressed, or batch_size is less than 1. While iterating, if the file cannot be read as its format.

Return type:

Iterator[Tractogram]

larmor.io.load_dwi(path, bvals=None, bvecs=None, *, frame='fsl')#

Loads a diffusion volume and its gradients.

A MIF file with a gradient table in its header (dw_scheme) provides it. A NIfTI file, or a MIF file without one, needs the bvals and bvecs files; they are never looked for by name. Files given for a MIF file that has a table override it, with a warning.

Parameters:
  • path (str | Path) – The volume file.

  • bvals (str | Path | None) – The b-values file, or None.

  • bvecs (str | Path | None) – The b-vectors file, in frame, or None. Give both files or neither.

  • frame (Literal['fsl', 'world']) – The frame of the bvecs file: “fsl” (converted with the volume file’s affine) or “world”. A MIF header is always in world coordinates.

Returns:

The volume as read, and its gradient table in world coordinates.

Return type:

tuple[Volume, GradientTable]

Giving only one of the two files is reported first; then the volume is read, so a missing volume is reported before any problem with the gradients.

Raises:
  • FileNotFoundError – If the volume or a gradient file does not exist.

  • ValueError – If only one of the two files is given, there is no gradient table (no files, and no table in the header), a file cannot be read, or the table does not have one entry per volume.

larmor.io.load_grid(path)#

Reads only the grid of a file, without the data.

Parameters:

path (str | Path) – A volume file (nii, nii.gz, mif, mif.gz or mih), whose header is read, or an MRIToolkit DTI or DKI fit (mat), whose grid is read as read_mritoolkit_grid reads it.

Returns:

The grid – the spatial shape (X, Y, Z) and the affine.

Raises:

ValueError – If the extension is not supported, or the file cannot be read as that format.

Return type:

Grid

larmor.io.load_header(path)#

Reads only the header of a volume file, without the data.

Parameters:

path (str | Path) – A nii, nii.gz, mif, mif.gz or mih file.

Returns:

The grid, and the full shape of the data – (X, Y, Z) or (X, Y, Z, N).

Raises:

ValueError – If the extension is not supported, or the file cannot be read as that format.

Return type:

tuple[Grid, tuple[int, …]]

larmor.io.load_surface(path, *, values=())#

Reads a surface, and optionally files of values per vertex for it.

Parameters:
  • path (str | Path) – A GIfTI gii file, or a FreeSurfer surface such as lh.white (recognised by its first bytes, since it has no extension).

  • values (str | Path | Sequence[str | Path]) – A file, or files, of values per vertex added to vertex_data: FreeSurfer files named after the part after the hemisphere (lh.thickness gives “thickness”), and GIfTI files by the names inside them (unnamed arrays by their file, the same way).

Returns:

The surface, in scanner coordinates when the file allows it.

Raises:

ValueError – If a file is not a supported surface or values file, a name appears twice, or a values file does not have one entry per vertex.

Return type:

Surface

larmor.io.load_tractogram(path, *, reference=None, on_progress=None, max_streamlines=None, seed=None)#

Reads a tractogram, in the format given by the file’s extension.

Parameters:
  • path (str | Path) – A tck, trk, vtk or fib file, each also gzipped (gz), or MRIToolkit’s tractography in a mat file (read_mritoolkit_tracts; other mat files are refused).

  • reference (Grid | None) – The grid of the image the tractogram belongs to. A TRK uses it when it has no vox_to_ras and checks it otherwise; TCK and VTK files store no grid, so it becomes the tractogram’s reference as given. A mat file needs it to place its points.

  • on_progress (Callable[[int, int], None] | None) – Called as the file is read, with the bytes read so far and the file’s size on disk (compressed bytes for a gzip file). Raise ReadCancelledError in it to stop the read.

  • max_streamlines (int | None) – If the file has more streamlines, keep a random subset of this size, chosen after the whole file is read (Tractogram.subsample). None keeps all.

  • seed (int | None) – Seed of the random subset; the same seed gives the same streamlines.

Returns:

The tractogram.

Raises:
  • ValueError – If the extension is not supported, the file cannot be read as that format, or max_streamlines is negative.

  • ReadCancelledError – If on_progress raises it.

Return type:

Tractogram

larmor.io.load_tractogram_subset(path, max_streamlines, *, seed=None, reference=None, on_progress=None)#

Reads a tractogram, keeping at most max_streamlines, and says which.

The file is read whole; if it has more streamlines, a random subset of max_streamlines is kept, the same as load_tractogram keeps, so values stored per streamline of the whole file (a TSF or weights file) can be matched to it.

Parameters:
  • path (str | Path) – A tck, trk, vtk or fib file, each also gzipped (gz).

  • max_streamlines (int) – The most streamlines to keep.

  • seed (int | None) – Seed of the random subset; the same seed gives the same streamlines.

  • reference (Grid | None) – As in load_tractogram.

  • on_progress (Callable[[int, int], None] | None) – As in load_tractogram.

Returns:

The tractogram; the (S,) int64 indices of its streamlines in the file, ascending (all of them if none was dropped); and the number of streamlines in the file.

Raises:
  • ValueError – If the extension is not supported, the file cannot be read as that format, or max_streamlines is negative.

  • ReadCancelledError – If on_progress raises it.

Return type:

tuple[Tractogram, ndarray, int]

larmor.io.load_volume(path, *, on_progress=None)#

Reads a volume, in the format given by the file’s extension.

Parameters:
  • path (str | Path) – A nii, nii.gz, mif, mif.gz or mih file.

  • on_progress (Callable[[int, int], None] | None) – Called as the file is read, with the bytes read so far and the file’s size on disk (compressed bytes for a gzip file). Raise ReadCancelledError in it to stop the read.

Returns:

The volume.

Raises:
  • ValueError – If the extension is not supported, or the file cannot be read as that format.

  • ReadCancelledError – If on_progress raises it.

Return type:

Volume

larmor.io.open_tractogram_writer(path, *, reference=None)#

Opens a tractogram file to be written batch by batch, by its extension.

Use it as a context manager and call write for each batch; leaving the block normally finishes the file. A file written in batches is byte for byte the one save_tractogram writes for all the streamlines at once.

Parameters:
  • path (str | Path) – A tck or trk file; an existing file is overwritten.

  • reference (Grid | None) – The grid a TRK is written for; TCK does not use it.

Returns:

A TckWriter or TrkWriter.

Raises:

ValueError – If the format cannot be written in batches (compressed files and VTK), or a TRK has no reference grid.

Return type:

BatchWriter

larmor.io.output_files(path)#

Returns every file that save_volume writes for path.

A mih header keeps its data in a dat of the same name, so both must be checked before overwriting (the CLI’s --force).

Parameters:

path (str | Path) – A nii, nii.gz, mif, mif.gz or mih file.

Returns:

The file itself, and for a mih header also its dat data file.

Raises:

ValueError – If the extension is not supported.

Return type:

list[Path]

larmor.io.read_b_matrix(path, *, ref_path=None)#

Reads a b-matrix file written by write_b_matrix.

Assumes Larmor’s layout (N x 6, b * (gx^2, 2 gx gy, 2 gx gz, gy^2, 2 gy gz, gz^2), s/mm^2, world coordinates). Files from other programs (ExploreDTI, TORTOISE, AFNI, …) may use another order, units or frame and are not supported. A b-matrix does not store the sign of a vector: each vector is returned with its first non-zero component positive.

Parameters:
  • path (str | Path) – The b-matrix text file.

  • ref_path (str | Path | None) – A volume whose number of volumes the table must match. Defaults to None, which does not check.

Returns:

GradientTable – The b-values (s/mm^2) and unit b-vectors (world coordinates, RAS+) of the file’s rows.

Raises:

ValueError – If the file is missing, empty or not a table of numbers, if it does not have shape (N, 6), or if ref_path is given and is not 4D or its number of volumes differs from N.

Return type:

GradientTable

larmor.io.read_bvals_bvecs(bvals_path, bvecs_path, *, ref_path=None, frame='fsl')#

Reads bvals and bvecs files into a gradient table in world coordinates.

Parameters:
  • bvals_path (str | Path) – The bvals file.

  • bvecs_path (str | Path) – The bvecs file, (3, N) or (N, 3).

  • ref_path (str | Path | None) – The image the files belong to. Required for “fsl”; when given, its number of volumes is checked. Defaults to None.

  • frame (Literal['fsl', 'world']) – The frame of the bvecs file. Defaults to “fsl”.

Returns:

GradientTable – The table, with its vectors in world coordinates.

Raises:

ValueError – If the files cannot be read or do not match each other or the image, or “fsl” is given without an image.

Return type:

GradientTable

larmor.io.read_lookup_table(path)#

Reads a lookup table in the FreeSurfer or the MRtrix layout.

Each line is an index, one or two names, then the colour: FreeSurfer’s index name R G B A (as in FreeSurferColorLUT.txt) or MRtrix’s index short-name long-name R G B A (as in fs_default.txt for labelconvert). Colours are from 0 to 255; the last column (FreeSurfer’s transparency, MRtrix’s alpha) is ignored, and may be missing. The name kept is the last one, MRtrix’s long name. Blank lines and lines starting with # are skipped; a later line for an index replaces an earlier one.

Parameters:

path (str | Path) – The text file, for example FreeSurfer’s FreeSurferColorLUT.txt.

Returns:

The labels by their index (the value in the parcellation image).

Raises:

ValueError – If the file cannot be read, a line is not a valid entry, or the file holds no entry; the message names the file and the line.

Return type:

dict[int, Label]

larmor.io.read_matlab(path)#

Opens a MATLAB mat file (version 4, 5 to 7, or 7.3) for listing and reading.

Parameters:

path (str | Path) – The mat file.

Returns:

The file, whose variables are read on request.

Raises:

ValueError – If the file is not a MATLAB file.

Return type:

MatlabFile

larmor.io.read_mritoolkit_fit(source)#

Reads MRIToolkit’s DTI or DKI fit (EDTI.PerformDTI_DKIFit) in world space.

The tensor, the kurtosis tensor and the vectors are taken to world coordinates, so the fit compares directly with Larmor’s DTIModel and DKIModel.

Parameters:

source (MatlabSource) – The fit’s mat file, or the file opened with read_matlab.

Returns:

The fit; its grid is the NIfTI image’s the fit was made from.

Raises:

ValueError – If the file is not an MRIToolkit fit (it needs DT, DWI, b and hdr).

Return type:

MRIToolkitFit

larmor.io.read_mritoolkit_frame(reference)#

Reads the (3, 3) matrix taking MRIToolkit’s vectors to world coordinates.

Its columns are the world directions of the NIfTI voxel axes j, i and k of the reference grid; MRIToolkit stores gradients, tensors, eigenvectors and FOD directions in that frame.

Parameters:

reference (Reference) – The grid: a Grid, an MRIToolkit fit, or a NIfTI or MIF file.

Returns:

The (3, 3) matrix, whose columns are those world directions.

Return type:

ndarray

larmor.io.read_mritoolkit_grid(source)#

Reads the image grid of an MRIToolkit fit from the NIfTI header it stores.

Parameters:

source (MatlabSource) – A mat file with the struct hdr (a DTI or DKI fit), or the file already opened with read_matlab.

Returns:

The grid of the NIfTI image the fit was made from.

Raises:

ValueError – If the file has no hdr.

Return type:

Grid

larmor.io.read_mritoolkit_kind(source)#

Reads what kind of MRIToolkit result a mat file holds, from its variables.

Parameters:

source (MatlabSource) – The mat file, or the file opened with read_matlab.

Returns:

“fit” (a DTI or DKI fit – DT and hdr), “fod” (a GRL or mFOD result: a struct with the fields FOD and fractions), “tracts” (Tracts), or None for none of these.

Return type:

str | None

larmor.io.read_mritoolkit_map(source, name)#

Reads one map an MRIToolkit fit stores, as MRIToolkitFit.maps holds it.

Parameters:
  • source (MatlabSource) – The fit’s mat file, or the file opened with read_matlab.

  • name (str) – One of the keys of MAP_VARIABLES: “FA”, “MD”, “AD”, “RD”, “eigenvalues”, “FE” or “b0”.

Returns:

The map on the fit’s grid, float32, 0 outside the fit’s mask (where its tensor is not finite) and where the file has NaN.

Raises:

ValueError – If the name is unknown or the file lacks its variable.

Return type:

Volume

larmor.io.read_mritoolkit_peaks(source, variable, *, reference=None)#

Reads a peaks image in MRIToolkit’s layout and frame, as world peaks.

The image’s last axis holds x, y, z of each peak in MRIToolkit’s frame (the NIfTI voxel axes j, i, k), 3 values per peak; each triplet is taken to world coordinates, as the peaks Larmor writes.

Parameters:
  • source (MatlabSource) – The mat file, or the file opened with read_matlab.

  • variable (str) – The variable holding the peaks image, as path of read_mritoolkit_volume.

  • reference (Reference | None) – The grid the image lies on, as for read_mritoolkit_volume. Defaults to None, the file’s own hdr.

Returns:

The peaks on the reference grid, with 3 values per peak (x, y, z in world coordinates).

Raises:

ValueError – If the image does not hold 3 values per peak.

Return type:

Volume

larmor.io.read_mritoolkit_tracts(source, reference, *, variable='Tracts')#

Reads MRIToolkit’s tractography (Tracts and its per-point values).

Parameters:
  • source (MatlabSource) – The tractography mat file, or the file opened with read_matlab.

  • reference (Reference) – The grid the tracking ran on: a Grid, the MRIToolkit fit (mat) it ran on, or a NIfTI or MIF file of that image. The file stores no grid of its own.

  • variable (str) – The cell of (N, 3) point arrays, in mm along the axes of MRIToolkit’s layout, as Tracts holds them; the per-point values are read only with Tracts.

Returns:

The streamlines in world coordinates, with the reference grid. Each per-point cell (TractFA, TractMD, TractFE, TractsFOD, …) is in point_data under its name without the prefix (FA, MD, FE, FOD), as stored, except two: FA is divided by sqrt(3) to the usual FA, and FE, whose components MRIToolkit stores as absolute values in the frame of the NIfTI voxel axes j, i, k, has its first two swapped, so that on a grid whose axes are the world’s it is in world order (its signs stay lost, and an oblique grid is not corrected). TractL, which holds the number of points of each streamline, is in streamline_data["L"].

Raises:

ValueError – If the file has no Tracts, or the reference cannot be read.

Return type:

Tractogram

larmor.io.read_mritoolkit_volume(source, path, *, reference=None)#

Reads an image of an MRIToolkit mat file as a Volume, its values as stored.

Parameters:
  • source (MatlabSource) – The mat file, or the file opened with read_matlab.

  • path (str) – The variable, or a struct field (GRL_Results.fractions), as in MatlabFile.read: an array whose first three axes are the image’s, or a cell of 3D arrays (such as DT or DWI), stacked along a fourth.

  • reference (Reference | None) – The grid the image lies on: a Grid, an MRIToolkit fit (its hdr), or a NIfTI or MIF file. Defaults to the file’s own hdr.

Returns:

The image in NIfTI voxel order on the reference grid; axes after the third are kept, flattened into one in MATLAB’s order.

Raises:

ValueError – If the value is not an image of the reference grid’s shape, or there is no reference and the file has no hdr.

Return type:

Volume

larmor.io.read_mrtrix_gradients(path, *, ref_path=None)#

Reads an MRtrix gradient table file (b, as given to MRtrix’s -grad).

One row per volume, x y z b: the direction in world coordinates (RAS+), so nothing is converted, and b in s/mm^2. Numbers are separated by spaces, tabs, commas or semicolons; everything from a # on is a comment. Directions that are not unit vectors are normalised as for any GradientTable.

Parameters:
  • path (str | Path) – The gradient file.

  • ref_path (str | Path | None) – The image the table belongs to; when given, its number of volumes is checked. Defaults to None.

Returns:

GradientTable – The table, with its vectors in world coordinates.

Raises:

ValueError – If the file cannot be read, a row is not 4 numbers, or the table does not match the image.

Return type:

GradientTable

References

Follows MRtrix3’s gradient table format (-grad, -export_grad_mrtrix). 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.io.read_streamline_weights(path)#

Reads a streamline weights file, such as those of tcksift2 and tckedit.

The file holds one value per streamline, in the tractogram’s order, either on one row or one per row, separated by whitespace, commas or semicolons. Everything after a # on a line is a comment, and blank lines are skipped. A file with no values gives an empty array.

Parameters:

path (str | Path) – The text file.

Returns:

np.ndarray – (S,) float32, the weights.

Raises:

ValueError – If the file cannot be read, a value is not a number, or the values form a table of several rows and columns; the message names the file and the line.

Return type:

ndarray

References

Reads the weights files of MRtrix3 (tcksift2 output, tckedit -tck_weights_in). 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.io.read_track_timestamp(path)#

Reads the timestamp in the header of a TCK or TSF file, without its data.

A TSF file and its TCK file, or two TSF files, belong together when they hold the same timestamp; pass it to write_tsf to pair new values with a TCK file:

timestamp = read_track_timestamp(“tracks.tck”) write_tsf(values, tractogram.offsets, “fa.tsf”, timestamp=timestamp)

Parameters:

path (str | Path) – A tck or tsf file, also gzipped.

Returns:

The timestamp, or None if the header has none.

Raises:

ValueError – If the file is not a TCK or TSF file.

Return type:

str | None

larmor.io.read_tsf(path, *, tractogram=None, on_progress=None)#

Reads a TSF file (MRtrix track scalar file): one value per streamline point.

The data is a run of values with a NaN after each streamline, read to the end or to an Inf. A last streamline without its closing NaN is dropped with a warning, and a header count that disagrees with the data gives a warning, as for TCK. The values usually belong in tractogram.point_data:

values, _ = read_tsf(“fa.tsf”, tractogram) tractogram.point_data[“fa”] = values

Parameters:
  • path (str | Path) – The tsf file.

  • tractogram (Tractogram | None) – The tractogram the values belong to. When given, the file must have one value per point of each of its streamlines. Defaults to None.

  • on_progress (Callable[[int, int], None] | None) – Called as the file is read, see load_volume.

Returns:

The (P,) values, float32 or float64 as stored, and the (S + 1,) int64 offsets: streamline s has values[offsets[s]:offsets[s + 1]].

Raises:
  • ValueError – If the file is not a TSF file Larmor can read, or does not match tractogram.

  • ReadCancelledError – If on_progress raises it.

Return type:

tuple[ndarray, ndarray]

References

Follows MRtrix3’s track scalar files (tcksample, tsfinfo). 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.io.save_surface(surface, path)#

Writes a surface: GIfTI for a gii name, FreeSurfer for any other name.

A FreeSurfer surface holds the mesh only; write values per vertex with write_freesurfer_values, or save as gii to keep them.

Parameters:
  • surface (Surface) – The surface to write.

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

Raises:

ValueError – If the name ends in a volume or tractogram extension.

larmor.io.save_tractogram(tractogram, path, *, reference=None)#

Writes a tractogram, in the format given by the file’s extension.

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

  • path (str | Path) – A tck, trk, vtk or fib file, each also gzipped (gz). VTK and FIB are written in binary.

  • reference (Grid | None) – The grid a TRK is written for; defaults to the tractogram’s own reference. TCK and VTK do not use it.

Raises:

ValueError – If the extension is not supported, or the tractogram cannot be written as that format (a TRK without any reference grid).

larmor.io.save_volume(volume, path, *, gradients=None)#

Writes a volume, in the format given by the file’s extension.

Parameters:
  • volume (Volume) – The volume to write.

  • path (str | Path) – A nii, nii.gz, mif, mif.gz or mih file; a mih also writes a dat (see output_files).

  • gradients (GradientTable | None) – The volume’s gradient table, written into the header. Only MIF files can hold one, and only for a 4D volume.

Raises:

ValueError – If the extension is not supported, gradients is given for a NIfTI file or a 3D volume, or does not have one entry per volume.

larmor.io.write_b_matrix(gtab, path, *, ref_path=None)#

Writes the table’s b-matrix as an Larmor b-matrix file.

One row per volume: b * (gx^2, 2 gx gy, 2 gx gz, gy^2, 2 gy gz, gz^2), in s/mm^2, in world coordinates (RAS+).

Parameters:
  • gtab (GradientTable) – The table to write.

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

  • ref_path (str | Path | None) – A volume whose number of volumes the table must match. Defaults to None, which does not check.

Raises:

ValueError – If ref_path is given and is not 4D or its number of volumes differs from the table’s.

larmor.io.write_bvals_bvecs(gtab, bvals_path, bvecs_path, *, ref_path=None, frame='fsl')#

Writes a gradient table as bvals and bvecs files: one row, and 3 rows.

Parameters:
  • gtab (GradientTable) – The table to write.

  • bvals_path (str | Path) – The bvals file.

  • bvecs_path (str | Path) – The bvecs file.

  • ref_path (str | Path | None) – The image written alongside. Required for “fsl”; when given, its number of volumes is checked. Defaults to None.

  • frame (Literal['fsl', 'world']) – The frame to write the bvecs in. Defaults to “fsl”.

Raises:

ValueError – If the table does not match the image, or “fsl” is given without an image.

larmor.io.write_mrtrix_gradients(gtab, path, *, ref_path=None)#

Writes a gradient table as an MRtrix gradient file (b).

One row per volume, x y z b, with the unit direction in world coordinates (RAS+) and b in s/mm^2, in full precision so that the table reads back unchanged.

Parameters:
  • gtab (GradientTable) – The table to write.

  • path (str | Path) – The gradient file; an existing file is overwritten.

  • ref_path (str | Path | None) – The image written alongside; when given, its number of volumes is checked. Defaults to None.

Raises:

ValueError – If the table does not match the image.

References

Follows MRtrix3’s gradient table format (-grad, -export_grad_mrtrix). 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.io.write_streamline_weights(weights, path, *, append=False)#

Writes streamline weights as text, for read_streamline_weights or MRtrix.

The values are written as float32 with 9 significant digits, which gives back every float32 exactly, each followed by one space, all on one row with no newline. Appending continues the same row, so a file written in batches reads back as one array.

Parameters:
  • weights (ndarray) – (S,) the weight of each streamline, in the tractogram’s order.

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

  • append (bool) – If True, add the values at the end of the file, which must be one this function wrote (one row ending in a space); otherwise overwrite it.

Raises:

ValueError – If weights is not one-dimensional.

References

Writes the layout of MRtrix3’s tckedit -tck_weights_out. 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.io.write_tsf(values, offsets, path, *, timestamp=None)#

Writes values per streamline point as a TSF file (MRtrix track scalar file).

The values are written in order with a NaN after each streamline, little-endian: floats of 8 or more bytes (float64 of either byte order, longdouble) as Float64, all others as Float32. For a point_data entry:

write_tsf(tractogram.point_data[“fa”], tractogram.offsets, “fa.tsf”)

Parameters:
  • values (ndarray) – (P,) one value per point, all finite.

  • offsets (ndarray) – (S + 1,) where each streamline starts, as Tractogram.offsets.

  • path (str | Path) – The tsf file; an existing file is overwritten.

  • timestamp (str | None) – Written as the header’s timestamp, which MRtrix uses to pair a TSF with its TCK file (tsfvalidate) and two TSF files with each other (tsfdivide, tsfmult, which refuse a file without one). Pass the same value as the timestamp of write_tck or TckWriter, or the one read_track_timestamp reads from an existing TCK file. Defaults to None, no timestamp.

Raises:

ValueError – If values is not 1-D, real (float, integer or bool) and finite, offsets do not match it, or timestamp has a ‘#’ or a line break.

References

Follows MRtrix3’s track scalar files (tcksample, tsfinfo). 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.