mr2.data.KData

class mr2.data.KData[source]

Bases: Dataclass

MR raw data / k-space data class.

__init__(header: KHeader, data: Tensor, traj: KTrajectory) → None
classmethod from_file(filename: Any | BinaryIO, trajectory: KTrajectoryCalculator | KTrajectory | KTrajectoryIsmrmrd | None = None, header_overwrites: Mapping[str, object] | None = None, dataset_idx: int = -1, acquisition_filter_criterion: Callable[[Acquisition], bool] | None = is_image_acquisition, *, file_format: Literal['mr2', 'ismrmrd-hdf5', 'ismrmrd-stream'] | None = None) → Self[source]

Load k-space data from an MR2 or ISMRMRD file.

Detect the format from the file contents. File-like inputs default to HDF5; pass file_format='ismrmrd-stream' for binary streams such as sys.stdin.buffer. MR2 files restore the saved KData; the remaining options apply to ISMRMRD input.

Parameters:
  • filename (Any | BinaryIO) – path or binary file-like object

  • trajectory (KTrajectoryCalculator | KTrajectory | KTrajectoryIsmrmrd | None, default: None) – Trajectory source for ISMRMRD input. MR2 files contain their own trajectory. A KTrajectory should have shape (acquisitions 1 1 1 k0) and match the selected acquisitions, with discarded readout samples already removed.

  • header_overwrites (Mapping[str, object] | None, default: None) – dictionary of key-value pairs to overwrite the header

  • dataset_idx (int, default: -1) – index of the dataset or serialized measurement to load; defaults to the last

  • acquisition_filter_criterion (Callable[[Acquisition], bool] | None, default: is_image_acquisition) – function which returns True if an acquisition should be included in KData, or None to disable filtering

  • file_format (Optional[Literal['mr2', 'ismrmrd-hdf5', 'ismrmrd-stream']], default: None) – Explicit input format. If None, detect path formats and assume HDF5 for file-like inputs.

classmethod from_ismrmrd(ismrmrd_header: ismrmrdHeader | str | bytes, acquisitions: Iterable[Acquisition], trajectory: KTrajectoryCalculator | KTrajectory | KTrajectoryIsmrmrd, header_overwrites: Mapping[str, object] | None = None, acquisition_filter_criterion: Callable[[Acquisition], bool] | None = is_image_acquisition, *, header_defaults: Mapping[str, object] | None = None) → Self[source]

Normalize an ISMRMRD header and acquisitions into sorted k-space data.

Parameters:
  • ismrmrd_header (ismrmrdHeader | str | bytes) – Parsed ISMRMRD header or XML string/bytes, as received by a reconstruction server.

  • acquisitions (Iterable[Acquisition]) – Acquisition objects in acquisition order, including a one-pass iterator. The input objects are not modified. Filtering, coil selection and selection of the longest post-discard readouts precede metadata and trajectory construction.

  • trajectory (KTrajectoryCalculator | KTrajectory | KTrajectoryIsmrmrd) – Trajectory calculator, stored ISMRMRD trajectory reader, or a KTrajectory of shape (acquisitions 1 1 1 k0) matching the retained, cropped acquisitions.

  • header_overwrites (Mapping[str, object] | None, default: None) – Header fields to overwrite.

  • acquisition_filter_criterion (Callable[[Acquisition], bool] | None, default: is_image_acquisition) – Acquisition predicate, or None to disable filtering.

  • header_defaults (Mapping[str, object] | None, default: None) – Fallback header fields, used only when absent from the ISMRMRD header. Header overwrites take precedence, including explicit None values. Without a measurement timestamp or a default, datetime remains unknown.

classmethod iter_ismrmrd(filename: str | PathLike | BinaryIO, trajectory: KTrajectoryCalculator | KTrajectory | KTrajectoryIsmrmrd, header_overwrites: Mapping[str, object] | None = None, acquisition_filter_criterion: Callable[[Acquisition], bool] | None = is_image_acquisition) → Generator[Self, None, None][source]

Yield one KData per selected acquisition in stream order.

Each KData contains one readout and its acquisition counters. The XML header supplies the encoding geometry. Images, waveforms and other messages are ignored. Missing CLOSE and corrupt messages raise the deserializer’s errors.

