gifti

GIfTI format IO

gifti

Classes defining Gifti objects

Module: gifti.gifti

Classes defining Gifti objects

The Gifti specification was (at time of writing) available as a PDF download from http://www.nitrc.org/projects/gifti/

GiftiCoordSystem([dataspace, xformspace, xform])

Gifti coordinate system transform matrix

GiftiDataArray([data, intent, datatype, ...])

Container for Gifti numerical data array and associated metadata

GiftiImage([header, extra, file_map, meta, ...])

GIFTI image object

GiftiLabel([key, red, green, blue, alpha])

Gifti label: association of integer key with optional RGBA values

GiftiLabelTable()

Gifti label table: a sequence of key, label pairs

GiftiMetaData(*args, **kwargs)

A sequence of GiftiNVPairs containing metadata for a gifti data array

GiftiNVPairs([name, value])

Gifti name / value pairs

Module: gifti.parse_gifti_fast

GiftiImageParser([encoding, buffer_size, ...])

Parameters:

GiftiParseError

Gifti-specific parsing error

read_data_block(darray, fname, data, mmap)

Parses data from a <Data> element, or loads from an external file.

Module: gifti.util

GiftiCoordSystem

class nibabel.gifti.gifti.GiftiCoordSystem(dataspace=0, xformspace=0, xform=None)

Bases: XmlSerializable

Gifti coordinate system transform matrix

Quotes are from the gifti spec dated 2011-01-14.

“For a DataArray with an Intent NIFTI_INTENT_POINTSET, this element describes the stereotaxic space of the data before and after the application of a transformation matrix. The most common stereotaxic space is the Talairach Space that places the origin at the anterior commissure and the negative X, Y, and Z axes correspond to left, posterior, and inferior respectively. At least one CoordinateSystemTransformMatrix is required in a DataArray with an intent of NIFTI_INTENT_POINTSET. Multiple CoordinateSystemTransformMatrix elements may be used to describe the transformation to multiple spaces.”

Attributes:
dataspaceint

From the spec: Contains the stereotaxic space of a DataArray’s data prior to application of the transformation matrix. The stereotaxic space should be one of:

  • NIFTI_XFORM_UNKNOWN

  • NIFTI_XFORM_SCANNER_ANAT

  • NIFTI_XFORM_ALIGNED_ANAT

  • NIFTI_XFORM_TALAIRACH

  • NIFTI_XFORM_MNI_152

xformspaceint

Spec: “Contains the stereotaxic space of a DataArray’s data after application of the transformation matrix. See the DataSpace element for a list of stereotaxic spaces.”

xformarray-like shape (4, 4)

Affine transformation matrix

__init__(dataspace=0, xformspace=0, xform=None)
print_summary()

GiftiDataArray

class nibabel.gifti.gifti.GiftiDataArray(data=None, intent='NIFTI_INTENT_NONE', datatype=None, encoding='GIFTI_ENCODING_B64GZ', endian='little', coordsys=None, ordering='C', meta=None, ext_fname='', ext_offset=0)

Bases: XmlSerializable

Container for Gifti numerical data array and associated metadata

Quotes are from the gifti spec dated 2011-01-14.

Description of DataArray in spec:

“This element contains the numeric data and its related metadata. The CoordinateSystemTransformMatrix child is only used when the DataArray’s Intent is NIFTI_INTENT_POINTSET. FileName and FileOffset are required if the data is stored in an external file.”

Attributes:
darrayNone or ndarray

Data array

intentint

NIFTI intent code, see nifti1.intent_codes

datatypeint

NIFTI data type codes, see nifti1.data_type_codes. From the spec: “This required attribute describes the numeric type of the data contained in a Data Array and are limited to the types displayed in the table:

NIFTI_TYPE_UINT8 : Unsigned, 8-bit bytes. NIFTI_TYPE_INT32 : Signed, 32-bit integers. NIFTI_TYPE_FLOAT32 : 32-bit single precision floating point.”

At the moment, we do not enforce that the datatype is one of these three.

encodingstring

Encoding of the data, see util.gifti_encoding_codes; default is GIFTI_ENCODING_B64GZ.

endianstring

The Endianness to store the data array. Should correspond to the machine endianness. Default is system byteorder.

coordsysGiftiCoordSystem instance

Input and output coordinate system with transformation matrix between the two.

