Reconstruction functions#

mrax.reco.reconstruct_acquisition(acquisition: AcquisitionData, *, method: str = 'fft', sensitivities=None, experiment=None, model=None, device: str | Device = 'cpu', frame_batch_size: int | None = None, **options) → ReconstructionResult#

Reconstruct explicit samples through the normalized acquisition contract.

FFT, variational and signal-model reconstruction share the same measured samples, encoding grid, calibration convention and output recipe. Completion supplies initialization. Iterative objectives retain the acquired support.

mrax.reco.processing.pad_centered_kspace(array, target_shape)#

Pad trailing Fourier axes, preserving DC at index size // 2.

mrax.reco.utils.estimate_sensitivities_cartesian(kspace: ndarray | Array, *, frame: int = 0, eps: float = 1e-08) → ndarray | None#

Estimate coil sensitivity maps from Cartesian k-space via RSS normalization.

mrax.reco.utils.pick_sensitivity_frame(kspace: ndarray | Array, *, strategy: Literal['first', 'max_energy'] | str = 'max_energy') → int#

Choose a reference frame for sensitivity estimation.

mrax.reco.utils.pocs_complete_kspace(kspace: ndarray | Array, *, iterations: int = 20, mask: ndarray, spatial_ndim: int = 2, device: str | Device = 'cpu') → ndarray#

Fill missing Cartesian k-space via POCS (useful for partial Fourier).

mrax.reco.processing.apply_channel_scale_phase(data: ndarray, *, scale: Sequence[float] | ndarray | None = None, phase_degrees: Sequence[float] | ndarray | None = None, coil_axis: int = 1) → ndarray#

Apply per-coil scale factors and phase offsets to k-space or coil images.

Parameters#

data:

Array with one coil/channel dimension. Typical shapes are (frame, coil, sample) for non-Cartesian streams or (frame, coil, *spatial) for Cartesian grids and coil images.

scale:

Optional real multiplicative factors, one per coil.

phase_degrees:

Optional phase offsets in degrees, one per coil. Positive values multiply the corresponding coil by exp(1j * phase).

coil_axis:

Axis containing the coil/channel dimension.

Returns#

np.ndarray

Corrected copy of the input array.

Notes#

Use this for receiver normalization from any vendor. Bruker maps RecoScaleChan and RecoPhaseChan to these arguments. Other importers can map equivalent receiver gains and phase references the same way.

mrax.reco.processing.apply_samplewise_correction(data: ndarray, correction: Sequence[complex] | ndarray, *, sample_axis: int = -1) → ndarray#

Multiply a k-space stream by a per-sample complex correction.

The correction can be a one-dimensional vector matching sample_axis or an already-broadcastable array. This is useful for B0/demodulation phase corrections, trajectory-specific scaling, or calibration vectors derived outside MRax.

mrax.reco.processing.estimate_radial_density(trajectory: ndarray, *, spatial_shape: tuple[int, ...] | None = None, power: float | None = None) → ndarray#

Estimate radial density compensation weights from a 2D or 3D trajectory.

Parameters#

trajectory:

(sample, D) array in normalized k-space coordinates, usually cycles/pixel.

spatial_shape:

Optional output image shape. When supplied, weights are normalized to sum to the number of spatial pixels/voxels. Otherwise they are normalized to mean 1.

power:

Radial power. Defaults to 1 for 2D trajectories and 2 for 3D trajectories, matching common rho and rho^2 density compensation.

Notes#

This is a simple analytic estimate. Prefer sequence-provided or iteratively optimized density weights when they are available and validated.

mrax.reco.processing.fid_profiles_to_kspace(profiles: ndarray, *, axis: int = -1, transform: Literal['none', 'fft', 'ifft', 'fft_ifftshift', 'ifft_ifftshift']='fft_ifftshift', output_points: int | None = None, crop_offset: int | None = None, readout_shift: float | None = None, dtype: dtype | type | None = <class 'numpy.complex64'>) → ndarray#

Transform time-domain readout profiles into frequency-domain k-space profiles.

Parameters#

profiles:

Input readout profiles. The selected axis is interpreted as the readout time/frequency axis.

transform:

Readout transform to apply before cropping. "fft_ifftshift" matches the common pattern where a centered FID-like readout is shifted to FFT order and transformed along the readout.

output_points, crop_offset:

Optional crop on the transformed readout axis. crop_offset=None means centered crop.

readout_shift:

Optional fractional sample shift applied after the crop as a phase ramp.

dtype:

