io#

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#

Dpy(fname, *[, mode, compression])

Module: io.gradients#

read_bvals_bvecs(fbvals, fbvecs)

Read b-values and b-vectors from disk.

Module: io.image#

load_nifti_data(fname, *[, as_ndarray])

Load only the data array from a nifti file.

load_nifti(fname, *[, return_img, ...])

Load data and other information from a nifti file.

save_nifti(fname, data, affine, *[, hdr, dtype])

Save a data array into a nifti file.

save_qa_metric(fname, xopt, fopt)

Save Quality Assurance metrics.

Module: io.peaks#

load_pam(fname, *[, verbose])

Load a PeaksAndMetrics HDF5 file (PAM5).

save_pam(fname, pam, *[, affine, verbose])

Save all important attributes of object PeaksAndMetrics in a PAM5 file (HDF5).

pam_to_niftis(pam, *[, fname_peaks_dir, ...])

Save SH, directions, indices and values of peaks to Nifti.

niftis_to_pam(affine, peak_dirs, ...[, ...])

Return SH, directions, indices and values of peaks to pam5.

tensor_to_pam(evals, evecs, affine, *[, ...])

Convert diffusion tensor to pam5.

Module: io.pickles#

Load and save pickles

save_pickle(fname, dix)

Save dix to fname as pickle.

load_pickle(fname)

Load object from pickle file fname.

Module: io.stateful_surface#

StatefulSurface(vertices, faces, reference, ...)

Class for stateful representation of meshes and lines Object designed to be identical no matter the file format (gii, vtk, ply, stl, obj, pial).

Module: io.stateful_tractogram#

StatefulTractogram(streamlines, reference, ...)

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#

save_tractogram(sft, filename, *[, ...])

Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)

load_tractogram(filename, reference, *[, ...])

Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)

load_generator(ttype)

Generate a loading function that performs a file extension check to restrict the user to a single file format.

save_generator(ttype)

Generate a saving function that performs a file extension check to restrict the user to a single file format.

load_trk(filename, reference, *[, to_space, ...])

Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)

load_tck(filename, reference, *[, to_space, ...])

Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)

load_trx(filename, reference, *[, to_space, ...])

Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)

load_vtk(filename, reference, *[, to_space, ...])

Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)

load_vtp(filename, reference, *[, to_space, ...])

Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)

load_fib(filename, reference, *[, to_space, ...])

Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)

load_dpy(filename, reference, *[, to_space, ...])

Load the stateful tractogram from any format (trx/trk/tck/vtk/vtp/fib/dpy)

save_trk(sft, filename[, bbox_valid_check])

Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)

save_tck(sft, filename[, bbox_valid_check])

Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)

save_trx(sft, filename[, bbox_valid_check])

Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)

save_vtk(sft, filename[, bbox_valid_check])

Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)

save_vtp(sft, filename[, bbox_valid_check])

Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)

save_fib(sft, filename[, bbox_valid_check])

Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)

save_dpy(sft, filename[, bbox_valid_check])

Save the stateful tractogram in any format (trx/trk/tck/vtk/vtp/fib/dpy)

Module: io.surface#

load_surface(fname, reference, *[, ...])

Load the stateful surface from any format (vtk/vtp/obj/stl/ply/gii/pial)

save_surface(sfs, fname, *[, to_space, ...])

Save the stateful surface to any format (vtk/vtp/obj/stl/ply/gii/pial)

load_pial(fname, *[, return_meta])

Load pial file.

save_pial(fname, vertices, faces, *[, metadata])

Save pial file.

load_gifti(fname, *[, return_header])

Load gifti file.

save_gifti(fname, vertices, faces, *[, header])

Save gifti file.

apply_freesurfer_transform(vertices, ...[, inv])

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

Space(*values)

Enum to simplify future change to convention

Origin(*values)

Enum to simplify future change to convention

nifti1_symmat(image_data, *args, **kwargs)

Returns a Nifti1Image with a symmetric matrix intent

make5d(data)

Reshape the input to have 5 dimensions.

decfa(img_orig, *[, scale])

Create a nifti-compliant directional-encoded color FA image.

decfa_to_float(img_orig)

Convert a nifti-compliant directional-encoded color FA image into a nifti image with RGB encoded in floating point resolution.

is_reference_info_valid(affine, dimensions, ...)

Validate basic data type and value of spatial attribute.

get_reference_info(reference)

Get the spatial attributes of the given data file.

is_header_compatible(reference_1, reference_2)

Compare the spatial attributes of the data in the input files.

create_tractogram_header(tractogram_type, ...)

Write a standard trk/tck header from spatial attribute

create_nifti_header(affine, dimensions, ...)

Write a standard nifti header from spatial attribute

save_buan_profiles_hdf5(fname, dt, *[, key])

Saves the given input dataframe to .h5 file

read_img_arr_or_path(data, *[, affine])

Helper function that handles inputs that can be paths, nifti img or arrays