ind_ordint

The ordering of the array. see util.array_index_order_codes. Default is RowMajorOrder - C ordering

metaGiftiMetaData instance

An instance equivalent to a dictionary for metadata information.

ext_fnamestr

Filename in which data is stored, or empty string if no corresponding filename.

ext_offsetint

Position in bytes within ext_fname at which to start reading data.

Returns a shell object that cannot be saved.

__init__(data=None, intent='NIFTI_INTENT_NONE', datatype=None, encoding='GIFTI_ENCODING_B64GZ', endian='little', coordsys=None, ordering='C', meta=None, ext_fname='', ext_offset=0)

Returns a shell object that cannot be saved.

property metadata

Returns metadata as dictionary

property num_dim
print_summary()

GiftiImage

class nibabel.gifti.gifti.GiftiImage(header=None, extra=None, file_map=None, meta=None, labeltable=None, darrays=None, version='1.0')

Bases: XmlSerializable, SerializableImage

GIFTI image object

The Gifti spec suggests using the following suffixes to your filename when saving each specific type of data:

.gii

Generic GIFTI File

.coord.gii

Coordinates

.func.gii

Functional

.label.gii

Labels

.rgba.gii

RGB or RGBA

.shape.gii

Shape

.surf.gii

Surface

.tensor.gii

Tensors

.time.gii

Time Series

.topo.gii

Topology

The Gifti file is stored in endian convention of the current machine.

__init__(header=None, extra=None, file_map=None, meta=None, labeltable=None, darrays=None, version='1.0')
add_gifti_data_array(dataarr)

Adds a data array to the GiftiImage

Parameters:
dataarrGiftiDataArray instance
agg_data(intent_code=None)

Aggregate GIFTI data arrays into an ndarray or tuple of ndarray

In the general case, the numpy data array is extracted from each GiftiDataArray object and returned in a tuple, in the order they are found in the GIFTI image.

If all GiftiDataArray s have intent of 2001 (NIFTI_INTENT_TIME_SERIES), then the data arrays are concatenated as columns, producing a vertex-by-time array. If an intent_code is passed, data arrays are filtered by the selected intents, before being aggregated. This may be useful for images containing several intents, or ensuring an expected data type in an image of uncertain provenance. If intent_code is a tuple, then a tuple will be returned with the result of agg_data for each element, in order. This may be useful for ensuring that expected data arrives in a consistent order.

Parameters:
intent_codeNone, string, integer or tuple of strings or integers, optional

code(s) specifying nifti intent

Returns:
tuple of ndarrays or ndarray

If the input is a tuple, the returned tuple will match the order.

Examples

Consider a surface GIFTI file:

>>> import nibabel as nib
>>> from nibabel.testing import test_data
>>> surf_img = nib.load(test_data('gifti', 'ascii.gii'))

The coordinate data, which is indicated by the NIFTI_INTENT_POINTSET intent code, may be retrieved using any of the following equivalent calls:

>>> coords = surf_img.agg_data('NIFTI_INTENT_POINTSET')
>>> coords_2 = surf_img.agg_data('pointset')
>>> coords_3 = surf_img.agg_data(1008)  # Numeric code for pointset
>>> print(np.array2string(coords, precision=3))
[[-16.072 -66.188  21.267]
 [-16.706 -66.054  21.233]
 [-17.614 -65.402  21.071]]
>>> np.array_equal(coords, coords_2)
True
>>> np.array_equal(coords, coords_3)
True

Similarly, the triangle mesh can be retrieved using various intent specifiers:

>>> triangles = surf_img.agg_data('NIFTI_INTENT_TRIANGLE')
>>> triangles_2 = surf_img.agg_data('triangle')
>>> triangles_3 = surf_img.agg_data(1009)  # Numeric code for pointset
>>> print(np.array2string(triangles))
[0 1 2]
>>> np.array_equal(triangles, triangles_2)
True
>>> np.array_equal(triangles, triangles_3)
True

All arrays can be retrieved as a tuple by omitting the intent code:

>>> coords_4, triangles_4 = surf_img.agg_data()
>>> np.array_equal(coords, coords_4)
True
>>> np.array_equal(triangles, triangles_4)
True

Finally, a tuple of intent codes may be passed in order to select the arrays in a specific order:

>>> triangles_5, coords_5 = surf_img.agg_data(('triangle', 'pointset'))
>>> np.array_equal(triangles, triangles_5)
True
>>> np.array_equal(coords, coords_5)
True

The following image is a GIFTI file with ten (10) data arrays of the same size, and with intent code 2001 (NIFTI_INTENT_TIME_SERIES):

>>> func_img = nib.load(test_data('gifti', 'task.func.gii'))

When aggregating time series data, these arrays are concatenated into a single, vertex-by-timestep array:

>>> series = func_img.agg_data()
>>> series.shape
(642, 10)

In the case of a GIFTI file with unknown data arrays, it may be preferable to specify the intent code, so that a time series array is always returned:

>>> series_2 = func_img.agg_data('NIFTI_INTENT_TIME_SERIES')
>>> series_3 = func_img.agg_data('time series')
>>> series_4 = func_img.agg_data(2001)
>>> np.array_equal(series, series_2)
True
>>> np.array_equal(series, series_3)
True
>>> np.array_equal(series, series_4)
True

Requesting a data array from a GIFTI file with no matching intent codes will result in an empty tuple:

>>> surf_img.agg_data('time series')
()
>>> func_img.agg_data('triangle')
()
files_types: tuple[tuple[str, str | None], ...] = (('image', '.gii'),)
classmethod from_file_map(file_map, buffer_size=35000000, mmap=True)

Load a Gifti image from a file_map

Parameters:
file_mapdict

Dictionary with single key image with associated value which is a FileHolder instance pointing to the image file.

buffer_size: None or int, optional

size of read buffer. None uses default buffer_size from xml.parsers.expat.

mmap{True, False, ‘c’, ‘r’, ‘r+’}

Controls the use of numpy memory mapping for reading data. Only has an effect when loading GIFTI images with data stored in external files (DataArray elements with an Encoding equal to ExternalFileBinary). If False, do not try numpy memmap for data array. If one of {'c', 'r', 'r+'}, try numpy memmap with mode=mmap. A mmap value of True gives the same behavior as mmap='c'. If the file cannot be memory-mapped, ignore mmap value and read array from file.

Returns:
imgGiftiImage
classmethod from_filename(filename, buffer_size=35000000, mmap=True)
get_arrays_from_intent(intent)

Return list of GiftiDataArray elements matching given intent

property labeltable
property meta
property numDA
parser

alias of GiftiImageParser

print_summary()
remove_gifti_data_array(ith)

Removes the ith data array element from the GiftiImage

remove_gifti_data_array_by_intent(intent)

Removes all the data arrays with the given intent type

to_bytes(enc='utf-8')

Return a bytes object with the contents of the file that would be written if the image were saved.

Parameters:
**kwargskeyword arguments

Keyword arguments that may be passed to img.to_file_map()

Returns:
bytes

Serialized image

to_file_map(file_map=None, enc='utf-8')

Save the current image to the specified file_map

Parameters:
file_mapdict

Dictionary with single key image with associated value which is a FileHolder instance pointing to the image file.

Returns:
None
to_xml(enc='utf-8') bytes

Return XML corresponding to image content

valid_exts: tuple[str, ...] = ('.gii',)

GiftiLabel

class nibabel.gifti.gifti.GiftiLabel(key=0, red=None, green=None, blue=None, alpha=None)

Bases: XmlSerializable

Gifti label: association of integer key with optional RGBA values

Quotes are from the gifti spec dated 2011-01-14.

Notes

freesurfer examples seem not to conform to datatype “NIFTI_TYPE_RGBA32” because they are floats, not 4 8-bit integers.

Attributes:
keyint

(From the spec): “This required attribute contains a non-negative integer value. If a DataArray’s Intent is NIFTI_INTENT_LABEL and a value in the DataArray is ‘X’, its corresponding label is the label with the Key attribute containing the value ‘X’. In early versions of the GIFTI file format, the attribute Index was used instead of Key. If an Index attribute is encountered, it should be processed like the Key attribute.”

redNone or float

Optional value for red.

greenNone or float

Optional value for green.

blueNone or float

Optional value for blue.

alphaNone or float

Optional value for alpha.

__init__(key=0, red=None, green=None, blue=None, alpha=None)
property rgba

Returns RGBA as tuple

GiftiLabelTable

class nibabel.gifti.gifti.GiftiLabelTable

Bases: XmlSerializable