Parameters:
  • filename (str | PathLike | BinaryIO) – Path or blocking binary stream, including sys.stdin.buffer. Caller streams remain open. Close the iterator when stopping early to release an owned file.

  • trajectory (KTrajectoryCalculator | KTrajectory | KTrajectoryIsmrmrd) – Trajectory source, as in from_ismrmrd, applied to each acquisition. A precomputed KTrajectory must match one readout, rather than the full measurement. KTrajectoryIsmrmrd must use normalize=False, since normalization requires the full measurement. KTrajectorySunflowerGoldenRpe also requires a full measurement and cannot be used here.

  • header_overwrites (Mapping[str, object] | None, default: None) – Header fields to overwrite.

  • acquisition_filter_criterion (Callable[[Acquisition], bool] | None, default: is_image_acquisition) – Acquisition predicate, or None to disable filtering.

Yields:

KData – K-space data with shape (1, coils, 1, 1, samples).

header: KHeader

Header information for k-space data

data: Tensor

K-space data. Shape (*other coils k2 k1 k0)

traj: KTrajectory

K-space trajectory along kz, ky and kx. Shape (*other 1 k2 k1 k0)

property device: device | None[source]

Return the device of the tensors.

Looks at each field of a dataclass implementing a device attribute, such as torch.Tensor or Dataclass instances. If the devices of the fields differ, an InconsistentDeviceError is raised, otherwise the device is returned. If no field implements a device attribute, None is returned.

Raises:

InconsistentDeviceError – If the devices of different fields differ.

Returns:

The device of the fields or None if no field implements a device attribute.

property is_cpu: bool[source]

Return True if all tensors are on the CPU.

Checks all tensor attributes of the dataclass for their device, (recursively if an attribute is a Dataclass)

Returns False if not all tensors are on cpu or if the device is inconsistent, returns True if the data class has no tensors as attributes.

property is_cuda: bool[source]

Return True if all tensors are on a single CUDA device.

Checks all tensor attributes of the dataclass for their device, (recursively if an attribute is a Dataclass)

Returns False if not all tensors are on the same CUDA devices, or if the device is inconsistent, returns True if the data class has no tensors as attributes.

property ndim: int[source]

Return the number of dimensions of the dataclass.

This is the number of dimensions of the broadcasted shape of all fields.

property shape: Size[source]

Return the broadcasted shape of all tensor/data fields.

Each field of this dataclass is broadcastable to this shape.

Returns:

The broadcasted shape of all fields.

Raises:

InconsistentShapeError – If the shapes cannot be broadcasted.

acs(size: int | SpatialDimension[int] | None = None) → Tensor[source]

Return centered Cartesian calibration k-space.

Parameters:

size (Union[int, SpatialDimension[int], None], default: None) – Explicit calibration widths. An integer gives a square in 2D or cube in 3D; inactive encoding axes stay singleton. If omitted, infer the largest adequately covered centered square or cube shared by all batches. See prepare_acs for the coverage criterion.

Returns:

torch.Tensor – Calibration tensor shaped (..., coils, kz, ky, kx) in the original coil basis and encoding FOV. Cartesian samples are extracted exactly; non-Cartesian samples are approximately gridded using one Voronoi density calculation for adjoint reconstruction.

Notes

kdata.acs() infers the size, kdata.acs(24) requests a square or cube, and kdata.acs(SpatialDimension(1, 24, 32)) requests a rectangle. Non-Cartesian sizing estimates coverage using rounded sample bins and can be conservative. Explicit non-Cartesian sizes skip this estimate; explicit Cartesian sizes still require exactly one sample per grid point.

Raises:

ValueError – If the size or trajectory is invalid, automatic sizing finds no covered center, or an explicit Cartesian block has missing or repeated samples.

apodize(width: float | SpatialDimension[float] | None = None, *, window: Literal['hann', 'gaussian'] = 'hann', radial: bool = False) → Self[source]

Return a copy with a centered k-space window applied at trajectory coordinates.

Suppressing high spatial frequencies smooths the reconstructed image and reduces ringing at the cost of spatial resolution. Weights are shared across coils, with unit gain at DC and no energy/noise normalization. Trajectory, header and acquisition metadata are copied unchanged.