Optional output dtype. Use None to keep NumPy’s transform dtype.

Returns#

np.ndarray

Frequency-domain readout profiles.

Notes#

This applies to sequences that store raw FIDs or oversampled readouts that must be Fourier-transformed, cropped, and phase shifted before samples are paired with a trajectory.

mrax.reco.processing.apply_readout_phase_shift(data: ndarray, shift_samples: float, *, axis: int = -1) → ndarray#

Apply a fractional readout shift as a linear phase ramp.

shift_samples is expressed in samples over the selected axis. Positive values use exp(+2j*pi*shift*n/N). Pass a negative shift when your convention requires the inverse ramp.

mrax.reco.processing.crop_along_axis(data: ndarray, output_size: int, *, axis: int = -1, offset: int | None = None) → ndarray#

Crop one axis of an array, centered by default.

mrax.reco.processing.readout_crop_bounds(input_size: int, output_size: int, offset: int | None = None) → tuple[int, int]#

Return (start, stop) bounds for a readout crop.

offset=None performs a centered crop. Explicit offsets are useful when a vendor reconstruction records an asymmetric cutoff.

mrax.reco.phase.unwrap_phase_image(phase: Array | ndarray | bool | number | bool | int | float | complex, *, spatial_ndim: int | None = None, weights: Array | ndarray | bool | number | bool | int | float | complex | None = None, period: float = 6.283185307179586, weight_floor: float = 0.001, weight_power: float = 4.0, max_iterations: int = 50, tolerance: float = 1e-05) → Array#

Unwrap trailing spatial axes independently for every leading index.

Two- and three-dimensional data use a fast cosine-transform least-squares initializer. When nonnegative weights are supplied, a fixed-budget preconditioned conjugate-gradient refinement emphasizes reliable spatial edges and confines inconsistencies to low-weight regions. One-dimensional data use direct Itoh integration.

The result differs from phase only by integer multiples of period. Leading frame, echo, observable and coil axes remain independent.

Parameters#

phase:

Real wrapped phase values in radians.

spatial_ndim:

Number of trailing spatial axes to unwrap (1, 2, or 3). If omitted, all axes are treated as spatial, up to three dimensions.

weights:

Optional nonnegative phase-reliability weights broadcastable to phase. Reconstruction callers should use image magnitude. Weights are normalized independently for each leading batch index.

period:

Phase period in the same units as phase. The default is 2 * pi.

weight_floor, weight_power:

Reliability floor and contrast used for spatial edge weights.

max_iterations, tolerance:

Fixed work limit and convergence tolerance for weighted refinement.

References#

D. C. Ghiglia and L. A. Romero, “Robust two-dimensional weighted and unweighted phase unwrapping that uses fast transforms and iterative methods,” JOSA A 11(1), 107-117 (1994), https://doi.org/10.1364/JOSAA.11.000107.

mrax.reco.components.reconstruction_variant(processed: Mapping[str, Any] | None, *, component: str = 'magnitude', coil: int | None = None, frame: int | None = None, unwrap_phase: bool = False, spatial_ndim: int | None = None) → ndarray#

Return a real magnitude or phase reconstruction.

coil=None selects the combined reconstruction. Its magnitude preserves the existing MRax/vendor-style combined magnitude. Combined phase is taken from a stored complex reconstruction when available, otherwise from the coherent sum of the channel-corrected coil images. Phase values are in radians in [-pi, pi] unless unwrap_phase=True. Spatial unwrapping is applied independently over leading frame/observable axes.

class mrax.reco.variational.MRIEncodingOperator(spatial_shape: tuple[int, ...], sensitivities: Array | None = None, mask: Array | None = None, trajectory: Array | None = None, density: Array | None = None, axes: tuple[int, ...] = (-2, -1), nufft_eps: float = 1e-06, independent_coils: bool = False, readout_coordinates: Array | None = None, readout_polarity: Array | None = None, readout_phase: Array | None = None)#

Explicit encoding and its mathematical adjoint on a declared spatial grid.

forward(image: Array, *, image_has_coils: bool | None = None) → Array#

Encode image batches. A receiver axis is always explicitly requested.

adjoint(kspace: Array, *, kspace_has_coils: bool | None = None, density_compensation: bool = False, normalize_sensitivities: bool = False) → Array#

Apply the true adjoint. Compensation and SENSE normalization are opt-in.

class mrax.reco.variational.RegridApodizationCorrection(kernel_width: float, shape_parameter: float, full_shape: tuple[int, ...] | None = None, crop_offset: tuple[int, ...] | None = None, strength: float = 1.0, normalization: str = 'relative')#

