nifreeze.data.base module

Four-dimensional data representation in hard-disk and memory.

nifreeze.data.base.AFFINE_ABSENCE_ERROR_MSG = "BaseDataset 'affine' may not be None"

BaseDataset initialization affine absence error message.

nifreeze.data.base.AFFINE_NDIM_ERROR_MSG = "BaseDataset 'affine' must be a 2D array"

Affine dimensionality error message.

nifreeze.data.base.AFFINE_OBJECT_ERROR_MSG = "BaseDataset 'affine' must be a numpy array."

BaseDataset initialization affine object error message.

nifreeze.data.base.AFFINE_SHAPE_ERROR_MSG = "BaseDataset 'affine' must be a 2D numpy array (4 x 4)"

BaseDataset initialization affine shape error message.

nifreeze.data.base.BRAINMASK_SHAPE_MISMATCH_ERROR_MSG = "BaseDataset 'brainmask' shape ({brainmask_shape}) does not match dataset volumes ({data_shape})."

BaseDataset brainmask shape mismatch error message.

class nifreeze.data.base.BaseDataset(self, dataobj: 'Any' = None, affine: 'np.ndarray' = None, brainmask: 'np.ndarray | None' = None, motion: 'np.ndarray | None' = None, datahdr: 'nb.Nifti1Header | None' = None, filepath: 'Path' = NOTHING) → None[source]

Bases: Generic[Unpack[Ts]]

Base dataset representation structure.

A general data structure to represent 4D images and the necessary metadata for head motion estimation (that is, potentially a brain mask and the head motion estimates).

Volumes are stored on the first axis: dataobj has shape (N, X, Y, Z) for N volumes, and dataset[i] selects dataobj[i]. The array is kept C-contiguous, so each volume is a contiguous block in memory and on disk.

The data structure has a direct HDF5 mapping to facilitate memory efficiency. For modalities requiring additional metadata such as DWI (which requires the gradient table and potentially a b=0 reference), this class may be derived to override certain behaviors (in the case of DWIs, the indexed access should also return the corresponding gradient specification).

Method generated by attrs for class BaseDataset.

ESTIMATES: ClassVar[tuple[str, ...]] = ('motion',)

each maps the reference, moved by the fields before it, into the volume (see get_transform()).

Type:

The fields of per-volume estimates, in the order they apply

__len__() → int[source]

Obtain the number of volumes/frames in the dataset.

affine: ndarray

Best affine for RAS-to-voxel conversion of coordinates (NIfTI header).

brainmask: ndarray | None

A boolean ndarray object containing a corresponding brainmask.

datahdr: Nifti1Header | None

A Nifti1Header header corresponding to the data.

dataobj: ndarray

N volumes on the first axis.

Type:

A ndarray of shape (N, X, Y, Z)

classmethod from_filename(filename: Path | str) → Self[source]

Read an nfHDF5 file from disk and create a BaseDataset.

Parameters:

filename (os.pathlike) – The HDF5 file path to read.

Returns:

The constructed dataset with data loaded from the file.

Return type:

BaseDataset

get_filename() → Path[source]

Get the filepath of the HDF5 file.

get_transform(index: int) → ndarray | None[source]

The RAS+ matrix that maps the reference into volume index.

Every field of ESTIMATES that is set enters, each applied after the ones before it: for a DWI volume, eddy @ motion.

Parameters:

index (int) – The volume.

Returns:

The 4 x 4 matrix, or None if no estimate is set.

Return type:

ndarray or None

motion: ndarray | None

for each volume, the RAS+ matrix that maps the reference into it.

Type:

The head-motion estimates, (N, 4, 4)

realign_into(view: Self, index: int, order: int = 3) → None[source]

Write volume index into a realigned view, moved by its current estimates.

The original volume is resampled once with its mapping (see get_transform(), the same mapping as to_nifti()). A new estimate replaces the realigned volume: the realigned volume is never resampled again. Volumes without an estimate are copied as they are.

Parameters:
  • view (BaseDataset) – The realigned view (see realigned()).

  • index (int) – The volume to realign.

  • order (int, optional) – The interpolation order used to resample the volume.

realigned(order: int = 3) → Self[source]

Create the realigned view of the dataset, which models train on.

The view is a shallow copy whose volumes are a disk-backed copy of this dataset’s volumes. Volumes with an estimate are moved into the reference frame (see realign_into()). This dataset is not modified.

Parameters:

order (int, optional) – The interpolation order used to resample the volumes.

Returns:

The realigned view.

Return type:

BaseDataset

set_estimates(index: int, **estimates: ndarray) → None[source]

Store the estimates of several fields of ESTIMATES for volume index.

Each matrix is the field’s own estimate, as stored, not a mapping with the other fields included (unlike set_transform()). A registration that estimates head motion and eddy currents together stores both this way, and get_transform() then returns their composition.

Parameters:
  • index (int) – The volume.

  • **estimates (ndarray) – A 4 x 4 RAS+ matrix per field (e.g., motion=..., eddy=...).

set_transform(index: int, affine: ndarray, field: str = 'motion') → None[source]

