streamlines

Multiformat-capable streamline format read / write interface

detect_format(fileobj)

Returns the StreamlinesFile object guessed from the file-like object.

is_supported(fileobj)

Checks if the file-like object if supported by NiBabel.

load(fileobj[, lazy_load])

Loads streamlines in RAS+ and mm space from a file-like object.

save(tractogram, filename, **kwargs)

Saves a tractogram to a file.

Module: streamlines.array_sequence

ArraySequence([iterable, buffer_size])

Sequence of ndarrays having variable first dimension sizes.

concatenate(seqs, axis)

Concatenates multiple ArraySequence objects along an axis.

create_arraysequences_from_generator(gen, n)

Creates ArraySequence objects from a generator yielding tuples

is_array_sequence(obj)

Return True if obj is an array sequence.

is_ndarray_of_int_or_bool(obj)

Module: streamlines.header

Field class defining common header fields in tractogram files

Field()

Header fields common to multiple streamline file formats.

Module: streamlines.tck

Read / write access to TCK streamlines format.

TCK format is defined at http://mrtrix.readthedocs.io/en/latest/getting_started/image_data.html?highlight=format#tracks-file-format-tck

TckFile(tractogram[, header])

Convenience class to encapsulate TCK file format.

Module: streamlines.tractogram

LazyDict(*args, **kwargs)

Dictionary of generator functions.

LazyTractogram([streamlines, ...])

Lazy container for streamlines and their data information.

PerArrayDict([n_rows])

Dictionary for which key access can do slicing on the values.

PerArraySequenceDict([n_rows])

Dictionary for which key access can do slicing on the values.

SliceableDataDict(*args, **kwargs)

Dictionary for which key access can do slicing on the values.

Tractogram([streamlines, ...])

Container for streamlines and their data information.

TractogramItem(streamline, ...)

Class containing information about one streamline.

is_data_dict(obj)

True if obj seems to implement the DataDict API

is_lazy_dict(obj)

True if obj seems to implement the LazyDict API

Module: streamlines.tractogram_file

Define abstract interface for Tractogram file classes

DataError

Raised when data is missing or inconsistent in a tractogram file.

DataWarning

Base class for warnings about tractogram file data.

ExtensionWarning

Base class for warnings about tractogram file extension.

HeaderError

Raised when a tractogram file header contains invalid information.

HeaderWarning

Base class for warnings about tractogram file header.

TractogramFile(tractogram[, header])

Convenience class to encapsulate tractogram file format.

abstractclassmethod(callable)

Module: streamlines.trk

TrkFile(tractogram[, header])

Convenience class to encapsulate TRK file format.

decode_value_from_name(encoded_name)

Decodes a value that has been encoded in the last bytes of a string.

encode_value_in_name(value, name[, max_name_len])

Return name as fixed-length string, appending value as string.

get_affine_rasmm_to_trackvis(header)

get_affine_trackvis_to_rasmm(header)

Get affine mapping trackvis voxelmm space to RAS+ mm space

Module: streamlines.utils

get_affine_from_reference(ref)

Returns the affine defining the reference space.

peek_next(iterable)

Peek next element of iterable.

detect_format

nibabel.streamlines.detect_format(fileobj)

Returns the StreamlinesFile object guessed from the file-like object.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object pointing to a tractogram file (and ready to read from the beginning of the header)

Returns:
tractogram_fileTractogramFile class

The class type guessed from the content of fileobj.

is_supported

nibabel.streamlines.is_supported(fileobj)

Checks if the file-like object if supported by NiBabel.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object pointing to a streamlines file (and ready to read from the beginning of the header)

Returns:
is_supportedboolean

load

nibabel.streamlines.load(fileobj, lazy_load=False)

Loads streamlines in RAS+ and mm space from a file-like object.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object pointing to a streamlines file (and ready to read from the beginning of the streamlines file’s header).

lazy_load{False, True}, optional

If True, load streamlines in a lazy manner i.e. they will not be kept in memory and only be loaded when needed. Otherwise, load all streamlines in memory.

Returns:
tractogram_fileTractogramFile object

Returns an instance of a TractogramFile containing data and metadata of the tractogram loaded from fileobj.

Notes

The streamline coordinate (0,0,0) refers to the center of the voxel.

save

nibabel.streamlines.save(tractogram, filename, **kwargs)

Saves a tractogram to a file.

Parameters:
tractogramTractogram object or TractogramFile object

If Tractogram object, the file format will be guessed from filename and a TractogramFile object will be created using provided keyword arguments. If TractogramFile object, the file format is known and will be used to save its content to filename.