Parameters:
  • width (Union[float, SpatialDimension[float], None], default: None) – Full window width in trajectory units: one unit normally corresponds to one Cartesian encoding step, or 1 / encoding_fov in spatial frequency. A scalar applies to all spatial directions; a SpatialDimension specifies z, y and x separately. Defaults to the header’s encoding matrix sizes, independent of acquired sample count. All widths must be finite and positive.

  • window (Literal['hann', 'gaussian'], default: 'hann') – 'hann' has compact support of the specified width. 'gaussian' uses width as its full width at half maximum, with no hard cutoff. See mr2.utils.filters.hann_window() and mr2.utils.filters.gaussian_window() for the formulas.

  • radial (bool, default: False) – If False, multiply the windows along kz, ky and kx (separable). If True, evaluate one window at the radius formed from coordinates scaled by their respective widths (ellipsoidal support for Hann). Gaussian weights coincide for both choices.

Returns:

Apodized copy with the same dtype and device. Repeated data dimensions are reduced to singletons following the usual KData convention. Density compensation is not applied or modified.

compress_coils(n_compressed_coils: int, batch_dims: Sequence[int] | None = None, joint_dims: Sequence[int] | ellipsis = Ellipsis, rotate: bool = False, return_compression_op: Literal[False] = False) → Self[source]
compress_coils(n_compressed_coils: int, batch_dims: Sequence[int] | None = None, joint_dims: Sequence[int] | ellipsis = Ellipsis, rotate: bool = False, return_compression_op: Literal[True] = Ellipsis) → tuple[Self, LinearOperator]

Reduce the number of coils based on a PCA compression.

A PCA is carried out along the coil dimension and the n_compressed_coils virtual coil elements are selected. For more information on coil compression please see [BUE2007], [DON2008] and [HUA2008].

Returns a copy of the data.

Parameters:
  • kdata – K-space data

  • n_compressed_coils (int) – Number of compressed coils

  • batch_dims (Sequence[int] | None, default: None) – Dimensions which are treated as batched, i.e. separate coil compression matrizes (e.g. different slices). Default is to do one coil compression matrix for the entire k-space data. Only batch_dim or joint_dim can be defined. If batch_dims is not None then joint_dims has to be …

  • joint_dims (Sequence[int] | EllipsisType, default: ...) – Dimensions which are combined to calculate single coil compression matrix (e.g. k0, k1, contrast). Default is that all dimensions (except for the coil dimension) are joint_dims. Only batch_dim or joint_dim can be defined. If joint_dims is not … batch_dims has to be None

  • rotate (bool, default: False) – Apply a varimax rotation to the compression matrix to distribute the signal more equally across the compressed coils.

  • return_compression_op (bool, default: False) – If True, return the compression operator used for compression along with the compressed data.

Returns:

Copy of K-space data with compressed coils. (Optional) Compression operator used for compression along with the compressed data.

Raises:
  • ValueError – If both batch_dims and joint_dims are defined.

  • ValuerError – If coil dimension is part of joint_dims or batch_dims.

References

[BUE2007]

Buehrer M, Pruessmann KP, Boesiger P, Kozerke S (2007) Array compression for MRI with large coil arrays. MRM 57. https://doi.org/10.1002/mrm.21237

[DON2008]

Doneva M, Boernert P (2008) Automatic coil selection for channel reduction in SENSE-based parallel imaging. MAGMA 21. https://doi.org/10.1007/s10334-008-0110-x

[HUA2008]

Huang F, Vijayakumar S, Li Y, Hertel S, Duensing GR (2008) A software channel compression technique for faster reconstruction with many channels. MRM 26. https://doi.org/10.1016/j.mri.2007.04.010

partial_fourier(dim: int = -2, method: Literal['pocs', 'homodyne'] = 'pocs', *, n_iterations: int = 10) → Self[source]

Complete one Cartesian partial Fourier direction using trajectory-derived support.

Requires separable Cartesian axes with shared sampling across batches and a contiguous acquired interval touching either edge.

Parameters:
  • dim (int, default: -2) – Partial Fourier axis within (k2, k1, k0); accepts positive or negative indices.

  • method (Literal['pocs', 'homodyne'], default: 'pocs') – 'pocs' preserves acquired values; 'homodyne' uses ramp weighting.

  • n_iterations (int, default: 10) – POCS iteration count; unused for homodyne.