Kaiser-Bessel deapodization settings for gridding-style reconstructions.

The correction is applied in the image domain after optional cropping. full_shape and crop_offset describe the grid coordinate system used to evaluate the separable correction when the reconstruction is cropped from an oversampled grid.

mrax.reco.variational.build_operator(*, spatial_shape: tuple[int, ...] | None = None, kspace: Array | ndarray | None = None, sensitivities: Array | ndarray | None = None, mask: Array | ndarray | None = None, trajectory: Array | ndarray | None = None, density: Array | ndarray | None = None, axes: Sequence[int] | None = None, nufft_eps: float = 1e-06, independent_coils: bool = False, readout_coordinates=None, readout_polarity=None, readout_phase=None) → MRIEncodingOperator#

Build one explicit encoding operator for Cartesian or sampled inputs.

mrax.reco.variational.center_crop_spatial(image: Array | ndarray, output_shape: tuple[int, ...], crop_offset: tuple[int, ...] | None = None) → Array#

Crop the last len(output_shape) axes of an image or coil-image stack.

Use this after reconstructing on an oversampled grid. crop_offset=None performs a centered crop. Explicit offsets reproduce vendor cutoff windows or asymmetric grids.

mrax.reco.variational.checkerboard_phase(shape: tuple[int, ...]) → Array#

Return a +1/-1 checkerboard phase array for spatial image axes.

This is useful after FFT-style reconstructions when a scanner convention or gridding path leaves the image on the opposite centered-grid parity. It is the public version of the optional phase step in the acquisition recipe.

mrax.reco.variational.apply_regrid_apodization_correction(image: Array | ndarray, correction: RegridApodizationCorrection, spatial_shape: tuple[int, ...]) → Array#

Apply separable Kaiser-Bessel deapodization to a gridded reconstruction.

Apply this only when the gridding kernel matches the correction. For example, a vendor reconstruction using a Kaiser-Bessel convolution kernel can require this image-domain correction. Applying it to nearest-neighbor gridding is usually only a diagnostic experiment.

mrax.reco.variational.elliptical_support_mask(shape: tuple[int, ...], radius: float = 1.0) → Array#

Return a circular/elliptical support mask for 2D or 3D image shapes.

mrax.reco.variational.apply_image_support_mask(image: Array | ndarray, image_mask: str | Array | ndarray | None, spatial_shape: tuple[int, ...]) → Array#

Apply an image-domain support mask to the last spatial axes.

image_mask may be "ellipse"/"circle" or an explicit mask matching spatial_shape. Passing None returns the input unchanged.

mrax.reco.variational.combine_coil_images(coil_images: Array | ndarray, *, method: Literal['sum', 'rss', 'sense'] = 'sense', sensitivities: Array | ndarray | None = None, coil_axis: int | None = None, eps: float = 1e-08) → Array#

Combine coil images with sum, root-sum-of-squares, or SENSE weighting.

Parameters#

coil_images:

Array containing a coil axis and trailing spatial axes.

method:

"sum" for direct complex summation, "rss" for magnitude RSS, or "sense" for sensitivity-weighted combination. "sense" falls back to sum with sensitivities=None.

sensitivities:

Optional (coil, *spatial) sensitivity map for SENSE combination.

coil_axis:

Axis containing coils. If omitted, MRax assumes (frame, coil, *spatial) for non-SENSE data and infers the axis from sensitivities for SENSE data.

mrax.reco.variational.solve_variational(kspace: Array | ndarray, *, spatial_shape: tuple[int, ...] | None = None, sensitivities: Array | ndarray | None = None, mask: Array | ndarray | None = None, trajectory: Array | ndarray | None = None, density: Array | ndarray | None = None, data_weights: Array | ndarray | None = None, independent_coils: bool = False, readout_coordinates=None, readout_polarity=None, readout_phase=None, frame_shifts: Array | ndarray | None = None, frame_axis: int = 0, shift_order: int = 1, shift_mode: str = 'constant', shift_cval: float = 0.0, optimizer_name: str | None = None, step_size: float | None = None, num_steps: int = 50, regularizer: Literal['none', 'l2', 'l1', 'tv'] = 'tv', regularizer_weight: float = 0.01, tv_iterations: int = 2048, prox_tolerance: float = 1e-07, nufft_eps: float = 1e-06, bregman_penalty: float | None = None, initial_image: Array | ndarray | None = None, return_history: bool = False, grad_clip_norm: float | None = None, device: str | Device = 'cpu') → tuple[Array, list[float]] | Array#

