io#
Input/Output utilities.
Reading and writing of diffusion MRI data, bvals/bvecs, gradients, and related file formats.
Module: io.bids#
Read diffusion data organised following the BIDS specification.
This module implements the small subset of BIDS needed to feed DIPY
workflows: entity parsing, dataset enumeration, resolution of the gradient
and JSON files that belong to a diffusion acquisition (including the
inheritance principle), companion anatomical and fieldmap images, and the
dataset_description.json of a derivative dataset.
It deliberately does not index, query or validate a whole dataset. When
pybids happens to be installed, validate_with_pybids() reports
non-compliant file names as warnings, but discovery never depends on it.
|
One diffusion acquisition resolved from a BIDS dataset. |
|
Split a BIDS file name into its stem and its extension. |
|
Parse the BIDS entities of a file name. |
|
Build a BIDS file name from entities, a suffix and an extension. |
|
Check that |
|
Tell whether a directory looks like the root of a BIDS dataset. |
|
List the subject labels of a BIDS dataset. |
|
List the session labels of one subject. |
|
Apply the BIDS inheritance principle to find applicable files. |
|
Read the JSON metadata that applies to a file. |
|
Find the T1w image of a subject. |
|
Find the EPI fieldmap acquired with the opposite phase encoding. |
|
Collect the acquisition metadata a distortion correction would need. |
|
Warn about file names that the BIDS validator rejects. |
|
Resolve every diffusion acquisition of a BIDS dataset. |
|
Build the output directory of a run inside a derivative dataset. |
|
Write the |
Module: io.dpy#
A class for handling large tractography datasets.
It is built using the h5py which in turn implement key features of the HDF5 (hierarchical data format) API [1].
References#
|
Module: io.gradients#
|
Read b-values and b-vectors from disk. |
Module: io.image#
|
Load only the data array from a nifti file. |
|
Load data and other information from a nifti file. |
|
Save a data array into a nifti file. |
|
Save Quality Assurance metrics. |
Module: io.peaks#
|
Load a PeaksAndMetrics HDF5 file (PAM5). |
|
Save all important attributes of object PeaksAndMetrics in a PAM5 file (HDF5). |
|
Save SH, directions, indices and values of peaks to Nifti. |
|
Return SH, directions, indices and values of peaks to pam5. |
|
Convert diffusion tensor to pam5. |
Module: io.pickles#
Load and save pickles
|
Save dix to fname as pickle. |
|
Load object from pickle file fname. |
Module: io.stateful_surface#
|
Class for stateful representation of meshes and lines Object designed to be identical no matter the file format (gii, vtk, ply, stl, obj, pial). |
|
Convert vertices and triangles to a polyxios PolyData. |
Module: io.stateful_tractogram#
|
Class for stateful representation of collections of streamlines Object designed to be identical no matter the file format (trk, tck, vtk, fib, dpy). |
Module: io.streamline#
|
Convert a list of lines to a polyxios PolyData. |
|
Get the lines of a polyxios PolyData as a list of coordinate arrays. |
|
Save streamlines as polydata to a supported format file. |
|
Load streamlines from polydata. |
|
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Generate a loading function that performs a file extension check to restrict the user to a single file format. |
|
Generate a saving function that performs a file extension check to restrict the user to a single file format. |
|
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy) |
|
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy) |
Module: io.surface#
|
Load a polydata from a supported format file. |
|
Save a polydata to a supported format file. |
|
Get the (n_vertices, 3) vertex coordinates of a polyxios PolyData. |
|
Get the (n_triangles, 3) vertex indices of a polyxios PolyData. |
|
Get every per-vertex array of a polyxios PolyData, keyed by name. |
|
Load the stateful surface from any format (vtk/vtp/obj/stl/ply/gii/pial) |
|
Save the stateful surface to any format (vtk/vtp/obj/stl/ply/gii/pial) |
|
Load pial file. |
|
Save pial file. |
|
Load gifti file. |
|
Save gifti file. |
|
Apply the freesurfer transform to the vertices to bring them to RASMM space or to bring them back to the original space. |
Module: io.utils#
Utility functions for file formats
|
Enum to simplify future change to convention |
|
Enum to simplify future change to convention |
|
Returns a Nifti1Image with a symmetric matrix intent |
|
Reshape the input to have 5 dimensions. |
|
Check whether an array has a structured NIfTI |
|
Check whether a plain numeric array has RGB-compatible shape and values. |
|
Convert a structured RGB/RGBA array to a plain numeric array. |
|
Create a nifti-compliant directional-encoded color FA image. |
|
Convert a nifti-compliant directional-encoded color FA image into a nifti image with RGB encoded in floating point resolution. |
|
Validate basic data type and value of spatial attribute. |
|
Get the spatial attributes of the given data file. |
|
Compare the spatial attributes of the data in the input files. |
|
Write a standard trk/tck header from spatial attribute |
|
Write a standard nifti header from spatial attribute |
|
Saves the given input dataframe to .h5 file |
|
Helper function that handles inputs that can be paths, nifti img or arrays |
|
Recursively compare two dictionaries or lists for matching structure and dtypes. |
|
Split the filename and its extension(s). |
Module: io.vtk#
Deprecated. Polydata IO now lives beside the formats that use it.
VTK formats (.vtk, .vtp, .fib) are handled directly by dipy.io.streamline
for tractograms and dipy.io.surface for surfaces, both through polyxios.
This module only re-exports them and is removed in DIPY 2.0.
DWIRun#
- class dipy.io.bids.DWIRun(root: str, dwi: str, bval: str | None = None, bvec: str | None = None, sidecar: str | None = None, metadata: dict = <factory>, t1w: str | None = None, fmap_epi: str | None = None, fmap_metadata: dict = <factory>, entities: dict = <factory>)[source]#
Bases:
objectOne diffusion acquisition resolved from a BIDS dataset.
Instances compare by value and hash on
rootanddwi, so they can be used as dictionary keys or set members despite their dict fields.- Attributes:
- rootstr
Absolute path of the BIDS dataset root.
- dwistr
Absolute path of the DWI NIfTI file.
- bvalstr or None
Absolute path of the b-values file, or None when absent.
- bvecstr or None
Absolute path of the b-vectors file, or None when absent.
- sidecarstr or None
Absolute path of the nearest JSON sidecar, or None when absent.
- metadatadict
Merged JSON sidecar contents, nearest file winning.
- t1wstr or None
Absolute path of the T1w image chosen for this run.
- fmap_epistr or None
Absolute path of the opposite phase-encoding EPI fieldmap.
- fmap_metadatadict
Merged JSON sidecar contents of
fmap_epi.- entitiesdict
Entity key to label mapping, e.g.
{"sub": "01", "dir": "AP"}.
- property is_complete#
bool : True when both gradient files were resolved.
- property label#
str : Entity chain identifying the run, e.g.
sub-01_run-2.
- property relative_dir#
str : Dataset-relative directory of the run, e.g.
sub-01/dwi.
- property session#
str or None : Session label, without the
ses-prefix.
- property sort_key#
tuple : Ordering key over subject, session, acquisition and run.
- property subject#
str : Subject label, without the
sub-prefix.
split_extension#
parse_entities#
- dipy.io.bids.parse_entities(*, filename)[source]#
Parse the BIDS entities of a file name.
Unknown entity keys are kept verbatim so that a dataset using entities DIPY does not know about still round-trips.
- Parameters:
- filenamestr or Path
File name or path, e.g.
sub-01_ses-1_dir-AP_dwi.nii.gz.
- Returns:
- dict
Entity keys mapped to their labels, plus
suffixandextensionwhen the name carries them.
Examples
>>> from dipy.io.bids import parse_entities >>> sorted(parse_entities(filename="sub-01_dir-AP_dwi.nii.gz").items()) [('dir', 'AP'), ('extension', '.nii.gz'), ('sub', '01'), ('suffix', 'dwi')]
build_entity_name#
- dipy.io.bids.build_entity_name(*, entities, suffix, extension)[source]#
Build a BIDS file name from entities, a suffix and an extension.
- Parameters:
- entitiesdict
Entity keys mapped to their labels.
suffixandextensionkeys, if present, are ignored in favour of the arguments.- suffixstr
BIDS suffix, e.g.
dwi,dwimapormask.- extensionstr
Extension including the leading dot, e.g.
.nii.gz.
- Returns:
- str
File name with entities in the canonical BIDS order, unknown keys appended alphabetically.
Examples
>>> from dipy.io.bids import build_entity_name >>> build_entity_name(entities={"sub": "01", "desc": "FA"}, ... suffix="dwimap", extension=".nii.gz") 'sub-01_desc-FA_dwimap.nii.gz'
validate_dataset#
- dipy.io.bids.validate_dataset(*, root, require_description=True)[source]#
Check that
rootlooks like a BIDS dataset.- Parameters:
- rootstr or Path
Candidate dataset root.
- require_descriptionbool, optional
If True, a missing
dataset_description.jsonis an error rather than a warning.
- Returns:
- dict
Parsed
dataset_description.json, or an empty dict when the file is absent andrequire_descriptionis False.
- Raises:
- ValueError
If
rootdoes not exist, is not a directory, holds no subject directory, or carries a malformed or (when required) missingdataset_description.json.
looks_like_dataset#
list_subjects#
list_sessions#
- dipy.io.bids.list_sessions(*, root, subject)[source]#
List the session labels of one subject.
- Parameters:
- rootstr or Path
Dataset root.
- subjectstr
Subject label, with or without the
sub-prefix.
- Returns:
- list of str
Sorted session labels without the
ses-prefix, empty when the subject has no session level.
inherited_files#
- dipy.io.bids.inherited_files(*, root, path, suffix, extension)[source]#
Apply the BIDS inheritance principle to find applicable files.
A candidate applies to
pathwhen its entities are a subset of those ofpathand its suffix and extension match.- Parameters:
- rootstr or Path
Dataset root. The walk never goes above it.
- pathstr or Path
File the candidates should apply to.
- suffixstr
BIDS suffix the candidates must carry, e.g.
dwi.- extensionstr
Extension the candidates must carry, e.g.
.json.
- Returns:
- list of str
Absolute paths of the applicable files, nearest first. Within one directory level, the file matching the most entities comes first.
read_sidecar#
- dipy.io.bids.read_sidecar(*, root, path)[source]#
Read the JSON metadata that applies to a file.
The inheritance chain is merged from the most distant file to the nearest one, so that nearer keys win. Within one directory level, the file matching the most entities is merged last and wins.
- Parameters:
- rootstr or Path
Dataset root.
- pathstr or Path
File whose metadata is wanted, e.g. a DWI NIfTI file.
- Returns:
- sidecarstr or None
Absolute path of the nearest JSON file, None when there is none.
- metadatadict
Merged metadata, empty when there is no JSON file.
find_t1w#
- dipy.io.bids.find_t1w(*, root, entities)[source]#
Find the T1w image of a subject.
Preference goes to the same session, then to the fewest extra entities, then to a name without a
desc-entity, then to the first in lexicographic order. A T1w of another session is used, with a warning, only when the session of the run has none.- Parameters:
- rootstr or Path
Dataset root.
- entitiesdict
Entities of the diffusion run, used for the subject and session.
- Returns:
- str or None
Absolute path of the chosen T1w image, None when the subject has none.
find_opposite_pe_fmap#
- dipy.io.bids.find_opposite_pe_fmap(*, root, dwi_path, dwi_metadata, entities)[source]#
Find the EPI fieldmap acquired with the opposite phase encoding.
Candidates are ranked by three rules, in order: the fieldmap declares the DWI file in
IntendedFor; it shares theacq-entity and carries the oppositedir-entity; itsPhaseEncodingDirectionis the opposite of the DWI one. The last two rules skip a fieldmap whoseIntendedForis set but lists no diffusion image, since it was acquired for another modality (e.g. a BOLD run), and try a fieldmap withoutIntendedForbefore one declared for other diffusion runs only. Falling back on the latter logs a warning.- Parameters:
- rootstr or Path
Dataset root.
- dwi_pathstr or Path
Absolute path of the diffusion file.
- dwi_metadatadict
Metadata of the diffusion file.
- entitiesdict
Entities of the diffusion file.
- Returns:
- fmapstr or None
Absolute path of the chosen fieldmap.
- metadatadict
Merged metadata of the chosen fieldmap, empty when none was found.
phase_encoding_info#
validate_with_pybids#
- dipy.io.bids.validate_with_pybids(*, root, paths)[source]#
Warn about file names that the BIDS validator rejects.
Does nothing when
bids_validator, which ships withpybids, is not installed. Discovery never depends on this check.- Parameters:
- rootstr or Path
Dataset root the paths are relative to.
- pathssequence of str
Absolute paths to check.
- Returns:
- list of str
Dataset-relative paths the validator rejected.
find_dwi_runs#
- dipy.io.bids.find_dwi_runs(*, root, participant_label=None, session_label=None, acquisition_label=None, run_label=None, require_gradients=False, validate=True)[source]#
Resolve every diffusion acquisition of a BIDS dataset.
- Parameters:
- rootstr or Path
Dataset root.
- participant_labelsequence of str, optional
Subject labels to keep, with or without the
sub-prefix. None keeps every subject.- session_labelsequence of str, optional
Session labels to keep, with or without the
ses-prefix.- acquisition_labelsequence of str, optional
acq-labels to keep.- run_labelsequence of str, optional
run-labels to keep. Numeric labels match by value, so1selectsrun-01.- require_gradientsbool, optional
If True, runs with a missing b-value or b-vector file are dropped instead of being returned with None.
- validatebool, optional
If True and
pybidsis installed, warn about file names the BIDS validator rejects.
- Returns:
- list of DWIRun
Runs sorted by subject, session, acquisition and run. When both a
.nii.gzand a.niifile share a name, only the.nii.gzone is kept.
derivative_path#
- dipy.io.bids.derivative_path(*, deriv_root, run, datatype='dwi')[source]#
Build the output directory of a run inside a derivative dataset.
- Parameters:
- deriv_rootstr or Path
Root of the derivative dataset.
- runDWIRun
Resolved diffusion acquisition.
- datatypestr, optional
BIDS datatype directory to write into.
- Returns:
- str
Absolute path of
<deriv_root>/sub-X[/ses-Y]/<datatype>.
write_dataset_description#
- dipy.io.bids.write_dataset_description(*, path, source_datasets=(), name='dipy', pipeline_name=None, bids_version='1.9.0')[source]#
Write the
dataset_description.jsonof a derivative dataset.- Parameters:
- pathstr or Path
Directory to write into. Created when absent.
- source_datasetssequence of str, optional
Roots of the raw datasets the derivatives were computed from. The first one is also declared as
rawinDatasetLinks, so thatbids:raw:<path>URIs in derivative sidecars resolve to it.- namestr, optional
Dataset name.
- pipeline_namestr, optional
Name of the pipeline, reported in
GeneratedBy.- bids_versionstr, optional
BIDS version the description claims to follow.
- Returns:
- str
Absolute path of the file that was written.
Dpy#
- class dipy.io.dpy.Dpy(fname, *, mode='r', compression=0)[source]#
Bases:
objectMethods
close()Close the Dpy file descriptor.
Read one track from the Dpy file at the current position.
Read the entire tractography dataset from the Dpy file.
read_tracksi(indices)Read tracks with specific indices from the Dpy file.
version()Return the version of the Dpy file.
write_track(track)Write a single track to the Dpy file.
write_tracks(tracks)Write multiple tracks to the Dpy file.
- read_track()[source]#
Read one track from the Dpy file at the current position.
- Returns:
- trackndarray (N, 3)
A single streamline.
- read_tracks()[source]#
Read the entire tractography dataset from the Dpy file.
- Returns:
- tracksStreamlines
The entire set of streamlines in the file.
- read_tracksi(indices)[source]#
Read tracks with specific indices from the Dpy file.
- Parameters:
- indiceslist or array-like
The indices of the tracks to read.
- Returns:
- tracksStreamlines
The streamlines corresponding to the given indices.
- version()[source]#
Return the version of the Dpy file.
- Returns:
- versionstr
The version string stored in the file.
read_bvals_bvecs#
- dipy.io.gradients.read_bvals_bvecs(fbvals, fbvecs)[source]#
Read b-values and b-vectors from disk.
- Parameters:
- fbvalsstr or Path
Full path to file with b-values. None to not read bvals.
- fbvecsstr or Path
Full path of file with b-vectors. None to not read bvecs.
- Returns:
- bvalsarray, (N,) or None
- bvecsarray, (N, 3) or None
Notes
Files can be either ‘.bvals’/’.bvecs’ or ‘.txt’ or ‘.npy’ (containing arrays stored with the appropriate values).
load_nifti_data#
- dipy.io.image.load_nifti_data(fname, *, as_ndarray=True)[source]#
Load only the data array from a nifti file.
- Parameters:
- fnamestr or Path
Full path to the file.
- as_ndarray: bool, optional
convert nibabel ArrayProxy to a numpy.ndarray. If you want to save memory and delay this casting, just turn this option to False.
- Returns:
- data: np.ndarray or nib.ArrayProxy
See also
Notes
Structured RGB/RGBA data (NIfTI
DT_RGB24/DT_RGBA32) is auto-unpacked into a plain array with an added trailing color-channel axis, and aUserWarningis raised. Passas_ndarray=Falseto skip this and receive the raw structured data.
load_nifti#
- dipy.io.image.load_nifti(fname, *, return_img=False, return_voxsize=False, return_coords=False, as_ndarray=True)[source]#
Load data and other information from a nifti file.
- Parameters:
- fnamestr or Path
Full path to a nifti file.
- return_imgbool, optional
Whether to return the nibabel nifti img object.
- return_voxsize: bool, optional
Whether to return the nifti header zooms.
- return_coordsbool, optional
Whether to return the nifti header aff2axcodes.
- as_ndarray: bool, optional
convert nibabel ArrayProxy to a numpy.ndarray. If you want to save memory and delay this casting, just turn this option to False.
- Returns:
- A tuple, with (at the most, if all keyword args are set to True):
- (data, img.affine, img, vox_size, nib.aff2axcodes(img.affine))
See also
Notes
Like load_nifti_data, structured RGB/RGBA data is unpacked into a numeric array with a trailing color-channel axis and a
UserWarningwhenas_ndarray=True. Passas_ndarray=Falseto retain the raw proxy.The returned image is unchanged:
np.asanyarray(img.dataobj)accesses its structured data, whileimg.get_fdata()cannot cast it to float.
save_nifti#
- dipy.io.image.save_nifti(fname, data, affine, *, hdr=None, dtype=None, as_decfa=False, scale=None)[source]#
Save a data array into a nifti file.
- Parameters:
- fnamestr or Path
The full path to the file to be saved.
- datandarray
The array with the data to save.
- affine4x4 array
The affine transform associated with the file.
- hdrnifti header, optional
May contain additional information to store in the file header.
- as_decfabool, optional
If True, encode data as a DEC FA image via
dipy.io.utils.decfa;dtypeis ignored in this case.- scalebool or None, optional
When
as_decfais True, controls scaling from the 0-1 to the 0-255 range. None enables scaling for float data. Scaling is ignored for integer data or whenas_decfais False.
- Returns:
- None
save_qa_metric#
load_pam#
- dipy.io.peaks.load_pam(fname, *, verbose=False)[source]#
Load a PeaksAndMetrics HDF5 file (PAM5).
- Parameters:
- fnamestring or Path
Filename of PAM5 file.
- verbosebool, optional
Print summary information about the loaded file.
- Returns:
- pamPeaksAndMetrics object
Object holding peaks information and metrics.
save_pam#
- dipy.io.peaks.save_pam(fname, pam, *, affine=None, verbose=False)[source]#
Save all important attributes of object PeaksAndMetrics in a PAM5 file (HDF5).
- Parameters:
- fnamestr
Filename of PAM5 file.
- pamPeaksAndMetrics
Object holding peaks information and metrics.
- affinendarray, optional
The 4x4 matrix transforming the date from native to world coordinates. PeaksAndMetrics should have that attribute but if not it can be provided here.
- verbosebool, optional
Print summary information about the saved file.
pam_to_niftis#
- dipy.io.peaks.pam_to_niftis(pam, *, fname_peaks_dir='peaks_dirs.nii.gz', fname_peaks_values='peaks_values.nii.gz', fname_peaks_indices='peaks_indices.nii.gz', fname_shm='shm.nii.gz', fname_gfa='gfa.nii.gz', fname_sphere='sphere.txt', fname_b='B.nii.gz', fname_qa='qa.nii.gz', reshape_dirs=False)[source]#
Save SH, directions, indices and values of peaks to Nifti.
- Parameters:
- pamPeaksAndMetrics
Object holding peaks information and metrics.
- fname_peaks_dirstr, optional
Peaks direction filename.
- fname_peaks_valuesstr, optional
Peaks values filename.
- fname_peaks_indicesstr, optional
Peaks indices filename.
- fname_shmstr, optional
Spherical Harmonics coefficients filename. It will be saved if available.
- fname_gfastr, optional
Generalized FA filename. It will be saved if available.
- fname_spherestr, optional
Sphere vertices filename. It will be saved if available.
- fname_bstr, optional
B Matrix filename. Matrix that transforms spherical harmonics to spherical function. It will be saved if available.
- fname_qastr, optional
Quantitative Anisotropy filename. It will be saved if available.
- reshape_dirsbool, optional
If True, Reshape and convert to float32 a set of peaks for visualisation with mrtrix or the fibernavigator.
niftis_to_pam#
- dipy.io.peaks.niftis_to_pam(affine, peak_dirs, peak_values, peak_indices, *, shm_coeff=None, sphere=None, gfa=None, B=None, qa=None, odf=None, total_weight=None, ang_thr=None, pam_file=None)[source]#
Return SH, directions, indices and values of peaks to pam5.
- Parameters:
- affinearray, (4, 4)
The matrix defining the affine transform.
- peak_dirsndarray
The direction of each peak.
- peak_valuesndarray
The value of the peaks.
- peak_indicesndarray
Indices (in sphere vertices) of the peaks in each voxel.
- shm_coeffarray, optional
Spherical harmonics coefficients.
- sphereSphere class instance, optional
The sphere providing discrete directions for evaluation.
- gfandarray, optional
Generalized FA volume.
- Bndarray, optional
Matrix that transforms spherical harmonics to spherical function.
- qaarray, optional
Quantitative Anisotropy in each voxel.
- odfndarray, optional
SH coefficients for the ODF spherical function.
- total_weightfloat, optional
Total weight of the peaks.
- ang_thrfloat, optional
Angular threshold of the peaks.
- pam_filestr, optional
Filename of the desired pam file.
- Returns:
- pamPeaksAndMetrics
Object holding peak_dirs, shm_coeffs and other attributes.
tensor_to_pam#
- dipy.io.peaks.tensor_to_pam(evals, evecs, affine, *, shm_coeff=None, sphere=None, gfa=None, B=None, qa=None, odf=None, total_weight=None, ang_thr=None, pam_file=None, npeaks=5, generate_peaks_indices=True)[source]#
Convert diffusion tensor to pam5.
- Parameters:
- evalsndarray
Eigenvalues of a diffusion tensor. shape should be (…,3).
- evecsndarray
Eigen vectors from the tensor model.
- affinearray, (4, 4)
The matrix defining the affine transform.
- shm_coeffarray, optional
Spherical harmonics coefficients.
- sphereSphere class instance, optional
The sphere providing discrete directions for evaluation.
- gfandarray, optional
Generalized FA volume.
- Bndarray, optional
Matrix that transforms spherical harmonics to spherical function.
- qaarray, optional
Quantitative Anisotropy in each voxel.
- odfndarray, optional
SH coefficients for the ODF spherical function.
- pam_filestr, optional
Filename of the desired pam file.
- npeaksint, optional
Maximum number of peaks found.
- generate_peaks_indicesbool, optional
- total_weightfloat, optional
Total weight of the peaks.
- ang_thrfloat, optional
Angular threshold of the peaks.
- Returns:
- pamPeaksAndMetrics
Object holding peaks information and metrics.
save_pickle#
- dipy.io.pickles.save_pickle(fname, dix)[source]#
Save dix to fname as pickle.
- Parameters:
- fnamestr
filename to save object e.g. a dictionary
- dixobject
dictionary or other object
See also
Examples
>>> import os >>> from tempfile import mkstemp >>> fd, fname = mkstemp() # make temporary file (opened, attached to fh) >>> d={0:{'d':1}} >>> save_pickle(fname, d) >>> d2=load_pickle(fname, check_safety=False)
We remove the temporary file we created for neatness
>>> os.close(fd) # the file is still open, we need to close the fh >>> os.remove(fname)
load_pickle#
- dipy.io.pickles.load_pickle(fname, *, check_safety=True)[source]#
Load object from pickle file fname.
- Parameters:
- fnamestr
filename to load dict or other python object
- check_safetybool, optional
If True, emit a warning that pickle files can execute arbitrary code. Set to False only when loading files from trusted sources.
- Returns:
- dixobject
dictionary or other object
See also
StatefulSurface#
- class dipy.io.stateful_surface.StatefulSurface(vertices, faces, reference, space, *, origin=Origin.NIFTI, data_per_vertex=None, dtype_dict=None)[source]#
Bases:
objectClass for stateful representation of meshes and lines Object designed to be identical no matter the file format (gii, vtk, ply, stl, obj, pial). Facilitate transformation between space and data manipulation for each streamline / vertex.
- Attributes:
affineGetter for the reference affine
data_per_vertexGetter for data_per_vertex
dimensionsGetter for the reference dimensions
dtype_dictGetter for dtype_dict
facesPartially safe getter for faces
originGetter for origin standard
spaceGetter for the current space
space_attributesGetter for spatial attribute
verticesPartially safe getter for vertices
voxel_orderGetter for the reference voxel order
voxel_sizesGetter for the reference voxel sizes
Methods
are_compatible(sfs_1, sfs_2)Compatibility verification of two StatefulSurface to ensure space, origin, data_per_vertex consistency
Compute the bounding box of the vertices in their current state
from_sfs(vertices, sfs, *[, faces, ...])Create an instance of StatefulSurface from another instance of StatefulSurface.
Return a list of the data_per_vertex attribute names
Build a polyxios PolyData from the surface.
Safe getter for vertices (for slicing)
Verify that the bounding box is valid in voxel space.
Safe function to shift vertices so the center of voxel is the origin
Safe function to shift vertices so the corner of voxel is the origin
to_origin(target_origin)Safe function to change vertices to a particular origin standard False means NIFTI (center) and True means TrackVis (corner)
to_rasmm()Safe function to transform vertices and update state
to_space(target_space)Safe function to transform vertices to a particular space using an enum and update state
to_vox()Safe function to transform vertices and update state
to_voxmm()Safe function to transform vertices and update state
remove_invalid_vertices
to_lpsmm
- property affine#
Getter for the reference affine
- static are_compatible(sfs_1, sfs_2)[source]#
Compatibility verification of two StatefulSurface to ensure space, origin, data_per_vertex consistency
- compute_bounding_box()[source]#
Compute the bounding box of the vertices in their current state
- Returns:
- outputndarray
8 corners of the XYZ aligned box, all zeros if no vertices
- property data_per_vertex#
Getter for data_per_vertex
- property dimensions#
Getter for the reference dimensions
- property dtype_dict#
Getter for dtype_dict
- property faces#
Partially safe getter for faces
- static from_sfs(vertices, sfs, *, faces=None, data_per_vertex=None)[source]#
Create an instance of StatefulSurface from another instance of StatefulSurface.
- Parameters:
- verticesndarray
Vertices of the new StatefulSurface.
- sfsStatefulSurface,
The other StatefulSurface to copy the space_attribute AND state from.
- facesndarray, optional
Faces of the new StatefulSurface. If None, the faces of the original StatefulSurface will be used.
- data_per_vertexdict, optional
Dictionary in which each key has X items. X being the number of points on the surface.
- —–
- is_bbox_in_vox_valid()[source]#
Verify that the bounding box is valid in voxel space. Negative coordinates or coordinates above the volume dimensions are considered invalid in voxel space.
- Returns:
- outputbool
Are the vertices within the volume of the associated reference
- property origin#
Getter for origin standard
- property space#
Getter for the current space
- property space_attributes#
Getter for spatial attribute
- to_origin(target_origin)[source]#
Safe function to change vertices to a particular origin standard False means NIFTI (center) and True means TrackVis (corner)
- to_space(target_space)[source]#
Safe function to transform vertices to a particular space using an enum and update state
- property vertices#
Partially safe getter for vertices
- property voxel_order#
Getter for the reference voxel order
- property voxel_sizes#
Getter for the reference voxel sizes
convert_to_polydata#
- dipy.io.stateful_surface.convert_to_polydata(vertices, triangles, *, data_per_point=None)[source]#
Convert vertices and triangles to a polyxios PolyData.
- Parameters:
- verticesnumpy.ndarray
An array of shape (n_vertices, 3) containing the vertex coordinates.
- trianglesnumpy.ndarray
An array of shape (n_triangles, 3) containing the vertex indices of the triangles.
- data_per_pointdict, optional
A dictionary where keys are array names and values are numpy arrays of shape (n_vertices, …) representing data associated with each vertex.
- Returns:
- polydatapolyxios.PolyData
StatefulTractogram#
- class dipy.io.stateful_tractogram.StatefulTractogram(streamlines, reference, space, *, origin=Origin.NIFTI, data_per_point=None, data_per_streamline=None)[source]#
Bases:
objectClass for stateful representation of collections of streamlines Object designed to be identical no matter the file format (trk, tck, vtk, fib, dpy). Facilitate transformation between space and data manipulation for each streamline / point.
- Attributes:
affineGetter for the reference affine
data_per_pointGetter for data_per_point
data_per_streamlineGetter for data_per_streamline
dimensionsGetter for the reference dimensions
dtype_dictGetter for dtype_dict
originGetter for origin standard
spaceGetter for the current space
space_attributesGetter for spatial attribute
streamlinesPartially safe getter for streamlines
voxel_orderGetter for the reference voxel order
voxel_sizesGetter for the reference voxel sizes
Methods
are_compatible(sft_1, sft_2)Compatibility verification of two StatefulTractogram to ensure space, origin, data_per_point and data_per_streamline consistency
Compute the bounding box of the streamlines in their current state
from_sft(streamlines, sft, *[, ...])Create an instance of StatefulTractogram from another instance of StatefulTractogram.
Return a list of the data_per_point attribute names
Return a list of the data_per_streamline attribute names
Safe getter for streamlines (for slicing)
Verify that the bounding box is valid in voxel space.
remove_invalid_streamlines(*[, epsilon])Remove streamlines with invalid coordinates from the object.
Safe function to shift streamlines so the center of voxel is the origin
Safe function to shift streamlines so the corner of voxel is the origin
to_origin(target_origin)Safe function to change streamlines to a particular origin standard False means NIFTI (center) and True means TrackVis (corner)
to_rasmm()Safe function to transform streamlines and update state
to_space(target_space)Safe function to transform streamlines to a particular space using an enum and update state
to_vox()Safe function to transform streamlines and update state
to_voxmm()Safe function to transform streamlines and update state
to_lpsmm
- property affine#
Getter for the reference affine
- static are_compatible(sft_1, sft_2)[source]#
Compatibility verification of two StatefulTractogram to ensure space, origin, data_per_point and data_per_streamline consistency
- compute_bounding_box()[source]#
Compute the bounding box of the streamlines in their current state
- Returns:
- outputndarray
8 corners of the XYZ aligned box, all zeros if no streamlines
- property data_per_point#
Getter for data_per_point
- property data_per_streamline#
Getter for data_per_streamline
- property dimensions#
Getter for the reference dimensions
- property dtype_dict#
Getter for dtype_dict
- static from_sft(streamlines, sft, *, data_per_point=None, data_per_streamline=None)[source]#
Create an instance of StatefulTractogram from another instance of StatefulTractogram.
- Parameters:
- streamlineslist or ArraySequence
Streamlines of the tractogram
- sftStatefulTractogram,
The other StatefulTractogram to copy the space_attribute AND state from.
- data_per_pointdict, optional
Dictionary in which each key has X items, each items has Y_i items X being the number of streamlines Y_i being the number of points on streamlines #i
- data_per_streamlinedict, optional
Dictionary in which each key has X items X being the number of streamlines
- —–
- is_bbox_in_vox_valid()[source]#
Verify that the bounding box is valid in voxel space. Negative coordinates or coordinates above the volume dimensions are considered invalid in voxel space.
- Returns:
- outputbool
Are the streamlines within the volume of the associated reference
- property origin#
Getter for origin standard
- remove_invalid_streamlines(*, epsilon=0.001)[source]#
Remove streamlines with invalid coordinates from the object. Will also remove the data_per_point and data_per_streamline. Invalid coordinates are any X,Y,Z values above the reference dimensions or below zero
- Parameters:
- epsilonfloat, optional
Epsilon value for the bounding box verification.
- Returns:
- outputtuple
Tuple of two list, indices_to_remove, indices_to_keep
- property space#
Getter for the current space
- property space_attributes#
Getter for spatial attribute
- property streamlines#
Partially safe getter for streamlines
- to_origin(target_origin)[source]#
Safe function to change streamlines to a particular origin standard False means NIFTI (center) and True means TrackVis (corner)
- to_space(target_space)[source]#
Safe function to transform streamlines to a particular space using an enum and update state
- property voxel_order#
Getter for the reference voxel order
- property voxel_sizes#
Getter for the reference voxel sizes
convert_to_polydata_lines#
get_polydata_lines#
- dipy.io.streamline.get_polydata_lines(polydata)[source]#
Get the lines of a polyxios PolyData as a list of coordinate arrays.
- Parameters:
- polydatapolyxios.PolyData
- Returns:
- lineslist of numpy.ndarray
One array of shape (n_points, 3) per line.
Notes
A PolyData holding no line element falls back to its raw connectivity, which is what keeps a tractogram saved as
.vtpreadable: the polyxios VTP writer files every element underPolys.
save_vtk_streamlines#
- dipy.io.streamline.save_vtk_streamlines(streamlines, filename, *, to_lps=True, binary=False)[source]#
Save streamlines as polydata to a supported format file.
File formats can be VTK, VTP and FIB.
- Parameters:
- streamlineslist
list of 2D arrays or ArraySequence
- filenamestring or Path
output filename (.vtk, .vtp or .fib)
- to_lpsbool
Default to True, will follow the vtk file convention for streamlines Will be supported by MITKDiffusion and MI-Brain
- binarybool
save the file as binary
load_vtk_streamlines#
- dipy.io.streamline.load_vtk_streamlines(filename, *, to_lps=True)[source]#
Load streamlines from polydata.
Load formats can be VTK, VTP and FIB.
- Parameters:
- filenamestring or Path
input filename (.vtk, .vtp or .fib)
- to_lpsbool
Default to True, will follow the vtk file convention for streamlines Will be supported by MITK-Diffusion and MI-Brain
- Returns:
- outputlist
list of 2D arrays
save_tractogram#
- dipy.io.streamline.save_tractogram(sft, filename, *, bbox_valid_check=True, to_space=Space.RASMM, to_origin=Origin.NIFTI)[source]#
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- sftStatefulTractogram
The stateful tractogram to save
- filenamestring or Path
Filename with valid extension
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed before saving
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
load_tractogram#
- dipy.io.streamline.load_tractogram(filename, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, from_space=None, from_origin=None, trk_header_check=True)[source]#
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed after loading
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space)
Space to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin)
Origin to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool
- trk_header_checkbool
Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded
- Returns:
- outputStatefulTractogram
The tractogram to load (must have been saved properly)
load_generator#
- dipy.io.streamline.load_generator(ttype)[source]#
Generate a loading function that performs a file extension check to restrict the user to a single file format.
- Parameters:
- ttypestring
Extension of the file format that requires a loader
- Returns:
- outputfunction
Function (load_tractogram) that handle only one file format
save_generator#
- dipy.io.streamline.save_generator(ttype)[source]#
Generate a saving function that performs a file extension check to restrict the user to a single file format.
- Parameters:
- ttypestring
Extension of the file format that requires a saver
- Returns:
- outputfunction
Function (save_tractogram) that handle only one file format
load_trk#
- dipy.io.streamline.load_trk(filename, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, trk_header_check=True, from_space=None, from_origin=None)#
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed after loading
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space)
Space to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin)
Origin to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool
- trk_header_checkbool
Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded
- Returns:
- outputStatefulTractogram
The tractogram to load (must have been saved properly)
load_tck#
- dipy.io.streamline.load_tck(filename, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, trk_header_check=True, from_space=None, from_origin=None)#
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed after loading
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space)
Space to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin)
Origin to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool
- trk_header_checkbool
Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded
- Returns:
- outputStatefulTractogram
The tractogram to load (must have been saved properly)
load_trx#
- dipy.io.streamline.load_trx(filename, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, trk_header_check=True, from_space=None, from_origin=None)#
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed after loading
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space)
Space to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin)
Origin to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool
- trk_header_checkbool
Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded
- Returns:
- outputStatefulTractogram
The tractogram to load (must have been saved properly)
load_vtk#
- dipy.io.streamline.load_vtk(filename, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, trk_header_check=True, from_space=None, from_origin=None)#
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed after loading
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space)
Space to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin)
Origin to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool
- trk_header_checkbool
Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded
- Returns:
- outputStatefulTractogram
The tractogram to load (must have been saved properly)
load_vtp#
- dipy.io.streamline.load_vtp(filename, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, trk_header_check=True, from_space=None, from_origin=None)#
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed after loading
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space)
Space to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin)
Origin to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool
- trk_header_checkbool
Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded
- Returns:
- outputStatefulTractogram
The tractogram to load (must have been saved properly)
load_fib#
- dipy.io.streamline.load_fib(filename, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, trk_header_check=True, from_space=None, from_origin=None)#
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed after loading
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space)
Space to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin)
Origin to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool
- trk_header_checkbool
Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded
- Returns:
- outputStatefulTractogram
The tractogram to load (must have been saved properly)
load_dpy#
- dipy.io.streamline.load_dpy(filename, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, trk_header_check=True, from_space=None, from_origin=None)#
Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for streamlines generation
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed after loading
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space)
Space to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin)
Origin to which the tractogram was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool
- trk_header_checkbool
Verification that the reference has the same header as the spatial attributes as the input tractogram when a Trk is loaded
- Returns:
- outputStatefulTractogram
The tractogram to load (must have been saved properly)
save_trk#
- dipy.io.streamline.save_trk(sft, filename, *, bbox_valid_check=True)#
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- sftStatefulTractogram
The stateful tractogram to save
- filenamestring or Path
Filename with valid extension
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed before saving
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
save_tck#
- dipy.io.streamline.save_tck(sft, filename, *, bbox_valid_check=True)#
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- sftStatefulTractogram
The stateful tractogram to save
- filenamestring or Path
Filename with valid extension
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed before saving
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
save_trx#
- dipy.io.streamline.save_trx(sft, filename, *, bbox_valid_check=True)#
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- sftStatefulTractogram
The stateful tractogram to save
- filenamestring or Path
Filename with valid extension
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed before saving
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
save_vtk#
- dipy.io.streamline.save_vtk(sft, filename, *, bbox_valid_check=True)#
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- sftStatefulTractogram
The stateful tractogram to save
- filenamestring or Path
Filename with valid extension
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed before saving
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
save_vtp#
- dipy.io.streamline.save_vtp(sft, filename, *, bbox_valid_check=True)#
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- sftStatefulTractogram
The stateful tractogram to save
- filenamestring or Path
Filename with valid extension
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed before saving
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
save_fib#
- dipy.io.streamline.save_fib(sft, filename, *, bbox_valid_check=True)#
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- sftStatefulTractogram
The stateful tractogram to save
- filenamestring or Path
Filename with valid extension
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed before saving
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
save_dpy#
- dipy.io.streamline.save_dpy(sft, filename, *, bbox_valid_check=True)#
Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)
- Parameters:
- sftStatefulTractogram
The stateful tractogram to save
- filenamestring or Path
Filename with valid extension
- bbox_valid_checkbool
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- to_spaceEnum (dipy.io.utils.Space)
Space to which the streamlines will be transformed before saving
- to_originEnum (dipy.io.utils.Origin)
- Origin to which the streamlines will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
load_polydata#
save_polydata#
- dipy.io.surface.save_polydata(polydata, file_name, *, binary=False, color_array_name=None)[source]#
Save a polydata to a supported format file.
Save formats can be OBJ, VTK, VTP, PLY and STL.
- Parameters:
- polydatapolyxios.PolyData
The polydata object to be saved.
- file_namestring or Path
The output filename (.obj, .vtk, .vtp, .ply and .stl)
- binarybool, optional
Save the file in binary format.
- color_array_namestr, optional
Name of the vertex attribute holding the colors. It is written under the name readers pick colors up from, so that it survives the round-trip. Every other vertex attribute is written under its own.
get_polydata_vertices#
get_polydata_triangles#
get_polydata_vertex_attrs#
load_surface#
- dipy.io.surface.load_surface(fname, reference, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, bbox_valid_check=True, from_space=None, from_origin=None, gifti_in_freesurfer=False)[source]#
Load the stateful surface from any format (vtk/vtp/obj/stl/ply/gii/pial)
- Parameters:
- filenamestring or Path
Filename with valid extension
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), or ‘same’ if the input is a trk file. Reference that provides the spatial attribute. Typically a nifti-related object from the native diffusion used for surface generation
- to_spaceEnum (dipy.io.utils.Space), optional
Space to which the surface will be transformed after loading
- to_originEnum (dipy.io.utils.Origin), optional
- Origin to which the surface will be transformed after loading
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- bbox_valid_checkbool, optional
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- from_spaceEnum (dipy.io.utils.Space), optional
Space to which the surface was transformed before saving. Help for software compatibility. If None, assumes RASMM.
- from_originEnum (dipy.io.utils.Origin), optional
Origin to which the surface was transformed before saving. Help for software compatibility. If None, assumes NIFTI.
- gifti_in_freesurferbool, optional
Whether the gifti file is in freesurfer reference space.
- Returns:
- outputStatefulSurface
The surface to load (must have been saved properly)
- Raises:
- ValueError
If the bounding box is not valid in voxel space.
save_surface#
- dipy.io.surface.save_surface(sfs, fname, *, to_space=Space.RASMM, to_origin=Origin.NIFTI, legacy_vtk_format=False, bbox_valid_check=True, ref_pial=None, ref_gii=None, gifti_in_freesurfer=False)[source]#
Save the stateful surface to any format (vtk/vtp/obj/stl/ply/gii/pial)
- Parameters:
- sfsStatefulSurface
The surface to save (must have been loaded properly)
- fnamestr or Path
Absolute path of the file.
- to_spaceEnum (dipy.io.stateful_surface.Space), optional
Space to which the surface will be transformed before saving
- to_originEnum (dipy.io.stateful_surface.Origin), optional
- Origin to which the surface will be transformed before saving
NIFTI standard, default (center of the voxel) TRACKVIS standard (corner of the voxel)
- legacy_vtk_formatbool, optional
Kept for backward compatibility and ignored: polyxios always writes the classic VTK 4.2 layout, which every VTK reader takes.
- bbox_valid_checkbool, optional
Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.
- ref_pialstr or Path, optional
Reference pial file to save the surface in pial format. If not provided, the metadata of the input surface is used (if available).
- ref_giistr or Path, optional
Reference gii file to save the surface in gii format. If not provided, the header of the input surface is used (if available).
- gifti_in_freesurferbool, optional
Whether the gifti file must be saved in freesurfer reference space.
- Raises:
- ValueError
If the bounding box is not valid in voxel space.
load_pial#
- dipy.io.surface.load_pial(fname, *, return_meta=False)[source]#
Load pial file.
- Parameters:
- fnamestr or Path
Absolute path of the file.
- return_metabool, optional
Whether to read the metadata of the file or not, by default False.
- Returns:
- tuple
(vertices, faces) if return_meta=False. Otherwise, (vertices, faces, metadata).
save_pial#
load_gifti#
- dipy.io.surface.load_gifti(fname, *, return_header=False)[source]#
Load gifti file.
- Parameters:
- fnamestr or Path
Absolute path of the file.
- return_headerbool, optional
Whether to read the header of the file or not, by default False. If True, returns a tuple with vertices, faces and header.
- Returns:
- tuple
(vertices, faces)
save_gifti#
- dipy.io.surface.save_gifti(fname, vertices, faces, *, header=None)[source]#
Save gifti file. https://netneurolab.github.io/neuromaps/_modules/neuromaps/images.html
- Parameters:
- fnamestr or Path
Absolute path of the file.
- verticesndarray
Vertices.
- facesndarray
Faces.
- headernib.filebasedimages.FileBasedHeader
Valid header for the gifti file, typically loaded from a reference GII
apply_freesurfer_transform#
- dipy.io.surface.apply_freesurfer_transform(vertices, reference, *, inv=False)[source]#
Apply the freesurfer transform to the vertices to bring them to RASMM space or to bring them back to the original space.
- Parameters:
- verticesndarray
Vertices to transform.
- referencestr or Path
Reference file to get the transform from.
- invbool, optional
True if loading the surface, False if saving the surface.
Space#
Origin#
nifti1_symmat#
- dipy.io.utils.nifti1_symmat(image_data, *args, **kwargs)[source]#
Returns a Nifti1Image with a symmetric matrix intent
- Parameters:
- image_dataarray-like
should have lower triangular elements of a symmetric matrix along the last dimension
- *args
Passed to Nifti1Image
- **kwargs
Passed to Nifti1Image
- Returns:
- imageNifti1Image
5d, extra dimensions added before the last. Has symmetric matrix intent code
make5d#
has_rgb_dtype#
- dipy.io.utils.has_rgb_dtype(data)[source]#
Check whether an array has a structured NIfTI
DT_RGB24dtype.Returns
Truewhen data has a structured numpy dtype whose field names are exactly('R', 'G', 'B')or('R', 'G', 'B', 'A'), as created by nibabel when loading a NIfTI file with datatype code 128 (DT_RGB24) or 2304 (DT_RGBA32).- Parameters:
- datanp.ndarray
Array to inspect.
- Returns:
- bool
Truewhen data carries a structured RGB/RGBA dtype.
is_rgb_compatible_data#
- dipy.io.utils.is_rgb_compatible_data(data)[source]#
Check whether a plain numeric array has RGB-compatible shape and values.
Returns
Truewhen data hasndim == 4, the last dimension is 3 or 4, the array is non-empty, and values fall within a range consistent with color channels:uint8: always compatible (no DWI scanner uses uint8).
Other integer (e.g. int16): all values in [0, 255].
Float: all values in [0, 1] with no NaN.
Structured-dtype arrays (e.g. NIfTI
DT_RGB24) are not checked here; use has_rgb_dtype for those.- Parameters:
- datanp.ndarray
Array to inspect.
- Returns:
- bool
Truewhen data has RGB-compatible shape and values.
unpack_rgb_array#
- dipy.io.utils.unpack_rgb_array(data)[source]#
Convert a structured RGB/RGBA array to a plain numeric array.
Nibabel represents RGB/RGBA NIfTI images with datatype code 128 (
DT_RGB24) as structured arrays, e.g.dtype=[('R','u1'),('G','u1'),('B','u1')]with shape(X, Y, Z). NumPy ufuncs do not support structured dtypes, so this converts to a plain(X, Y, Z, N)array where N is the number of channels.Only arrays whose field names are exactly
('R', 'G', 'B')or('R', 'G', 'B', 'A')are unpacked. Other structured dtypes are returned unchanged.- Parameters:
- datanp.ndarray
Array that may have a structured RGB/RGBA dtype.
- Returns:
- np.ndarray
Regular numeric array when input was structured RGB/RGBA; otherwise the input unchanged.
decfa#
- dipy.io.utils.decfa(img_orig, *, scale=False)[source]#
Create a nifti-compliant directional-encoded color FA image.
- Parameters:
- img_origNifti1Image class instance.
Contains encoding of the DEC FA image with a 4D volume of data, where the elements on the last dimension represent R, G and B components.
- scale: bool.
Whether to scale data from the 0-1 to the 0-255 range. Ignored for integer data, which already represents channel values.
- Returns:
- imgNifti1Image class instance with dtype set to store tuples of
uint8 in (R, G, B) order.
Notes
The output uses NIfTI datatype code 128 (
DT_RGB24), stored as a structured dtype with fields('R', 'G', 'B'). The intent code is set to 1001 (NIFTI_INTENT_ESTIMATE) with name"Color FA". Nibabel reconstructs the structured dtype from the datatype code on load; the intent code is informational metadata only.For a description of this format, see:
https://nifti.nimh.nih.gov/nifti-1/documentation/nifti1fields/nifti1fields_pages/datatype.html
decfa_to_float#
- dipy.io.utils.decfa_to_float(img_orig)[source]#
Convert a nifti-compliant directional-encoded color FA image into a nifti image with RGB encoded in floating point resolution.
- Parameters:
- img_origNifti1Image class instance.
Contains encoding of the DEC FA image with a 3D volume of data, where each element is a (R, G, B) tuple in uint8.
- Returns:
- imgNifti1Image class instance with float dtype.
Notes
For a description of this format, see:
https://nifti.nimh.nih.gov/nifti-1/documentation/nifti1fields/nifti1fields_pages/datatype.html
is_reference_info_valid#
- dipy.io.utils.is_reference_info_valid(affine, dimensions, voxel_sizes, voxel_order)[source]#
Validate basic data type and value of spatial attribute.
Does not ensure that voxel_sizes and voxel_order are self-coherent with the affine.
- Only verifies the following:
affine is of the right type (float) and dimension (4,4)
affine contain values in the rotation part
dimensions is of right type (int) and length (3)
voxel_sizes is of right type (float) and length (3)
voxel_order is of right type (str) and length (3)
The listed parameters are what is expected, provide something else and this function should fail (cover common mistakes).
- Parameters:
- affine: ndarray (4,4)
Transformation of VOX to RASMM
- dimensions: ndarray (3,), int16
Volume shape for each axis
- voxel_sizes: ndarray (3,), float32
Size of voxel for each axis
- voxel_order: string
Typically ‘RAS’ or ‘LPS’
- Returns:
- outputbool
Does the input represent a valid ‘state’ of spatial attribute
get_reference_info#
- dipy.io.utils.get_reference_info(reference)[source]#
Get the spatial attributes of the given data file.
- Parameters:
- referenceNifti or Trk filename, Nifti1Image or TrkFile, Nifti1Header or
trk.header (dict), TrxFile or trx.header (dict) Reference that provides the spatial attribute.
- Returns:
- outputtuple
affine ndarray (4,4), np.float64, transformation of VOX to RASMM
dimensions ndarray (3,), int16, volume shape for each axis
voxel_sizes ndarray (3,), float32, size of voxel for each axis
voxel_order, string, Typically ‘RAS’ or ‘LPS’
is_header_compatible#
- dipy.io.utils.is_header_compatible(reference_1, reference_2)[source]#
Compare the spatial attributes of the data in the input files.
- Parameters:
- reference_1Nifti or Trk filename, Nifti1Image or TrkFile,
Nifti1Header or trk.header (dict) Reference that provides the spatial attribute.
- reference_2Nifti or Trk filename, Nifti1Image or TrkFile,
Nifti1Header or trk.header (dict) Reference that provides the spatial attribute.
- Returns:
- outputbool
Trueif all spatial attributes match,Falseotherwise.
create_tractogram_header#
- dipy.io.utils.create_tractogram_header(tractogram_type, affine, dimensions, voxel_sizes, voxel_order)[source]#
Write a standard trk/tck header from spatial attribute
- Parameters:
- tractogram_typestr, Path or nibabel.streamlines.format.TractogramFile
The tractogram type to create a header for.
- affinendarray (4, 4)
The affine transformation.
- dimensionsarray-like (3,)
The image dimensions.
- voxel_sizesarray-like (3,)
The voxel sizes.
- voxel_orderstr
The voxel order (e.g., ‘RAS’).
- Returns:
- headerdict
A standard tractogram header.
create_nifti_header#
- dipy.io.utils.create_nifti_header(affine, dimensions, voxel_sizes)[source]#
Write a standard nifti header from spatial attribute
- Parameters:
- affinendarray (4, 4)
The affine transformation.
- dimensionsarray-like (3,)
The image dimensions.
- voxel_sizesarray-like (3,)
The voxel sizes.
- Returns:
- headernibabel.nifti1.Nifti1Header
A standard NIfTI header.
save_buan_profiles_hdf5#
- dipy.io.utils.save_buan_profiles_hdf5(fname, dt, *, key=None)[source]#
Saves the given input dataframe to .h5 file
- Parameters:
- fnamestring or Path
file name for saving the hdf5 file
- dtPandas DataFrame
DataFrame to be saved as .h5 file
- keystr, optional
Key to retrieve the contents in the HDF5 file. The file rootname will be used if not provided.
read_img_arr_or_path#
- dipy.io.utils.read_img_arr_or_path(data, *, affine=None)[source]#
Helper function that handles inputs that can be paths, nifti img or arrays
- Parameters:
- dataarray or nib.Nifti1Image, str or Path.
Either as a 3D/4D array or as a nifti image object, or as a string containing the full path to a nifti file.
- affine4x4 array, optional.
Must be provided for data provided as an array. If provided together with Nifti1Image or str data, this input will over-ride the affine that is stored in the data input. Default: use the affine stored in data.
- Returns:
- data, affinendarray and 4x4 array
recursive_compare#
- dipy.io.utils.recursive_compare(d1, d2, *, level='root')[source]#
Recursively compare two dictionaries or lists for matching structure and dtypes.
This function is primarily used to compare dtype dictionaries, ensuring that they have the same keys/structure and that the leaf values have the same itemsize.
- Parameters:
- d1dict or list or object
The first object to compare.
- d2dict or list or object
The second object to compare.
- levelstr, optional
The current level of recursion, used for reporting errors.
- Raises:
- ValueError
If the dictionaries have different keys, lists have different lengths, or leaf values have different item sizes.
split_filename_extension#
- dipy.io.utils.split_filename_extension(filename)[source]#
Split the filename and its extension(s).
In our field filename can have period in it (e.g. smoothwm.L.surf.gii) At the moment only one double extension is supported (.nii.gz, .gii.gz)
- Parameters:
- filenamestr or Path
The input filename.
- Returns:
- namestr
The filename without its extension(s).
- extensionstr
The extension(s) of the filename, including the dot(s).