filenamestr

Name of the file where the tractogram will be saved.

**kwargskeyword arguments

Keyword arguments passed to TractogramFile constructor. Should not be specified if tractogram is already an instance of TractogramFile.

ArraySequence

class nibabel.streamlines.array_sequence.ArraySequence(iterable=None, buffer_size=4)

Bases: object

Sequence of ndarrays having variable first dimension sizes.

This is a container that can store multiple ndarrays where each ndarray might have a different first dimension size but a common size for the remaining dimensions.

More generally, an instance of ArraySequence of length $N$ is composed of $N$ ndarrays of shape $(d_1, d_2, … d_D)$ where $d_1$ can vary in length between arrays but $(d_2, …, d_D)$ have to be the same for every ndarray.

Initialize array sequence instance

Parameters:
iterableNone or iterable or ArraySequence, optional

If None, create an empty ArraySequence object. If iterable, create a ArraySequence object initialized from array-like objects yielded by the iterable. If ArraySequence, create a view (no memory is allocated). For an actual copy use copy() instead.

buffer_sizefloat, optional

Size (in Mb) for memory allocation when iterable is a generator.

__init__(iterable=None, buffer_size=4)

Initialize array sequence instance

Parameters:
iterableNone or iterable or ArraySequence, optional

If None, create an empty ArraySequence object. If iterable, create a ArraySequence object initialized from array-like objects yielded by the iterable. If ArraySequence, create a view (no memory is allocated). For an actual copy use copy() instead.

buffer_sizefloat, optional

Size (in Mb) for memory allocation when iterable is a generator.

append(element, cache_build=False)

Appends element to this array sequence.

Append can be a lot faster if it knows that it is appending several elements instead of a single element. In that case it can cache the parameters it uses between append operations, in a “build cache”. To tell append to do this, use cache_build=True. If you use cache_build=True, you need to finalize the append operations with finalize_append().

Parameters:
elementndarray

Element to append. The shape must match already inserted elements shape except for the first dimension.

cache_build{False, True}

Whether to save the build cache from this append routine. If True, append can assume it is the only player updating self, and the caller must finalize self after all append operations, with self.finalize_append().

Returns:
None

Notes

If you need to add multiple elements you should consider ArraySequence.extend.

property common_shape

Matching shape of the elements in this array sequence.

copy()

Creates a copy of this ArraySequence object.

Returns:
seq_copyArraySequence instance

Copy of self.

Notes

We do not simply deepcopy this object because we have a chance to use less memory. For example, if the array sequence being copied is the result of a slicing operation on an array sequence.

extend(elements)

Appends all elements to this array sequence.

Parameters:
elementsiterable of ndarrays or ArraySequence object

If iterable of ndarrays, each ndarray will be concatenated along the first dimension then appended to the data of this ArraySequence. If ArraySequence object, its data are simply appended to the data of this ArraySequence.

Returns:
None

Notes

The shape of the elements to be added must match the one of the data of this ArraySequence except for the first dimension.

finalize_append()

Finalize process of appending several elements to self

append() can be a lot faster if it knows that it is appending several elements instead of a single element. To tell the append method this is the case, use cache_build=True. This method finalizes the series of append operations after a call to append() with cache_build=True.

get_data()

Returns a copy of the elements in this array sequence.

Notes

To modify the data on this array sequence, one can use in-place mathematical operators (e.g., seq += …) or the use assignment operator (i.e, seq[…] = value).

property is_array_sequence
property is_sliced_view
classmethod load(filename)

Loads a ArraySequence object from a .npz file.

save(filename)

Saves this ArraySequence object to a .npz file.

shrink_data()
property total_nb_rows

Total number of rows in this array sequence.

concatenate

nibabel.streamlines.array_sequence.concatenate(seqs, axis)

Concatenates multiple ArraySequence objects along an axis.

Parameters:
seqs: iterable of :class:`ArraySequence` objects

Sequences to concatenate.

axisint

Axis along which the sequences will be concatenated.

Returns:
new_seq: ArraySequence object

New ArraySequence object which is the result of concatenating multiple sequences along the given axis.

create_arraysequences_from_generator

nibabel.streamlines.array_sequence.create_arraysequences_from_generator(gen, n, buffer_sizes=None)

Creates ArraySequence objects from a generator yielding tuples

Parameters:
gengenerator

Generator yielding a size n tuple containing the values to put in the array sequences.

nint

Number of ArraySequences object to create.

buffer_sizeslist of float, optional