Returns:

KData with completed k-space, a full Cartesian trajectory and updated encoding indices. Metadata for synthesized lines inherits the nearest acquired line’s values. The input is unchanged.

prewhiten(knoise: KNoise | Tensor, scale_factor: float | Tensor = 1.0) → Self[source]

Calculate noise prewhitening matrix and decorrelate coils.

This is a convenience wrapper around mr2.algorithms.prewhiten_kspace().

Parameters:
  • knoise (KNoise | Tensor) – Noise measurements. Either a KNoise object or a tensor of shape (coils, k0).

  • scale_factor (float | Tensor, default: 1.0) – Square root is applied on the noise covariance matrix. Used to adjust for effective noise bandwidth and difference in sampling rate between noise calibration and actual measurement: scale_factor = (T_acq_dwell/T_noise_dwell)*NoiseReceiverBandwidthRatio

Returns:

Prewhitened copy of k-space data.

remove_readout_os() → Self[source]

Remove any oversampling along the readout direction.

Removes oversampling along the readout direction by cropping the data to the size of the reconstruction matrix in image space [GAD].

Returns a copy of the data.

Parameters:

kdata – K-space data

Returns:

Copy of K-space data with oversampling removed.

Raises:

ValueError – If the recon matrix along x is larger than the encoding matrix along x.

References

reshape_by_idx() → Self[source]

Sort and reshape according to the acquisition indices.

Reshapes the data to (“all other labels”, coils, k2, k1, k0). Within “all other labels”, the order is determined by KDIM_SORT_LABELS.

select_other_subset(subset_idx: Tensor, subset_label: Literal['average', 'slice', 'contrast', 'phase', 'repetition', 'set']) → Self[source]

Select a subset from the other dimension of KData.

Warning

This function will be deprecated in the future.

Parameters:
  • kdata – K-space data (other coils k2 k1 k0)

  • subset_idx (Tensor) – Index which elements of the other subset to use, e.g. phase 0,1,2 and 5

  • subset_label (Literal['average', 'slice', 'contrast', 'phase', 'repetition', 'set']) – Name of the other label, e.g. phase

Returns:

K-space data (other_subset coils k2 k1 k0)

Raises:

ValueError – If the subset indices are not available in the data

squeeze(dim: int | Sequence[int] | None = None) → Self[source]

Squeeze KData along the specified dimensions.

to_bart(filename: str | Path, trajectory_filename: str | Path | None = None, *, other_dims: Sequence[BartDimension] | None = None) → None[source]

Save k-space data as BART array.

Data with integer trajectory coordinates (within KTrajectory.grid_detection_tolerance) is Cartesian. It is sorted into the encoding matrix with zeros at non-acquired positions. The k-space center is at index n // 2, matching BART’s centered FFT. (coils, k2, k1, k0) are stored in the BART dimensions COIL, PHS2, PHS1 and READ.

Non-Cartesian data is saved as samples with k0 in PHS1, the readouts (k2 k1) in PHS2 and coils in COIL. The trajectory is saved to a second file with the components (kx, ky, kz) along READ, in units of 1/FOV, as used by bart pics -t and bart nufft.

No meta data is saved.

Parameters:
  • filename (str | Path) – A .cfl or .hdr suffix writes a .hdr/.cfl pair, a .ra suffix writes a single file.

  • trajectory_filename (str | Path | None, default: None) – File for the trajectory. Required for non-Cartesian data, must be None for Cartesian data.

  • other_dims (Sequence[BartDimension] | None, default: None) – BART dimensions of the other dimensions, in tensor order, e.g. (BartDimension.TE, BartDimension.SLICE). None flattens all other dimensions into BartDimension.BATCH.

to_file(filename: Any) → None[source]

Save KData as ISMRMRD dataset to file.

Parameters:

filename (Any) – path to the ISMRMRD file

apply(function: Callable[[Any], Any] | None = None, *, recurse: bool = True) → Self[source]

Apply a function to all children. Returns a new object.