recursive_compare(d1, d2[, level])

Recursively compare two dictionaries or lists for matching structure and dtypes.

split_filename_extension(filename)

Split the filename and its extension(s).

Module: io.vtk#

load_polydata(file_name)

Load a vtk polydata to a supported format file.

save_polydata(polydata, file_name, *[, ...])

Save a vtk polydata to a supported format file.

save_vtk_streamlines(streamlines, filename, *)

Save streamlines as vtk polydata to a supported format file.

load_vtk_streamlines(filename, *[, to_lps])

Load streamlines from vtk polydata.

get_polydata_triangles(polydata[, dtype])

Get triangles from a vtkPolyData object.

get_polydata_vertices(polydata[, dtype])

Get vertices from a vtkPolyData object.

convert_to_polydata(vertices, triangles[, ...])

Convert vertices and triangles to a vtkPolyData object.

Dpy#

class dipy.io.dpy.Dpy(fname, *, mode='r', compression=0)[source]#

Bases: object

Methods

close()

Close the Dpy file descriptor.

read_track()

Read one track from the Dpy file at the current position.

read_tracks()

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.

close()[source]#

Close the Dpy file descriptor.

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.

write_track(track)[source]#

Write a single track to the Dpy file.

Parameters:
trackarray-like (N, 3)

The streamline to be written.

write_tracks(tracks)[source]#

Write multiple tracks to the Dpy file.

Parameters:
tracksStreamlines or list of array-like

The tractography dataset to be written.

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

load_nifti

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

load_nifti_data

save_nifti#

dipy.io.image.save_nifti(fname, data, affine, *, hdr=None, dtype=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.

Returns:
None

save_qa_metric#

dipy.io.image.save_qa_metric(fname, xopt, fopt)[source]#

Save Quality Assurance metrics.

Parameters:
fname: string or Path

File name to save the metric values.

xopt: numpy array

The metric containing the optimal parameters for image registration.

fopt: int

The distance between the registered images.

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

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)

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)[source]#

Load object from pickle file fname.

Parameters:
fnamestr

filename to load dict or other python object

Returns:
dixobject

dictionary or other object

StatefulSurface#

class dipy.io.stateful_surface.StatefulSurface(vertices, faces, reference, space, *, origin=Origin.NIFTI, data_per_vertex=None, dtype_dict=None)[source]#

Bases: object

Class 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:
affine

Getter for the reference affine

data_per_vertex

Getter for data_per_vertex

dimensions

Getter for the reference dimensions

dtype_dict

Getter for dtype_dict

faces

Partially safe getter for faces

origin

Getter for origin standard

space

Getter for the current space

space_attributes

Getter for spatial attribute

vertices

Partially safe getter for vertices

voxel_order

Getter for the reference voxel order

voxel_sizes

Getter 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_bounding_box()

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.

get_data_per_vertex_keys()

Return a list of the data_per_vertex attribute names

get_vertices_copy()

Safe getter for vertices (for slicing)

is_bbox_in_vox_valid()

Verify that the bounding box is valid in voxel space.

to_center()

Safe function to shift vertices so the center of voxel is the origin

to_corner()

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

get_polydata

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.

—–
get_data_per_vertex_keys()[source]#

Return a list of the data_per_vertex attribute names

get_vertices_copy()[source]#

Safe getter for vertices (for slicing)

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_center()[source]#

Safe function to shift vertices so the center of voxel is the origin

to_corner()[source]#

Safe function to shift vertices so the corner of voxel is the origin

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_rasmm()[source]#

Safe function to transform vertices and update state

to_space(target_space)[source]#

Safe function to transform vertices to a particular space using an enum and update state

to_vox()[source]#

Safe function to transform vertices and update state

to_voxmm()[source]#

Safe function to transform vertices 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

StatefulTractogram#

class dipy.io.stateful_tractogram.StatefulTractogram(streamlines, reference, space, *, origin=Origin.NIFTI, data_per_point=None, data_per_streamline=None)[source]#

Bases: object

Class 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:
affine

Getter for the reference affine

data_per_point

Getter for data_per_point

data_per_streamline

Getter for data_per_streamline

dimensions

Getter for the reference dimensions

dtype_dict

Getter for dtype_dict

origin

Getter for origin standard

space

Getter for the current space

space_attributes

Getter for spatial attribute

streamlines

Partially safe getter for streamlines

voxel_order

Getter for the reference voxel order

voxel_sizes

Getter 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_bounding_box()

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.

get_data_per_point_keys()

Return a list of the data_per_point attribute names

get_data_per_streamline_keys()

Return a list of the data_per_streamline attribute names

get_streamlines_copy()

Safe getter for streamlines (for slicing)

is_bbox_in_vox_valid()

Verify that the bounding box is valid in voxel space.

remove_invalid_streamlines(*[, epsilon])

Remove streamlines with invalid coordinates from the object.