Sizes (in Mb) for each ArraySequence’s buffer.

is_array_sequence

nibabel.streamlines.array_sequence.is_array_sequence(obj)

Return True if obj is an array sequence.

is_ndarray_of_int_or_bool

nibabel.streamlines.array_sequence.is_ndarray_of_int_or_bool(obj)

Field

class nibabel.streamlines.header.Field

Bases: object

Header fields common to multiple streamline file formats.

In IPython, use nibabel.streamlines.Field?? to list them.

__init__(*args, **kwargs)
DIMENSIONS = 'dimensions'
ENDIANNESS = 'endianness'
MAGIC_NUMBER = 'magic_number'
METHOD = 'method'
NB_POINTS = 'nb_points'
NB_PROPERTIES_PER_STREAMLINE = 'nb_properties_per_streamline'
NB_SCALARS_PER_POINT = 'nb_scalars_per_point'
NB_STREAMLINES = 'nb_streamlines'
ORIGIN = 'origin'
STEP_SIZE = 'step_size'
VOXEL_ORDER = 'voxel_order'
VOXEL_SIZES = 'voxel_sizes'
VOXEL_TO_RASMM = 'voxel_to_rasmm'

TckFile

class nibabel.streamlines.tck.TckFile(tractogram, header=None)

Bases: TractogramFile

Convenience class to encapsulate TCK file format.

Notes

MRtrix (so its file format: TCK) considers streamlines coordinates to be in world space (RAS+ and mm space). MRtrix refers to that space as the “real” or “scanner” space [1].

Moreover, when streamlines are mapped back to voxel space [2], a streamline point located at an integer coordinate (i,j,k) is considered to be at the center of the corresponding voxel. This is in contrast with TRK’s internal convention where it would have referred to a corner.

NiBabel’s streamlines internal representation follows the same convention as MRtrix.

Parameters:
tractogramTractogram object

Tractogram that will be contained in this TckFile.

headerNone or dict, optional

Metadata associated to this tractogram file. If None, make default empty header.

Notes

Streamlines of the tractogram are assumed to be in RAS+ and mm space. It is also assumed that when streamlines are mapped back to voxel space, a streamline point located at an integer coordinate (i,j,k) is considered to be at the center of the corresponding voxel. This is in contrast with TRK’s internal convention where it would have referred to a corner.

__init__(tractogram, header=None)
Parameters:
tractogramTractogram object

Tractogram that will be contained in this TckFile.

headerNone or dict, optional

Metadata associated to this tractogram file. If None, make default empty header.

Notes

Streamlines of the tractogram are assumed to be in RAS+ and mm space. It is also assumed that when streamlines are mapped back to voxel space, a streamline point located at an integer coordinate (i,j,k) is considered to be at the center of the corresponding voxel. This is in contrast with TRK’s internal convention where it would have referred to a corner.

EOF_DELIMITER = array([[inf, inf, inf]], dtype=float32)
FIBER_DELIMITER = array([[nan, nan, nan]], dtype=float32)
MAGIC_NUMBER = b'mrtrix tracks'
SUPPORTS_DATA_PER_POINT = False
SUPPORTS_DATA_PER_STREAMLINE = False
classmethod create_empty_header()

Return an empty compliant TCK header as dict

classmethod is_correct_format(fileobj)

Check if the file is in TCK format.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object in binary mode pointing to TCK file (and ready to read from the beginning of the TCK header). Note that calling this function does not change the file position.

Returns:
is_correct_format{True, False}

Returns True if fileobj is compatible with TCK format, otherwise returns False.

classmethod load(fileobj, lazy_load=False)

Loads streamlines from a filename or file-like object.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object in binary mode pointing to TCK file (and ready to read from the beginning of the TCK header). Note that calling this function does not change the file position.

lazy_load{False, True}, optional

If True, load streamlines in a lazy manner i.e. they will not be kept in memory. Otherwise, load all streamlines in memory.

Returns:
tck_fileTckFile object

Returns an object containing tractogram data and header information.

Notes

Streamlines of the tractogram are assumed to be in RAS+ and mm space. It is also assumed that when streamlines are mapped back to voxel space, a streamline point located at an integer coordinate (i,j,k) is considered to be at the center of the corresponding voxel. This is in contrast with TRK’s internal convention where it would have referred to a corner.

save(fileobj)

Save tractogram to a filename or file-like object using TCK format.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object in binary mode pointing to TCK file (and ready to write from the beginning of the TCK header data).

LazyDict

class nibabel.streamlines.tractogram.LazyDict(*args, **kwargs)