Parameters:
  • function (Callable[[Any], Any] | None, default: None) – The function to apply to all fields. None is interpreted as a no-op.

  • recurse (bool, default: True) – If True, the function will be applied to all children that are Dataclass instances.

apply_(function: Callable[[Any], Any] | None = None, *, memo: dict[int, Any] | None = None, recurse: bool = True) → Self[source]

Apply a function to all children in-place.

Parameters:
  • function (Callable[[Any], Any] | None, default: None) – The function to apply to all fields. None is interpreted as a no-op.

  • memo (dict[int, Any] | None, default: None) – A dictionary to keep track of objects that the function has already been applied to, to avoid multiple applications. This is useful if the object has a circular reference.

  • recurse (bool, default: True) – If True, the function will be applied to all children that are Dataclass instances.

clone() → Self[source]

Return a deep copy of the object.

concatenate(*others: Self, dim: int) → Self[source]

Concatenate other instances to the current instance.

Tensor-like fields are broadcast against each other in non-concat dimensions and concatenated along dim. Nested dataclasses use the parent’s per-object broadcast shapes for all their fields. Other nested objects supporting both concatenate and expand (e.g. Rotation) use the parent’s concat extent while keeping shared singleton dimensions elsewhere. List fields are joined into a new list. Other fields are left untouched.

Parameters:
  • others (Self) – other instance to concatenate.

  • dim (int) – The dimension to concatenate along.

Returns:

The concatenated dataclass.

cpu(*, memory_format: memory_format = torch.preserve_format, copy: bool = False) → Self[source]

Put in CPU memory.

Parameters:
  • memory_format (memory_format, default: torch.preserve_format) – The desired memory format of returned tensor.

  • copy (bool, default: False) – If True, the returned tensor will always be a copy, even if the input was already on the correct device. This will also create new tensors for views.

cuda(device: device | str | int | None = None, *, non_blocking: bool = False, memory_format: memory_format = torch.preserve_format, copy: bool = False) → Self[source]

Put object in CUDA memory.

Parameters:
  • device (device | str | int | None, default: None) – The destination GPU device. Defaults to the current CUDA device.

  • non_blocking (bool, default: False) – If True and the source is in pinned memory, the copy will be asynchronous with respect to the host. Otherwise, the argument has no effect.

  • memory_format (memory_format, default: torch.preserve_format) – The desired memory format of returned tensor.

  • copy (bool, default: False) – If True, the returned tensor will always be a copy, even if the input was already on the correct device. This will also create new tensors for views.

detach() → Self[source]

Detach the data from the autograd graph.

Returns:

A new dataclass with the data detached from the autograd graph. The data is shared between the original and the new object. Use detach().clone() to create an independent copy.

double(*, memory_format: memory_format = torch.preserve_format, copy: bool = False) → Self[source]

Convert all float tensors to double precision.

converts float to float64 and complex to complex128

Parameters:
  • memory_format (memory_format, default: torch.preserve_format) – The desired memory format of returned tensor.

  • copy (bool, default: False) – If True, the returned tensor will always be a copy, even if the input was already on the correct device. This will also create new tensors for views.

half(*, memory_format: memory_format = torch.preserve_format, copy: bool = False) → Self[source]

Convert all float tensors to half precision.

converts float to float16 and complex to complex32

Parameters:
  • memory_format (memory_format, default: torch.preserve_format) – The desired memory format of returned tensor.

  • copy (bool, default: False) – If True, the returned tensor will always be a copy, even if the input was already on the correct device. This will also create new tensors for views.

items() → Iterator[tuple[str, Any]][source]

Get an iterator over names and values of fields.

rearrange(pattern: str, **axes_lengths: int) → Self[source]

Rearrange the data according to the specified pattern.

Similar to einops.rearrange, allowing flexible rearrangement of data dimensions.

Examples

>>> # Split the phase encode lines into 8 cardiac phases
>>> data.rearrange('batch coils k2 (phase k1) k0 -> batch phase coils k2 k1 k0', phase=8)
>>> # Split the k-space samples into 64 k1 and 64 k2 lines
>>> data.rearrange('... 1 1 (k2 k1 k0) -> ... k2 k1 k0', k2=64, k1=64, k0=128)
Parameters:
  • pattern (str) – String describing the rearrangement pattern. See einops.rearrange and the examples above for more details.

  • **axes_lengths (dict) – Optional dictionary mapping axis names to their lengths. Used when pattern contains unknown dimensions.

