nifreeze.data.utils module

nifreeze.data.utils.CONVERSION_SLAB_BYTES = 1048576

Bytes read per step when converting a legacy dataobj (at least one x-plane).

nifreeze.data.utils.VOLUME_AXIS_ATTR = 'volume_axis'

nfHDF5 marks a volume-major dataobj (volumes are the first, slowest-varying axis on disk, so a single volume is a contiguous block that memory-maps locally). Legacy files store the last axis as volumes and carry no such attribute.

nifreeze.data.utils.apply_affines(nii, em_affines, output_filename=None) → Nifti1Image[source]

Apply affines to supplied nii data

Parameters:
  • nii (Nifti1Image) – Nifti1Image data to be transformed

  • em_affines (ndarray) – Nx4x4 array

  • output_filename (str, optional) – String specifying filepath to which to save transformed Nifti1Image data

Returns:

nii_t_img – Transformed Nifti1Image data

Return type:

Nifti1Image

nifreeze.data.utils.load_nfhdf5_fields(filename: Path | str, lazy_keys: tuple[str, ...] = ('dataobj',)) → dict[source]

Read the /0 group of an nfHDF5 file into a field dict.

dataobj (named in lazy_keys) is returned as a lazy, per-volume-local memmap (via open_dataobj_memmap()); every other field is read eagerly (they are small: affine, brain mask, gradients, timings).

nifreeze.data.utils.open_dataobj_memmap(filename: Path | str, key: str = '/0/dataobj', mode: Literal['r', 'c', 'r+'] = 'c', cache_dir: Path | str | None = None) → memmap[source]

Open a 4D dataobj as a lazy, per-volume-local memmap.

The returned array always has the shape (N, X, Y, Z), C-contiguous, so that dataobj[k] is volume k as one contiguous block. Two on-disk layouts are handled:

  • volume-major (VOLUME_AXIS_ATTR == 0, written by save_dataobj_volume_major()): directly mapped zero-copy when contiguous, uncompressed and native-endian. Compressed or chunked datasets are decompressed one volume at a time into a temporary cache.

  • legacy (X, Y, Z, N) (no attribute): converted into a volume-major temporary cache in a single sequential pass over the file, reading slabs of at most CONVERSION_SLAB_BYTES. Re-save the dataset with to_filename to skip this conversion on later loads.

Temporary caches are deleted when the last array referencing them is released (or at interpreter exit).

mode applies to the direct mapping: "c" (copy-on-write, the default) reads lazily from the file, while writes fault private pages and never mutate the source. Caches are always opened "r+".

nifreeze.data.utils.replace_on_success(filename: Path | str) → Iterator[Path][source]

Yield a temporary path next to filename and move it onto filename on success.

h5py.File(filename, "w") truncates the file in place. If that file backs a memory-mapped dataobj (for example, writing a dataset back to the file it was loaded from), the mapping would lose its data while it is being written out. Renaming a new file over it keeps the old inode, and thus the mapping, valid.

nifreeze.data.utils.save_dataobj_volume_major(root: Group, dataobj: ndarray, compression: str | None = None, compression_opts=None) → None[source]

Write a 4D (N, X, Y, Z) dataobj volume-major, one volume at a time.

Each volume is a contiguous block on disk, which memory-maps with per-volume locality on read (see open_dataobj_memmap()). Writing volume by volume keeps a memory-mapped dataobj from being read into memory at once.

nifreeze.data.utils.save_nfhdf5_fields(root: Group, dataset, compression: str | None = None, compression_opts=None) → None[source]

Write a dataset’s public attrs fields into the /0 group.

dataobj is written volume-major (save_dataobj_volume_major()); all other non-None, non-private fields are written as plain datasets.

nifreeze.data.utils.stream_select_volumes(src: ndarray, keep_mask: ndarray, cache_dir: Path | str | None = None, name: str = 'dataobj') → memmap[source]

Select volumes (first axis) of src into a disk-backed memmap.

Copies src[keep_mask] one volume at a time into a temporary cache, which is deleted when the result is released. Used to drop b=0 volumes from a memory-mapped DWI without materializing it.

nifreeze.data.utils.to_time_first(data: ndarray, keep: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None) → ndarray[source]

Copy a volumes-last (X, Y, Z, N) array (NIfTI order) into (N, X, Y, Z).

The result is C-contiguous (each volume is one contiguous block) and is filled one volume at a time, so the only copy made is the result itself.

Parameters:
  • data (ndarray) – The 4D array with volumes on the last axis.

  • keep (ndarray, optional) – Boolean mask or integer indices of the volumes to keep (all by default).

Returns:

The selected volumes, stacked on the first axis.

Return type:

ndarray

Examples

>>> data = np.arange(24).reshape(2, 3, 1, 4)
>>> out = to_time_first(data, keep=[True, False, True, True])
>>> out.shape, out.flags.c_contiguous
((3, 2, 3, 1), True)
>>> bool(np.array_equal(out[1], data[..., 2]))
True