Bases: MutableMapping

Dictionary of generator functions.

This container behaves like a dictionary but it makes sure its elements are callable objects that it assumes are generator functions yielding values. When getting the element associated with a given key, the element (i.e. a generator function) is first called before being returned.

__init__(*args, **kwargs)

LazyTractogram

class nibabel.streamlines.tractogram.LazyTractogram(streamlines=None, data_per_streamline=None, data_per_point=None, affine_to_rasmm=None)

Bases: Tractogram

Lazy container for streamlines and their data information.

This container behaves lazily as it uses generator functions to manage streamlines and their data information. This container is thus memory friendly since it doesn’t require having all this data loaded in memory.

Streamlines of a tractogram can be in any coordinate system of your choice as long as you provide the correct affine_to_rasmm matrix, at construction time. When applied to streamlines coordinates, that transformation matrix should bring the streamlines back to world space (RAS+ and mm space) [3].

Moreover, when streamlines are mapped back to voxel space [4], a streamline point located at an integer coordinate (i,j,k) is considered to be at the center of the corresponding voxel. This is in contrast with other conventions where it might have referred to a corner.

Notes

LazyTractogram objects do not support indexing currently. LazyTractogram objects are suited for operations that can be linearized such as applying an affine transformation or converting streamlines from one file format to another.

References

Attributes:
streamlinesgenerator function

Generator function yielding streamlines. Each streamline is an ndarray of shape ($N_t$, 3) where $N_t$ is the number of points of streamline $t$.

data_per_streamlineinstance of LazyDict

Dictionary where the items are (str, instantiated generator). Each key represents a piece of information $i$ to be kept alongside every streamline, and its associated value is a generator function yielding that information via ndarrays of shape ($P_i$,) where $P_i$ is the number of values to store for that particular piece of information $i$.

data_per_pointLazyDict object

Dictionary where the items are (str, instantiated generator). Each key represents a piece of information $i$ to be kept alongside every point of every streamline, and its associated value is a generator function yielding that information via ndarrays of shape ($N_t$, $M_i$) where $N_t$ is the number of points for a particular streamline $t$ and $M_i$ is the number of values to store for that particular piece of information $i$.

Parameters:
streamlinesgenerator function, optional

Generator function yielding streamlines. Each streamline is an ndarray of shape ($N_t$, 3) where $N_t$ is the number of points of streamline $t$.

data_per_streamlinedict of generator functions, optional

Dictionary where the items are (str, generator function). Each key represents an information $i$ to be kept alongside every streamline, and its associated value is a generator function yielding that information via ndarrays of shape ($P_i$,) where $P_i$ is the number of values to store for that particular information $i$.

data_per_pointdict of generator functions, optional

Dictionary where the items are (str, generator function). Each key represents an information $i$ to be kept alongside every point of every streamline, and its associated value is a generator function yielding that information via ndarrays of shape ($N_t$, $M_i$) where $N_t$ is the number of points for a particular streamline $t$ and $M_i$ is the number of values to store for that particular information $i$.

affine_to_rasmmndarray of shape (4, 4) or None, optional

Transformation matrix that brings the streamlines contained in this tractogram to RAS+ and mm space where coordinate (0,0,0) refers to the center of the voxel. By default, the streamlines are in an unknown space, i.e. affine_to_rasmm is None.

__init__(streamlines=None, data_per_streamline=None, data_per_point=None, affine_to_rasmm=None)
Parameters:
streamlinesgenerator function, optional

Generator function yielding streamlines. Each streamline is an ndarray of shape ($N_t$, 3) where $N_t$ is the number of points of streamline $t$.

data_per_streamlinedict of generator functions, optional

Dictionary where the items are (str, generator function). Each key represents an information $i$ to be kept alongside every streamline, and its associated value is a generator function yielding that information via ndarrays of shape ($P_i$,) where $P_i$ is the number of values to store for that particular information $i$.

data_per_pointdict of generator functions, optional

Dictionary where the items are (str, generator function). Each key represents an information $i$ to be kept alongside every point of every streamline, and its associated value is a generator function yielding that information via ndarrays of shape ($N_t$, $M_i$) where $N_t$ is the number of points for a particular streamline $t$ and $M_i$ is the number of values to store for that particular information $i$.

affine_to_rasmmndarray of shape (4, 4) or None, optional

Transformation matrix that brings the streamlines contained in this tractogram to RAS+ and mm space where coordinate (0,0,0) refers to the center of the voxel. By default, the streamlines are in an unknown space, i.e. affine_to_rasmm is None.