Returns:

The rearranged data with the same type as the input.

save_as_mr2(filepath: str | Path) → None[source]

Save the dataclass to an MR2 file.

``MR2` is a mr2 specific file format based on HDF5. It is a simple serialization of dataclasses.

Parameters:

filepath (str | Path) – The path to save the MR2 file to.

single(*, memory_format: memory_format = torch.preserve_format, copy: bool = False) → Self[source]

Convert all float tensors to single precision.

converts float to float32 and complex to complex64

Parameters:
  • memory_format (memory_format, default: torch.preserve_format) – The desired memory format of returned tensor.

  • copy (bool, default: False) – If True, the returned tensor will always be a copy, even if the input was already on the correct device. This will also create new tensors for views.

split(dim: int, size: int = 1, overlap: int = 0, dilation: int = 1) → tuple[Self, ...][source]

Split the dataclass into full windows along a dimension.

Incomplete trailing windows are omitted. Each window contains size elements and spans (size - 1) * dilation + 1 input positions.

Parameters:
  • dim (int) – dimension to split along.

  • size (int, default: 1) – Number of elements in each split. Must be positive.

  • overlap (int, default: 0) – Number of input positions by which consecutive window spans overlap. Must be smaller than size. The stride is (size - 1) * dilation + 1 - overlap. Negative overlap leaves gaps between window spans.

  • dilation (int, default: 1) – Spacing between elements in each split. Must be positive.

Examples

If the dimension has 6 elements:

  • split with size 2, overlap 0, dilation 1 -> elements (0,1), (2,3), and (4,5)

  • split with size 2, overlap 1, dilation 1 -> elements (0,1), (1,2), (2,3), (3,4), and (4,5)

  • split with size 2, overlap 0, dilation 2 -> elements (0,2), and (3,5)

  • split with size 2, overlap -1, dilation 1 -> elements (0,1), and (3,4)

Returns:

A tuple of the splits.

stack(*others: Self) → Self[source]

Stack other along new first dimension.

Parameters:

others (Self) – other instance to stack.

swapdims(dim0: int, dim1: int) → Self[source]

Swap two dimensions of the dataclass.

Parameters:
  • dim0 (int) – First dimension to swap.

  • dim1 (int) – Second dimension to swap.

Returns:

The dataclass with the dimensions swapped.

to(device: str | device | int | None = None, dtype: dtype | None = None, non_blocking: bool = False, *, copy: bool = False, memory_format: memory_format | None = None) → Self[source]
to(dtype: dtype, non_blocking: bool = False, *, copy: bool = False, memory_format: memory_format | None = None) → Self
to(tensor: Tensor, non_blocking: bool = False, *, copy: bool = False, memory_format: memory_format | None = None) → Self

Perform dtype and/or device conversion of data.

A torch.dtype and torch.device are inferred from the arguments args and kwargs. Please have a look at the documentation of torch.Tensor.to for more details.

A new instance of the dataclass will be returned.

The conversion will be applied to all Tensor- or Module fields of the dataclass, and to all fields that implement the Dataclass.

The dtype-type, i.e. float or complex will always be preserved, but the precision of floating point dtypes might be changed.

Examples

If called with dtype=torch.float32 OR dtype=torch.complex64:

  • A complex128 tensor will be converted to complex64

  • A float64 tensor will be converted to float32

  • A bool tensor will remain bool

  • An int64 tensor will remain int64

If other conversions are desired, please use the to method of the fields directly.

If the copy argument is set to True, a deep copy will be returned even if no conversion is necessary. If two fields are views of the same data before, in the result they will be independent copies if copy is set to True or a conversion is necessary. If set to False, some Tensors might be shared between the original and the new object.

unsqueeze(dim: int, n: int = 1) → Self[source]

Unsqueeze the dataclass at a specific dimension.

Parameters:
  • dim (int) – Dimension at which to insert singleton dimensions.

  • n (int, default: 1) – Number of singleton dimensions to insert.

__eq__(other: object) → bool[source]

Check deep equality of two dataclasses.

Tests equality up to broadcasting.

__new__(**kwargs)