Store the estimate of one field of ESTIMATES for volume index.

affine maps the reference into the volume with every estimate included, as registration returns it when started from get_transform(). The estimates of the other fields are factored out of it, so that get_transform() returns affine.

Parameters:
  • index (int) – The volume.

  • affine (ndarray) – The 4 x 4 RAS+ matrix that maps the reference into the volume.

  • field (str, optional) – The field the estimate goes to (default: "motion").

property shape3d: tuple[int, ...]

Get the shape of the 3D volume.

property size3d

Get the number of voxels in the 3D volume.

to_filename(filename: Path | str, compression: str | None = None, compression_opts: Any = None) → None[source]

Write the dataset to an nfHDF5 file.

Parameters:
  • filename (os.pathlike) – The HDF5 file path to write to.

  • compression (str, optional) – Compression strategy. See create_dataset documentation.

  • compression_opts (typing.Any, optional) – Parameters for compression filters.

to_nifti(filename: Path | str | None = None, write_estimates: bool = False, order: int = 3) → Nifti1Image[source]

Write a NIfTI file to disk.

Volumes are resampled into the reference with their mappings (see get_transform()) if any estimate has been set, otherwise the original data are written.

Parameters:
  • filename (os.pathlike, optional) – The output NIfTI file path.

  • write_estimates (bool, optional) – If True, the estimates are written next to the NIfTI file, into one X5 file: a transform per field of ESTIMATES, head motion first, chained in the order they apply when there are several.

  • order (int, optional) – The interpolation order to use when resampling the data. Defaults to 3 (cubic interpolation).

Returns:

NIfTI image written to disk.

Return type:

Nifti1Image

nifreeze.data.base.DATAOBJ_ABSENCE_ERROR_MSG = "BaseDataset 'dataobj' may not be None"

BaseDataset initialization dataobj absence error message.

nifreeze.data.base.DATAOBJ_NDIM_ERROR_MSG = "BaseDataset 'dataobj' must be a 4-D numpy array"

BaseDataset initialization dataobj dimensionality error message.

nifreeze.data.base.DATAOBJ_OBJECT_ERROR_MSG = "BaseDataset 'dataobj' must be a numpy array."

BaseDataset initialization dataobj object error message.

nifreeze.data.base.ESTIMATES_FIELD_ERROR_MSG = '{name} has no estimates {field!r} (it has: {fields}).'

Unknown field of estimates error message.

class nifreeze.data.base.ImageGrid(self, /, *args, **kwargs)

Bases: tuple

Create new instance of ImageGrid(shape, affine)

affine

Alias for field number 1

shape

Alias for field number 0

nifreeze.data.base.NFHDF5_RASB_VERSION = 3

The first nfHDF5 version whose gradient tables are known to be RAS+B.

nifreeze.data.base.NFHDF5_VERSION = 4

2 stores volumes first, 3 gradient tables in RAS+B, and 4 names the estimates after their artifacts (motion).

Type:

The version of the nfHDF5 files written

nifreeze.data.base.to_nifti(dataset: BaseDataset, filename: Path | str | None = None, write_estimates: bool = False, order: int = 3) → Nifti1Image[source]

Write a NIfTI file to disk.

Volumes are resampled into the reference with their mappings (see get_transform()) if any estimate has been set, otherwise the original data are written.

Parameters:
  • dataset (BaseDataset) – The dataset to serialize.

  • filename (os.pathlike, optional) – The output NIfTI file path.

  • write_estimates (bool, optional) – If True, the estimates are written next to the NIfTI file, into one X5 file: a transform per field of ESTIMATES, head motion first, chained in the order they apply when there are several.

  • order (int, optional) – The interpolation order to use when resampling the data. Defaults to 3 (cubic interpolation).

Returns:

NIfTI image written to disk.

Return type:

Nifti1Image

nifreeze.data.base.validate_affine(inst: BaseDataset, attr: Attribute, value: Any) → None[source]

Strict validator for affine matrices.

Enforces that value is present and is a 4x4 NumPy array.

This function is intended for use as an attrs-style validator.

Parameters:
  • inst (BaseDataset) – The instance being validated (unused, present for validator signature).

  • attr (Attribute) – The attribute being validated (unused, present for validator signature).

  • value (Any) – The value to validate.

:raises exc:TypeError: If the input cannot be converted to a float ndarray. :raises exc:ValueError: If the value is None, or not shaped (4, 4).

nifreeze.data.base.validate_dataobj(inst: BaseDataset, attr: Attribute, value: Any) → None[source]

Strict validator for data objects.

Enforces that value is present and is a NumPy array with exactly 4 dimensions (ndim == 4).

This function is intended for use as an attrs-style validator.

Parameters:
  • inst (BaseDataset) – The instance being validated (unused, present for validator signature).

  • attr (Attribute) – The attribute being validated (unused, present for validator signature).

  • value (Any) – The value to validate.

:raises exc:TypeError: If the input cannot be converted to a float ndarray. :raises exc:ValueError: If the value is None, or not 4-dimensional.