apply_affine(affine, lazy=True)

Applies an affine transformation to the streamlines.

The transformation given by the affine matrix is applied after any other pending transformations to the streamline points.

Parameters:
affine2D array (4,4)

Transformation matrix that will be applied on each streamline.

lazyTrue, optional

Should always be True for LazyTractogram object. Doing otherwise will raise a ValueError.

Returns:
lazy_tractogramLazyTractogram object

A copy of this LazyTractogram instance but with a transformation to be applied on the streamlines.

copy()

Returns a copy of this LazyTractogram object.

property data
property data_per_point
property data_per_streamline
extend(other)

Appends the data of another Tractogram.

Data that will be appended includes the streamlines and the content of both dictionaries data_per_streamline and data_per_point.

Parameters:
otherTractogram object

Its data will be appended to the data of this tractogram.

Returns:
None

Notes

The entries in both dictionaries self.data_per_streamline and self.data_per_point must match respectively those contained in the other tractogram.

classmethod from_data_func(data_func)

Creates an instance from a generator function.

The generator function must yield TractogramItem objects.

Parameters:
data_funcgenerator function yielding TractogramItem objects

Generator function that whenever is called starts yielding TractogramItem objects that will be used to instantiate a LazyTractogram.

Returns:
lazy_tractogramLazyTractogram object

New lazy tractogram.

classmethod from_tractogram(tractogram)

Creates a LazyTractogram object from a Tractogram object.

Parameters:
tractogramTractgogram object

Tractogram from which to create a LazyTractogram object.

Returns:
lazy_tractogramLazyTractogram object

New lazy tractogram.

property streamlines
to_world(lazy=True)

Brings the streamlines to world space (i.e. RAS+ and mm).

The transformation is applied after any other pending transformations to the streamline points.

Parameters:
lazyTrue, optional

Should always be True for LazyTractogram object. Doing otherwise will raise a ValueError.

Returns:
lazy_tractogramLazyTractogram object

A copy of this LazyTractogram instance but with a transformation to be applied on the streamlines.

PerArrayDict

class nibabel.streamlines.tractogram.PerArrayDict(n_rows=0, *args, **kwargs)

Bases: SliceableDataDict

Dictionary for which key access can do slicing on the values.

This container behaves like a standard dictionary but extends key access to allow keys for key access to be indices slicing into the contained ndarray values. The elements must also be ndarrays.

In addition, it makes sure the amount of data contained in those ndarrays matches the number of streamlines given at the instantiation of this instance.

Parameters:
n_rowsNone or int, optional

Number of rows per value in each key, value pair or None for not specified.

*args
**kwargs

Positional and keyword arguments, passed straight through the dict constructor.

__init__(n_rows=0, *args, **kwargs)
extend(other)

Appends the elements of another PerArrayDict.

That is, for each entry in this dictionary, we append the elements coming from the other dictionary at the corresponding entry.

Parameters:
otherPerArrayDict object

Its data will be appended to the data of this dictionary.

Returns:
None

Notes

The keys in both dictionaries must be the same.

PerArraySequenceDict

class nibabel.streamlines.tractogram.PerArraySequenceDict(n_rows=0, *args, **kwargs)

Bases: PerArrayDict

Dictionary for which key access can do slicing on the values.

This container behaves like a standard dictionary but extends key access to allow keys for key access to be indices slicing into the contained ndarray values. The elements must also be ArraySequence.

In addition, it makes sure the amount of data contained in those array sequences matches the number of elements given at the instantiation of the instance.

__init__(n_rows=0, *args, **kwargs)

SliceableDataDict

class nibabel.streamlines.tractogram.SliceableDataDict(*args, **kwargs)

Bases: MutableMapping

Dictionary for which key access can do slicing on the values.

This container behaves like a standard dictionary but extends key access to allow keys for key access to be indices slicing into the contained ndarray values.

Parameters:
*args
**kwargs

Positional and keyword arguments, passed straight through the dict constructor.

__init__(*args, **kwargs)

Tractogram

class nibabel.streamlines.tractogram.Tractogram(streamlines=None, data_per_streamline=None, data_per_point=None, affine_to_rasmm=None)

Bases: object

Container for streamlines and their data information.

Streamlines of a tractogram can be in any coordinate system of your choice as long as you provide the correct affine_to_rasmm matrix, at construction time. When applied to streamlines coordinates, that transformation matrix should bring the streamlines back to world space (RAS+ and mm space) [5].

