larmor.io#
Loading and saving the core data types by path, and the gradient files.
The surface format chosen by the file name ending; other surfaces are FreeSurfer's. |
|
The tractogram formats, and the file name endings that select each. |
|
The volume formats, and the file name endings that select each. |
|
A tractogram file written batch by batch, finished by |
|
A DTI or DKI fit read from MRIToolkit's |
|
One variable of a |
|
A |
|
Raised by a progress callback to stop a read; the read then raises it too. |
|
Whether a file is a volume or a tractogram, from its extension. |
|
Checks whether a MIF file's header has a gradient table ( |
|
Reads a tractogram batch by batch, for files too large to hold in memory. |
|
Loads a diffusion volume and its gradients. |
|
Reads only the grid of a file, without the data. |
|
Reads only the header of a volume file, without the data. |
|
Reads a surface, and optionally files of values per vertex for it. |
|
Reads a tractogram, in the format given by the file's extension. |
|
Reads a tractogram, keeping at most |
|
Reads a volume, in the format given by the file's extension. |
|
Opens a tractogram file to be written batch by batch, by its extension. |
|
Returns every file that |
|
Reads a b-matrix file written by |
|
Reads bvals and bvecs files into a gradient table in world coordinates. |
|
Reads a lookup table in the FreeSurfer or the MRtrix layout. |
|
Opens a MATLAB |
|
Reads MRIToolkit's DTI or DKI fit ( |
|
Reads the (3, 3) matrix taking MRIToolkit's vectors to world coordinates. |
|
Reads the image grid of an MRIToolkit fit from the NIfTI header it stores. |
|
Reads what kind of MRIToolkit result a |
|
Reads one map an MRIToolkit fit stores, as |
|
Reads a peaks image in MRIToolkit's layout and frame, as world peaks. |
|
Reads MRIToolkit's tractography ( |
|
Reads an image of an MRIToolkit |
|
Reads an MRtrix gradient table file ( |
|
Reads a streamline weights file, such as those of tcksift2 and tckedit. |
|
Reads the |
|
Reads a TSF file (MRtrix track scalar file): one value per streamline point. |
|
Writes a surface: GIfTI for a |
|
Writes a tractogram, in the format given by the file's extension. |
|
Writes a volume, in the format given by the file's extension. |
|
Writes the table's b-matrix as an Larmor b-matrix file. |
|
Writes a gradient table as bvals and bvecs files: one row, and 3 rows. |
|
Writes a gradient table as an MRtrix gradient file ( |
|
Writes streamline weights as text, for |
|
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
matfile, 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.
- 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.
- mask#
The fitted voxels (where the file’s tensor is finite), (X, Y, Z) bool.
- 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’sDWIB0), each when the file has what it needs.- Type:
- class larmor.io.MatlabEntry(path, shape, matlab_class, sparse=False)#
One variable of a
matfile, or a struct field or cell inside one.- path#
Where it is: a variable name, then
fieldfor a struct field,{i}for a cell element and(i)for a struct array element, with MATLAB’s 1-based linear indices (for exampleresults.FOD,Tracts{3}).- Type:
- class larmor.io.MatlabFile(path)#
A
matfile: 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’sa(i+1, j+1, k+1)(MATLAB stores arrays column-major, so they are Fortran-ordered); complex arrays as complex arrays; sparse matrices asscipy.sparse.csc_array; a char row asstrand 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 byentries. 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.
- 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:
- 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 inMatlabFile.read.- Returns:
MatlabEntry – Its shape and class.
- Return type:
- 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 inMatlabEntry.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:
- 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:
- 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:
- Returns:
True if the header has a
dw_scheme.- Raises:
ValueError – If the file is not a MIF file Larmor can read.
- Return type:
- 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_sizeat 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 tractogramload_tractogramreturns, with the same data,point_dataandstreamline_data(a TRK’s scalars and properties) and reference in each batch. A file without streamlines gives one empty batch.- Parameters:
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
tckortrk, is compressed, or batch_size is less than 1. While iterating, if the file cannot be read as its format.- Return type:
- 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:
- Returns:
The volume as read, and its gradient table in world coordinates.
- Return type:
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.gzormih), whose header is read, or an MRIToolkit DTI or DKI fit (mat), whose grid is read asread_mritoolkit_gridreads 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:
- larmor.io.load_header(path)#
Reads only the header of a volume file, without the data.
- larmor.io.load_surface(path, *, values=())#
Reads a surface, and optionally files of values per vertex for it.
- Parameters:
path (str | Path) – A GIfTI
giifile, or a FreeSurfer surface such aslh.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.thicknessgives “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:
- 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,vtkorfibfile, each also gzipped (gz), or MRIToolkit’s tractography in amatfile (read_mritoolkit_tracts; othermatfiles 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
referenceas given. Amatfile 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:
- 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_streamlinesis kept, the same asload_tractogramkeeps, 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,vtkorfibfile, 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:
- larmor.io.load_volume(path, *, on_progress=None)#
Reads a volume, in the format given by the file’s extension.
- Parameters:
- 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:
- 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
writefor each batch; leaving the block normally finishes the file. A file written in batches is byte for byte the onesave_tractogramwrites for all the streamlines at once.- Parameters:
- Returns:
A
TckWriterorTrkWriter.- Raises:
ValueError – If the format cannot be written in batches (compressed files and VTK), or a TRK has no reference grid.
- Return type:
- larmor.io.output_files(path)#
Returns every file that
save_volumewrites forpath.A
mihheader keeps its data in adatof the same name, so both must be checked before overwriting (the CLI’s--force).- Parameters:
- Returns:
The file itself, and for a
mihheader also itsdatdata file.- Raises:
ValueError – If the extension is not supported.
- Return type:
- 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:
- 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_pathis given and is not 4D or its number of volumes differs from N.- Return type:
- 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:
- 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:
- 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 inFreeSurferColorLUT.txt) or MRtrix’sindex short-name long-name R G B A(as infs_default.txtforlabelconvert). 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:
- larmor.io.read_matlab(path)#
Opens a MATLAB
matfile (version 4, 5 to 7, or 7.3) for listing and reading.- Parameters:
- Returns:
The file, whose variables are read on request.
- Raises:
ValueError – If the file is not a MATLAB file.
- Return type:
- 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
DTIModelandDKIModel.- Parameters:
source (MatlabSource) – The fit’s
matfile, or the file opened withread_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,bandhdr).- Return type:
- 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:
- larmor.io.read_mritoolkit_grid(source)#
Reads the image grid of an MRIToolkit fit from the NIfTI header it stores.
- Parameters:
source (MatlabSource) – A
matfile with the structhdr(a DTI or DKI fit), or the file already opened withread_matlab.- Returns:
The grid of the NIfTI image the fit was made from.
- Raises:
ValueError – If the file has no
hdr.- Return type:
- larmor.io.read_mritoolkit_kind(source)#
Reads what kind of MRIToolkit result a
matfile holds, from its variables.- Parameters:
source (MatlabSource) – The
matfile, or the file opened withread_matlab.- Returns:
“fit” (a DTI or DKI fit –
DTandhdr), “fod” (a GRL or mFOD result: a struct with the fieldsFODandfractions), “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.mapsholds it.- Parameters:
source (MatlabSource) – The fit’s
matfile, or the file opened withread_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:
- 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
matfile, or the file opened withread_matlab.variable (str) – The variable holding the peaks image, as
pathofread_mritoolkit_volume.reference (Reference | None) – The grid the image lies on, as for
read_mritoolkit_volume. Defaults to None, the file’s ownhdr.
- 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:
- larmor.io.read_mritoolkit_tracts(source, reference, *, variable='Tracts')#
Reads MRIToolkit’s tractography (
Tractsand its per-point values).- Parameters:
source (MatlabSource) – The tractography
matfile, or the file opened withread_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
Tractsholds them; the per-point values are read only withTracts.
- Returns:
The streamlines in world coordinates, with the reference grid. Each per-point cell (
TractFA,TractMD,TractFE,TractsFOD, …) is inpoint_dataunder 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 instreamline_data["L"].- Raises:
ValueError – If the file has no
Tracts, or the reference cannot be read.- Return type:
- larmor.io.read_mritoolkit_volume(source, path, *, reference=None)#
Reads an image of an MRIToolkit
matfile as a Volume, its values as stored.- Parameters:
source (MatlabSource) – The
matfile, or the file opened withread_matlab.path (str) – The variable, or a struct field (
GRL_Results.fractions), as inMatlabFile.read: an array whose first three axes are the image’s, or a cell of 3D arrays (such asDTorDWI), 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 ownhdr.
- 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:
- 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 anyGradientTable.- Parameters:
- 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:
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:
- 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:
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
timestampin 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_tsfto pair new values with a TCK file:timestamp = read_track_timestamp(“tracks.tck”) write_tsf(values, tractogram.offsets, “fa.tsf”, timestamp=timestamp)
- Parameters:
- 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:
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:
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
giiname, FreeSurfer for any other name.A FreeSurfer surface holds the mesh only; write values per vertex with
write_freesurfer_values, or save asgiito keep them.- Parameters:
- 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,vtkorfibfile, 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.gzormihfile; amihalso writes adat(seeoutput_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,
gradientsis 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.
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_pathis 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.
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_weightsor 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:
- Raises:
ValueError – If
weightsis 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_dataentry: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
tsffile; 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 thetimestampofwrite_tckorTckWriter, or the oneread_track_timestampreads from an existing TCK file. Defaults to None, no timestamp.
- Raises:
ValueError – If
valuesis not 1-D, real (float, integer or bool) and finite,offsetsdo not match it, ortimestamphas 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.