Gifti label table: a sequence of key, label pairs

From the gifti spec dated 2011-01-14:

The label table is used by DataArrays whose values are an key into the LabelTable’s labels. A file should contain at most one LabelTable and it must be located in the file prior to any DataArray elements.

__init__()
get_labels_as_dict()
print_summary()

GiftiMetaData

class nibabel.gifti.gifti.GiftiMetaData(*args, **kwargs)

Bases: CaretMetaData

A sequence of GiftiNVPairs containing metadata for a gifti data array

__init__(*args, **kwargs)
property data

The data attribute is deprecated. Use GiftiMetaData object directly as a dict.

  • deprecated from version: 4.0

  • Will raise <class ‘nibabel.deprecator.ExpiredDeprecationError’> as of version: 6.0

classmethod from_dict(data_dict)

from_dict class method deprecated. Use GiftiMetaData directly.

  • deprecated from version: 4.0

  • Will raise <class ‘nibabel.deprecator.ExpiredDeprecationError’> as of version: 6.0

property metadata

Returns metadata as dictionary

metadata property deprecated. Use GiftiMetaData object as dict or pass to dict() for a standard dictionary.

  • deprecated from version: 4.0

  • Will raise <class ‘nibabel.deprecator.ExpiredDeprecationError’> as of version: 6.0

print_summary()

GiftiNVPairs

class nibabel.gifti.gifti.GiftiNVPairs(name='', value='')

Bases: object

Gifti name / value pairs

Attributes:
namestr
valuestr

GiftiNVPairs objects are deprecated. Use the GiftiMetaData object as a dict, instead.

  • deprecated from version: 4.0

  • Will raise <class ‘nibabel.deprecator.ExpiredDeprecationError’> as of version: 6.0

__init__(name='', value='')

GiftiNVPairs objects are deprecated. Use the GiftiMetaData object as a dict, instead.

  • deprecated from version: 4.0

  • Will raise <class ‘nibabel.deprecator.ExpiredDeprecationError’> as of version: 6.0

property name
property value

GiftiImageParser

class nibabel.gifti.parse_gifti_fast.GiftiImageParser(encoding=None, buffer_size=35000000, verbose=0, mmap=True)

Bases: XmlParser

Parameters:
encodingstr

string containing xml document

buffer_size: None or int, optional

size of read buffer. None uses default buffer_size from xml.parsers.expat.

verboseint, optional

amount of output during parsing (0=silent, by default).

__init__(encoding=None, buffer_size=35000000, verbose=0, mmap=True)
Parameters:
encodingstr

string containing xml document

buffer_size: None or int, optional

size of read buffer. None uses default buffer_size from xml.parsers.expat.

verboseint, optional

amount of output during parsing (0=silent, by default).

CharacterDataHandler(data)

Collect character data chunks pending collation

The parser breaks the data up into chunks of size depending on the buffer_size of the parser. A large bit of character data, with standard parser buffer_size (such as 8K) can easily span many calls to this function. We thus collect the chunks and process them when we hit start or end tags.

EndElementHandler(name)
StartElementHandler(name, attrs)
flush_chardata()

Collate and process collected character data

property pending_data

True if there is character data pending for processing

GiftiParseError

class nibabel.gifti.parse_gifti_fast.GiftiParseError

Bases: ExpatError

Gifti-specific parsing error

__init__(*args, **kwargs)

read_data_block

nibabel.gifti.parse_gifti_fast.read_data_block(darray, fname, data, mmap)

Parses data from a <Data> element, or loads from an external file.

Parameters:
darrayGiftiDataArray

GiftiDataArray object representing the parent <DataArray> of this <Data> element

fnamestr or None

Name of GIFTI file being loaded, or None if in-memory

datastr or None

Data to parse, or None if data is in an external file

mmap{True, False, ‘c’, ‘r’, ‘r+’}

Controls the use of numpy memory mapping for reading data. Only has an effect when loading GIFTI images with data stored in external files (DataArray elements with an Encoding equal to ExternalFileBinary). If False, do not try numpy memmap for data array. If one of {'c', 'r', 'r+'}, try numpy memmap with mode=mmap. A mmap value of True gives the same behavior as mmap='c'. If the file cannot be memory-mapped, ignore mmap value and read array from file.

Returns:
numpy.ndarray or numpy.memmap containing the parsed data