Moreover, when streamlines are mapped back to voxel space [6], a streamline point located at an integer coordinate (i,j,k) is considered to be at the center of the corresponding voxel. This is in contrast with other conventions where it might have referred to a corner.

References

Attributes:
streamlinesArraySequence object

Sequence of $T$ streamlines. Each streamline is an ndarray of shape ($N_t$, 3) where $N_t$ is the number of points of streamline $t$.

data_per_streamlinePerArrayDict object

Dictionary where the items are (str, 2D array). Each key represents a piece of information $i$ to be kept alongside every streamline, and its associated value is a 2D array of shape ($T$, $P_i$) where $T$ is the number of streamlines and $P_i$ is the number of values to store for that particular piece of information $i$.

data_per_pointPerArraySequenceDict object

Dictionary where the items are (str, ArraySequence). Each key represents a piece of information $i$ to be kept alongside every point of every streamline, and its associated value is an iterable of ndarrays of shape ($N_t$, $M_i$) where $N_t$ is the number of points for a particular streamline $t$ and $M_i$ is the number values to store for that particular piece of information $i$.

Parameters:
streamlinesiterable of ndarrays or ArraySequence, optional

Sequence of $T$ streamlines. Each streamline is an ndarray of shape ($N_t$, 3) where $N_t$ is the number of points of streamline $t$.

data_per_streamlinedict of iterable of ndarrays, optional

Dictionary where the items are (str, iterable). Each key represents an information $i$ to be kept alongside every streamline, and its associated value is an iterable of ndarrays of shape ($P_i$,) where $P_i$ is the number of scalar values to store for that particular information $i$.

data_per_pointdict of iterable of ndarrays, optional

Dictionary where the items are (str, iterable). Each key represents an information $i$ to be kept alongside every point of every streamline, and its associated value is an iterable of ndarrays of shape ($N_t$, $M_i$) where $N_t$ is the number of points for a particular streamline $t$ and $M_i$ is the number scalar values to store for that particular information $i$.

affine_to_rasmmndarray of shape (4, 4) or None, optional

Transformation matrix that brings the streamlines contained in this tractogram to RAS+ and mm space where coordinate (0,0,0) refers to the center of the voxel. By default, the streamlines are in an unknown space, i.e. affine_to_rasmm is None.

__init__(streamlines=None, data_per_streamline=None, data_per_point=None, affine_to_rasmm=None)
Parameters:
streamlinesiterable of ndarrays or ArraySequence, optional

Sequence of $T$ streamlines. Each streamline is an ndarray of shape ($N_t$, 3) where $N_t$ is the number of points of streamline $t$.

data_per_streamlinedict of iterable of ndarrays, optional

Dictionary where the items are (str, iterable). Each key represents an information $i$ to be kept alongside every streamline, and its associated value is an iterable of ndarrays of shape ($P_i$,) where $P_i$ is the number of scalar values to store for that particular information $i$.

data_per_pointdict of iterable of ndarrays, optional

Dictionary where the items are (str, iterable). Each key represents an information $i$ to be kept alongside every point of every streamline, and its associated value is an iterable of ndarrays of shape ($N_t$, $M_i$) where $N_t$ is the number of points for a particular streamline $t$ and $M_i$ is the number scalar values to store for that particular information $i$.

affine_to_rasmmndarray of shape (4, 4) or None, optional

Transformation matrix that brings the streamlines contained in this tractogram to RAS+ and mm space where coordinate (0,0,0) refers to the center of the voxel. By default, the streamlines are in an unknown space, i.e. affine_to_rasmm is None.

property affine_to_rasmm

Affine bringing streamlines in this tractogram to RAS+mm.

apply_affine(affine, lazy=False)

Applies an affine transformation on the points of each streamline.

If lazy is not specified, this is performed in-place.

Parameters:
affinendarray of shape (4, 4)

Transformation that will be applied to every streamline.

lazy{False, True}, optional

If True, streamlines are not transformed in-place and a LazyTractogram object is returned. Otherwise, streamlines are modified in-place.

Returns:
tractogramTractogram or LazyTractogram object

Tractogram where the streamlines have been transformed according to the given affine transformation. If the lazy option is true, it returns a LazyTractogram object, otherwise it returns a reference to this Tractogram object with updated streamlines.

copy()

Returns a copy of this Tractogram object.

property data_per_point
property data_per_streamline
extend(other)

Appends the data of another Tractogram.

Data that will be appended includes the streamlines and the content of both dictionaries data_per_streamline and data_per_point.

Parameters:
otherTractogram object

Its data will be appended to the data of this tractogram.