Minimize a measured-sample mean squared error plus an image penalty.

Sampling masks retain frame and receiver dimensions. Density compensation only initializes the image. Statistical likelihood weights are supplied separately through data_weights. TV defaults to objective-aware FISTA with a certified proximal step. Explicit Adam with TV warns and smooths TV. Spatial grids can have one, two or three dimensions.

mrax.reco.variational.solve_model_based(kspace: Array | ndarray, *, experiment: Experiment, model: Model, spatial_shape: tuple[int, ...] | None = None, sensitivities: Array | ndarray | None = None, mask: Array | ndarray | None = None, data_weights: Array | ndarray | None = None, completion_kspace: Array | ndarray | None = None, completion_weight: float = 0.0, trajectory: Array | ndarray | None = None, density: Array | ndarray | None = None, optimizer_name: str | None = None, step_size: float = 0.02, num_steps: int = 200, encoding_batch_size: int | None = 32, regularizer_weight=0.0, regularizer_prox=None, optimizer_base_factory=None, box_constraints=None, initial_params: dict | None = None, regularizer_configs: dict[str, list[dict]] | None = None, regularizer_type: str | dict[str, str] | None = None, regularizer_weights: dict[str, float] | None = None, roi_mask: object | None = None, roi_mask_dims: tuple[str, ...] | None = None, object_support_mask: object | None = None, image_phase: Array | ndarray | None = None, image_to_encoding: Callable | None = None, encoding_frame_indices: Array | ndarray | None = None, readout_coordinates=None, readout_polarity=None, readout_phase=None, study_globals: dict[str, Quantity] | None = None, frame_mask: object | None = None, auto_mask_nan_observables: bool = True, nufft_eps: float = 1e-06, reference_image: Array | ndarray | Quantity | None = None, reference_kspace: Array | ndarray | None = None, reference_mask: Array | ndarray | None = None, reference_weight: float = 1.0, initial_reference_image: Array | ndarray | None = None, frame_phase_correction: str | None = 'none', return_history: bool = False, return_model_callable: bool = False, return_reconstruction_image: bool = False, proximal_tolerance: float = 1e-08, proximal_max_steps: int = 2048, bregman_penalty: float = 1.0, bregman_inner_steps: int = 5, device: str | Device = 'cpu') → tuple[dict[str, Quantity], list[float], Callable, Array] | tuple[dict[str, Quantity], list[float], Callable[[dict, Array | None, dict[str, Any] | None], Array]] | tuple[dict[str, Quantity], list[float]] | dict[str, Quantity]#

Directly reconstruct parameter maps from k-space via a chained model+encoding operator.

Minimizes RMS-normalized mean squared encoding error plus field regularizers. encoding_batch_size bounds frame-wise encoding workspace (default 32). None uses all frames at once. Temporal model/regularizer axes remain intact.

Notes#

  • The signal model comes from mrax.data_struct.model.Model and is treated as a (generally non-linear) operator mapping parameter fields -> image series.

  • The encoding operator \(A\) is the same as in solve_variational() (FFT/NUFFT, optional sampling mask, optional coil sensitivities).

  • roi_mask weights regularizers and masks output fields. Physical object support is supplied separately with object_support_mask. Fourier encoding retains the full object signal across analysis ROI boundaries.

  • frame_mask (or auto_mask_nan_observables=True) can drop frames with missing per-frame observables. Valid frames define the data term.

  • reference_image / reference_kspace can be used to model acquisitions where the signal model predicts a relative image series (e.g., Z-spectra). In that case the encoded prediction becomes \(A(reference\_image \cdot M(\theta))\). When reference_kspace is provided, the reference image is reconstructed jointly by adding a second data term \(reference\_weight \|\|A_{ref}(reference\_image) - reference\_kspace\|\|^2\).

  • completion_kspace / completion_weight can add an optional prior on the missing k-space samples (i.e., outside mask) by penalizing the difference to a filled k-space estimate (useful for partial Fourier / POCS-style completion). To match the weighting of a full-data mean-squared-error objective, set completion_weight=(1-f)/f where \(f=\mathrm{mean}(mask)\).

  • frame_phase_correction can apply a global phase alignment per frame (recommended for magnitude-only models when raw k-space contains frame-dependent phase flips).

  • return_reconstruction_image=True additionally returns the fitted image before output ROI masking, and requires return_model_callable=True.