# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright The NiPreps Developers <nipreps@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We support and encourage derived works from this project, please read
# about our expectations at
#
# https://www.nipreps.org/community/licensing/
#
"""PET data representation."""
from __future__ import annotations
from pathlib import Path
from typing import Any
import attrs
import h5py
import numpy as np
from typing_extensions import Self
from nifreeze.data.base import BaseDataset, _cmp, _data_repr, _has_ndim
from nifreeze.data.utils import (
load_nfhdf5_fields,
replace_on_success,
save_nfhdf5_fields,
)
ATTRIBUTE_ABSENCE_ERROR_MSG = "PET '{attribute}' may not be None"
"""PET initialization array attribute absence error message."""
ARRAY_ATTRIBUTE_OBJECT_ERROR_MSG = (
"PET '{attribute}' must be a numeric homogeneous array-like object."
)
"""PET initialization array attribute object error message."""
ARRAY_ATTRIBUTE_NDIM_ERROR_MSG = "PET '{attribute}' must be a 1D numpy array."
"""PET initialization array attribute ndim error message."""
ATTRIBUTE_VOLUME_DIMENSIONALITY_MISMATCH_ERROR_MSG = """\
PET '{attribute}' length does not match number of frames: \
expected {n_frames} values, found {attr_len}."""
"""PET attribute shape mismatch error message."""
TEMPORAL_ATTRIBUTE_INCONSISTENCY_ERROR_MSG = """\
PET 'total_duration' cannot be smaller than last 'midframe' value: \
found {total_duration} and {last_midframe}."""
"""PET attribute inconsistency error message."""
SCALAR_ATTRIBUTE_ERROR_MSG = (
"PET '{attribute}' must be a numeric or single-element sequence object."
)
"""PET initialization scalar attribute object error message."""
[docs]
def validate_1d_array(inst: PET, attr: attrs.Attribute, value: Any) -> None:
"""Strict validator to ensure an attribute is a 1D NumPy array.
Enforces that ``value`` has exactly one dimension (``value.ndim == 1``).
This function is intended for use as an attrs-style validator.
Parameters
----------
inst : :obj:`~nifreeze.data.pet.PET`
The instance being validated (unused; present for validator signature).
attr : :obj:`~attrs.Attribute`
The attribute being validated; ``attr.name`` is used in the error message.
value : :obj:`Any`
The value to validate.
Raises
------
exc:`ValueError`
If the value is not 1D.
"""
if not _has_ndim(value, 1):
raise ValueError(ARRAY_ATTRIBUTE_NDIM_ERROR_MSG.format(attribute=attr.name))
[docs]
@attrs.define(slots=True)
class PET(BaseDataset[np.ndarray]):
"""Data representation structure for PET data."""
midframe: np.ndarray = attrs.field(
default=None,
repr=_data_repr,
eq=attrs.cmp_using(eq=_cmp),
converter=attrs.Converter(format_array_like, takes_field=True), # type: ignore
validator=validate_1d_array,
)
"""A (N,) numpy array specifying the midpoint timing of each sample or frame."""
total_duration: float = attrs.field(
default=None,
repr=True,
converter=attrs.Converter(format_scalar_like, takes_field=True), # type: ignore
validator=attrs.validators.optional(attrs.validators.instance_of(float)),
)
"""A float representing the total duration of the dataset."""
def __attrs_post_init__(self) -> None:
"""Enforce presence and basic consistency of PET data fields at
instantiation time.
Specifically, the length of the frame_time and uptake attributes must
match the first dimension of the data (number of frames).
Computes the values for the private attributes.
"""
def _check_attr_vol_length_match(
_attr_name: str, _value: np.ndarray | None, _n_frames: int
) -> None:
if _value is not None and len(_value) != _n_frames:
raise ValueError(
ATTRIBUTE_VOLUME_DIMENSIONALITY_MISMATCH_ERROR_MSG.format(
attribute=_attr_name,
n_frames=_n_frames,
attr_len=len(_value),
)
)
n_frames = int(self.dataobj.shape[0])
_check_attr_vol_length_match("midframe", self.midframe, n_frames)
# Ensure that the total duration is larger than last midframe
if self.total_duration <= self.midframe[-1]:
raise ValueError(
TEMPORAL_ATTRIBUTE_INCONSISTENCY_ERROR_MSG.format(
total_duration=self.total_duration,
last_midframe=self.midframe[-1],
)
)
def _getextra(self, idx: int | slice | tuple | np.ndarray) -> tuple[np.ndarray]:
return (self.midframe[idx],)
# For the sake of the docstring
def __getitem__(
self, idx: int | slice | tuple | np.ndarray
) -> tuple[np.ndarray, np.ndarray | None, np.ndarray]:
"""
Returns volume(s) and corresponding affine(s) and timing(s) through fancy indexing.
Parameters
----------
idx : :obj:`int` or :obj:`slice` or :obj:`tuple` or :obj:`~numpy.ndarray`
Indexer for the volume (first) dimension.
Returns
-------
volumes : :obj:`~numpy.ndarray`
The selected data subset.
If ``idx`` is a single integer, this will have shape ``(X, Y, Z)``,
otherwise it may have shape ``(k, X, Y, Z)``.
motion_affine : :obj:`~numpy.ndarray` or :obj:`None`
The corresponding per-volume motion affine(s) or :obj:`None` if identity transform(s).
time : :obj:`~numpy.ndarray`
The frame time corresponding to the index(es).
"""
return super().__getitem__(idx)
[docs]
def to_filename(
self, filename: Path | str, compression: str | None = None, compression_opts: Any = None
) -> None:
"""Write the dataset to an :ref:`nfHDF5 <nfhdf5>` file."""
filename = Path(filename)
if not filename.name.endswith(".h5"):
filename = filename.parent / f"{filename.name}.h5"
with replace_on_success(filename) as tmp, h5py.File(tmp, "w") as out_file:
out_file.attrs["Format"] = "nfHDF5"
out_file.attrs["Version"] = np.uint16(2) # v2: volume-major dataobj
root = out_file.create_group("/0")
root.attrs["Type"] = "pet"
save_nfhdf5_fields(root, self, compression, compression_opts)
[docs]
@classmethod
def from_filename(cls, filename: Path | str) -> Self:
"""Read an :ref:`nfHDF5 <nfhdf5>` file from disk."""
return cls(**load_nfhdf5_fields(filename))