Returns:
None

Notes

The entries in both dictionaries self.data_per_streamline and self.data_per_point must match respectively those contained in the other tractogram.

property streamlines
to_world(lazy=False)

Brings the streamlines to world space (i.e. RAS+ and mm).

If lazy is not specified, this is performed in-place.

Parameters:
lazy{False, True}, optional

If True, streamlines are not transformed in-place and a LazyTractogram object is returned. Otherwise, streamlines are modified in-place.

Returns:
tractogramTractogram or LazyTractogram object

Tractogram where the streamlines have been sent to world space. If the lazy option is true, it returns a LazyTractogram object, otherwise it returns a reference to this Tractogram object with updated streamlines.

TractogramItem

class nibabel.streamlines.tractogram.TractogramItem(streamline, data_for_streamline, data_for_points)

Bases: object

Class containing information about one streamline.

TractogramItem objects have three public attributes: streamline, data_for_streamline, and data_for_points.

Parameters:
streamlinendarray shape (N, 3)

Points of this streamline represented as an ndarray of shape (N, 3) where N is the number of points.

data_for_streamlinedict

Dictionary containing some data associated with this particular streamline. Each key k is mapped to a ndarray of shape (Pt,), where Pt is the dimension of the data associated with key k.

data_for_pointsdict

Dictionary containing some data associated to each point of this particular streamline. Each key k is mapped to a ndarray of shape (Nt, Mk), where Nt is the number of points of this streamline and Mk is the dimension of the data associated with key k.

__init__(streamline, data_for_streamline, data_for_points)

is_data_dict

nibabel.streamlines.tractogram.is_data_dict(obj)

True if obj seems to implement the DataDict API

is_lazy_dict

nibabel.streamlines.tractogram.is_lazy_dict(obj)

True if obj seems to implement the LazyDict API

DataError

class nibabel.streamlines.tractogram_file.DataError

Bases: Exception

Raised when data is missing or inconsistent in a tractogram file.

__init__(*args, **kwargs)

DataWarning

class nibabel.streamlines.tractogram_file.DataWarning

Bases: Warning

Base class for warnings about tractogram file data.

__init__(*args, **kwargs)

ExtensionWarning

class nibabel.streamlines.tractogram_file.ExtensionWarning

Bases: Warning

Base class for warnings about tractogram file extension.

__init__(*args, **kwargs)

HeaderError

class nibabel.streamlines.tractogram_file.HeaderError

Bases: Exception

Raised when a tractogram file header contains invalid information.

__init__(*args, **kwargs)

HeaderWarning

class nibabel.streamlines.tractogram_file.HeaderWarning

Bases: Warning

Base class for warnings about tractogram file header.

__init__(*args, **kwargs)

TractogramFile

class nibabel.streamlines.tractogram_file.TractogramFile(tractogram, header=None)

Bases: ABC

Convenience class to encapsulate tractogram file format.

__init__(tractogram, header=None)
property affine

voxmm -> rasmm affine.

classmethod create_empty_header()

Returns an empty header for this streamlines file format.

property header
abstract classmethod is_correct_format(fileobj)

Checks if the file has the right streamlines file format.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object pointing to a streamlines file (and ready to read from the beginning of the header).

Returns:
is_correct_format{True, False}

Returns True if fileobj is in the right streamlines file format, otherwise returns False.

abstract classmethod load(fileobj, lazy_load=True)

Loads streamlines from a filename or file-like object.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object pointing to a streamlines file (and ready to read from the beginning of the header).

lazy_load{False, True}, optional

If True, load streamlines in a lazy manner i.e. they will not be kept in memory. Otherwise, load all streamlines in memory.

Returns:
tractogram_fileTractogramFile object

Returns an object containing tractogram data and header information.

abstract save(fileobj)

Saves streamlines to a filename or file-like object.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object opened and ready to write.

property streamlines
property tractogram

abstractclassmethod

class nibabel.streamlines.tractogram_file.abstractclassmethod(callable)

Bases: classmethod

__init__(callable)

TrkFile

class nibabel.streamlines.trk.TrkFile(tractogram, header=None)

Bases: TractogramFile

Convenience class to encapsulate TRK file format.

Notes

TrackVis (so its file format: TRK) considers the streamline coordinate (0,0,0) to be in the corner of the voxel whereas NiBabel’s streamlines internal representation (Voxel space) assumes (0,0,0) to be in the center of the voxel.

Thus, streamlines are shifted by half a voxel on load and are shifted back on save.

Parameters:
tractogramTractogram object

