#!/usr/bin/env python3 """Portable I/O helpers for M4Raw Brain H5 files.""" from __future__ import annotations import csv from dataclasses import dataclass from pathlib import Path from typing import Any import h5py import numpy as np NATIVE_KSPACE_AXES = ("slice", "coil", "frequency_encode", "phase_encode") NATIVE_TARGET_AXES = ("slice", "frequency_encode", "phase_encode") @dataclass(frozen=True) class M4RawVolume: """One complete H5 acquisition in its native stored axis order.""" kspace: np.ndarray reconstruction_rss: np.ndarray acquired_pe_mask: np.ndarray ismrmrd_header: bytes attrs: dict[str, Any] def _plain_attr(value: Any) -> Any: if isinstance(value, np.generic): return value.item() if isinstance(value, bytes): return value.decode("utf-8") return value def derive_acquired_pe_mask(kspace: np.ndarray) -> np.ndarray: """Return one for every acquired PE sample on the final stored axis.""" array = np.asarray(kspace) if array.ndim != 4: raise ValueError(f"Expected [slice,coil,FE,PE], got {array.shape}") return np.any(array != 0, axis=(0, 1, 2)).astype(np.uint8) def read_h5(path: str | Path) -> M4RawVolume: """Read one H5 file without changing its native axis order.""" with h5py.File(path, "r") as handle: header = handle["ismrmrd_header"][()] if isinstance(header, str): header = header.encode("utf-8") kspace = np.asarray(handle["kspace"]) if "acquired_pe_mask" in handle: pe_mask = np.asarray(handle["acquired_pe_mask"], dtype=np.uint8) else: pe_mask = derive_acquired_pe_mask(kspace) return M4RawVolume( kspace=kspace, reconstruction_rss=np.asarray( handle["reconstruction_rss"], dtype=np.float32 ), acquired_pe_mask=pe_mask, ismrmrd_header=header, attrs={key: _plain_attr(value) for key, value in handle.attrs.items()}, ) def read_target(path: str | Path) -> np.ndarray: """Read only the stored RSS target as float32.""" with h5py.File(path, "r") as handle: return np.asarray(handle["reconstruction_rss"], dtype=np.float32) def centered_ifft_rss(kspace: np.ndarray) -> np.ndarray: """Reconstruct `[slice,coil,FE,PE]` k-space with orthonormal IFFT/RSS.""" array = np.asarray(kspace) if array.ndim != 4: raise ValueError(f"Expected [slice,coil,FE,PE], got {array.shape}") coil_images = np.fft.fftshift( np.fft.ifft2( np.fft.ifftshift(array, axes=(-2, -1)), axes=(-2, -1), norm="ortho", ), axes=(-2, -1), ) return np.sqrt(np.sum(np.abs(coil_images) ** 2, axis=1)).astype(np.float32) def read_manifest(path: str | Path) -> list[dict[str, str]]: """Read a packaged tab-separated manifest.""" with Path(path).open(newline="", encoding="utf-8") as handle: return list(csv.DictReader(handle, delimiter="\t"))