to_center()

Safe function to shift streamlines so the center of voxel is the origin

to_corner()

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

—–
get_data_per_point_keys()[source]#

Return a list of the data_per_point attribute names

get_data_per_streamline_keys()[source]#

Return a list of the data_per_streamline attribute names

get_streamlines_copy()[source]#

Safe getter for streamlines (for slicing)

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_center()[source]#

Safe function to shift streamlines so the center of voxel is the origin

to_corner()[source]#

Safe function to shift streamlines so the corner of voxel is the origin

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_rasmm()[source]#

Safe function to transform streamlines and update state

to_space(target_space)[source]#

Safe function to transform streamlines to a particular space using an enum and update state

to_vox()[source]#

Safe function to transform streamlines and update state

to_voxmm()[source]#

Safe function to transform streamlines and update state

property voxel_order#

Getter for the reference voxel order

property voxel_sizes#

Getter for the reference voxel sizes

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_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

Whether to save the file in legacy VTK format or not.

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#

dipy.io.surface.save_pial(fname, vertices, faces, *, metadata=None)[source]#

Save pial file.

Parameters:
fnamestr or Path

Absolute path of the file.

verticesndarray

Vertices.

facesndarray

Faces.

metadatadict, optional

Key-value pairs to encode at the end of the file.

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#

class dipy.io.utils.Space(*values)[source]#

Bases: Enum

Enum to simplify future change to convention

Origin#

class dipy.io.utils.Origin(*values)[source]#

Bases: Enum

Enum to simplify future change to convention

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#

dipy.io.utils.make5d(data)[source]#

Reshape the input to have 5 dimensions.

Adds extra dimensions just before the last dimension.

Parameters:
dataarray-like

The input data to reshape.

Returns:
datandarray

The reshaped 5D data.

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 the incoming data from the 0-1 to the 0-255 range expected in the output.

Returns:
imgNifti1Image class instance with dtype set to store tuples of

uint8 in (R, G, B) order.

Notes

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

True if all spatial attributes match, False otherwise.

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).

load_polydata#

dipy.io.vtk.load_polydata(file_name)[source]#

Load a vtk polydata to a supported format file.

Supported file formats are OBJ, VTK, VTP, FIB, PLY, STL and XML

Parameters:
file_namestring or Path
Returns:
outputvtkPolyData

save_polydata#

dipy.io.vtk.save_polydata(polydata, file_name, *, binary=False, color_array_name=None, legacy_vtk_format=False)[source]#

Save a vtk polydata to a supported format file.

Save formats can be VTK, VTP, FIB, PLY, STL and XML. Color array can be saved as well either by being already in the polydata or by passing it as an argument (color_array).

Parameters:
polydatavtkPolyData

The polydata object to be saved.

file_namestring or Path

The output filename (.vtk, .fib, .ply, .stl and .xml)

binarybool, optional

Save the file in binary format.

color_array_namestr, optional

Name of the color array to save.

legacy_vtk_formatbool, optional

Use legacy VTK file format. Only applied when fury >= 2.0 is installed.

save_vtk_streamlines#

dipy.io.vtk.save_vtk_streamlines(streamlines, filename, *, to_lps=True, binary=False)[source]#

Save streamlines as vtk polydata to a supported format file.

File formats can be OBJ, VTK, VTP, FIB, PLY, STL and XML

Parameters:
streamlineslist

list of 2D arrays or ArraySequence

filenamestring or Path

output filename (.obj, .vtk, .fib, .ply, .stl and .xml)

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.vtk.load_vtk_streamlines(filename, *, to_lps=True)[source]#

Load streamlines from vtk polydata.

Load formats can be VTK, FIB

Parameters:
filenamestring or Path

input filename (.vtk 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

get_polydata_triangles#

dipy.io.vtk.get_polydata_triangles(polydata, dtype=None)[source]#

Get triangles from a vtkPolyData object.

Parameters:
polydatavtkPolyData

The polydata object from which to extract triangles.

dtypedata-type, optional

The desired data type for the output triangles. If None, the default data type will be used.

Returns
——-
trianglesnumpy.ndarray

An array of shape (n_triangles, 3) containing the vertex indices of the triangles.

get_polydata_vertices#

dipy.io.vtk.get_polydata_vertices(polydata, dtype=None)[source]#

Get vertices from a vtkPolyData object.

Parameters:
polydatavtkPolyData

The polydata object from which to extract vertices.

dtypedata-type, optional

The desired data type for the output vertices. If None, the default data type will be used.

Returns
——-
verticesnumpy.ndarray

An array of shape (n_vertices, 3) containing the vertex coordinates.

convert_to_polydata#

dipy.io.vtk.convert_to_polydata(vertices, triangles, data_per_point=None)[source]#

Convert vertices and triangles to a vtkPolyData object.

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:
polydatavtkPolyData

The resulting vtkPolyData object.