Tractogram that will be contained in this TrkFile.

headerdict, optional

Metadata associated to this tractogram file.

Notes

Streamlines of the tractogram are assumed to be in RAS+ and mm space where coordinate (0,0,0) refers to the center of the voxel.

__init__(tractogram, header=None)
Parameters:
tractogramTractogram object

Tractogram that will be contained in this TrkFile.

headerdict, optional

Metadata associated to this tractogram file.

Notes

Streamlines of the tractogram are assumed to be in RAS+ and mm space where coordinate (0,0,0) refers to the center of the voxel.

HEADER_SIZE = 1000
MAGIC_NUMBER = b'TRACK'
SUPPORTS_DATA_PER_POINT = True
SUPPORTS_DATA_PER_STREAMLINE = True
classmethod create_empty_header(endianness=None)

Return an empty compliant TRK header as dict

classmethod is_correct_format(fileobj)

Check if the file is in TRK format.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object pointing to TRK file (and ready to read from the beginning of the TRK header data). Note that calling this function does not change the file position.

Returns:
is_correct_format{True, False}

Returns True if fileobj is compatible with TRK format, otherwise returns False.

classmethod load(fileobj, lazy_load=False)

Loads streamlines from a filename or file-like object.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object pointing to TRK file (and ready to read from the beginning of the TRK header). Note that calling this function does not change the file position.

lazy_load{False, True}, optional

If True, load streamlines in a lazy manner i.e. they will not be kept in memory. Otherwise, load all streamlines in memory.

Returns:
trk_fileTrkFile object

Returns an object containing tractogram data and header information.

Notes

Streamlines of the returned tractogram are assumed to be in RAS and mm space where coordinate (0,0,0) refers to the center of the voxel.

save(fileobj)

Save tractogram to a filename or file-like object using TRK format.

Parameters:
fileobjstring or file-like object

If string, a filename; otherwise an open file-like object pointing to TRK file (and ready to write from the beginning of the TRK header data).

decode_value_from_name

nibabel.streamlines.trk.decode_value_from_name(encoded_name)

Decodes a value that has been encoded in the last bytes of a string.

Check encode_value_in_name() to see how the value has been encoded.

Parameters:
encoded_namebytes

Name in which a value has been encoded or not.

Returns:
namebytes

Name without the encoded value.

valueint

Value decoded from the name.

encode_value_in_name

nibabel.streamlines.trk.encode_value_in_name(value, name, max_name_len=20)

Return name as fixed-length string, appending value as string.

Form output from name if value <= 1 else name + \ + str(value).

Return output as fixed length string length max_name_len, padded with \.

This function also verifies that the modified length of name is less than max_name_len.

Parameters:
valueint

Integer value to encode.

namestr

Name to which we may append an ascii / latin-1 representation of value.

max_name_lenint, optional

Maximum length of byte string that output can have.

Returns:
encoded_namebytes

Name maybe followed by \ and ascii / latin-1 representation of value, padded with \ bytes.

get_affine_rasmm_to_trackvis

nibabel.streamlines.trk.get_affine_rasmm_to_trackvis(header)

get_affine_trackvis_to_rasmm

nibabel.streamlines.trk.get_affine_trackvis_to_rasmm(header)

Get affine mapping trackvis voxelmm space to RAS+ mm space

The streamlines in a trackvis file are in ‘voxelmm’ space, where the coordinates refer to the corner of the voxel.

Compute the affine matrix that will bring them back to RAS+ mm space, where the coordinates refer to the center of the voxel.

Parameters:
headerdict or ndarray

Dict or numpy structured array containing trackvis header.

Returns:
aff_tv2rasshape (4, 4) array

Affine array mapping coordinates in ‘voxelmm’ space to RAS+ mm space.

get_affine_from_reference

nibabel.streamlines.utils.get_affine_from_reference(ref)

Returns the affine defining the reference space.

Parameters:
refstr or Nifti1Image object or ndarray shape (4, 4)

If str then it’s the filename of reference file that will be loaded using nibabel.load() in order to obtain the affine. If Nifti1Image object then the affine is obtained from it. If ndarray shape (4, 4) then it’s the affine.

Returns:
affinendarray (4, 4)

Transformation matrix mapping voxel space to RAS+mm space.

peek_next

nibabel.streamlines.utils.peek_next(iterable)

Peek next element of iterable.

Parameters:
iterable

Iterable to peek the next element from.

Returns:
next_item

Element peeked from iterable.

new_iterable

Iterable behaving like if the original iterable was untouched.