Fitting#

Build differentiable losses, fit individual experiments and execute study plans. See Fitting controls for the workflow and Optimizers and regularizers for solver controls.

Objective and inputs#

build_loss returns the scalar loss, initial parameter tree and field unpacker. Weighted least squares is the default. Masks combine spatial confidence, frames and observable support. mask_dims specifies their axis order. Each fit requires usable finite observations.

data_normalization="roi" computes RMS over retained finite observations. "full" uses all finite image data. To preserve regularization balance when switching from full-image to ROI normalization, multiply each regularizer weight by (RMS_full / RMS_roi)**2. Double-precision fits use JAX_ENABLE_X64=true with float64 data, observables and initial parameters.

reference_image fits signal intensities as the fixed spatial reference times the relative model prediction. Returned predictions include that scale, and measurement uncertainty in the reference remains relevant. Signal-domain and Z-spectrum weighting define distinct statistical objectives.

data_variance specifies observation variances, with uniform variance as the default and "auto" for robust estimation before fitting. The optional variance_estimation_mask identifies a noise region separately from the fitting mask. See Variance Estimation and Weighted Fitting.

A custom differentiable data_loss(residual, weights) receives RMS-normalized residuals and the combined mask/precision weights and returns a real scalar. All optimizer interfaces use that callable. Grouped pseudo-Huber loss applies one bounded influence to the RMS of consecutive frames at each spatial position. delta is in normalized residual units. Calibrate it from the training noise for the intended statistical objective.

mrax.core.loss_builder.build_loss(experiment: Experiment, model: Model, dataset: DataSet, regularizer_configs: dict[str, list[dict]] | None = None, regularizer_type: str | dict[str, str] | None = None, regularizer_weights: dict[str, float] | None = None, mask: object | None = None, mask_dims: tuple[str, ...] | None = None, mask_fill_value: float | int | Array | None = 0.0, study_globals: dict[str, Quantity] | None = None, frame_mask: object | None = None, data_variance: object | None = None, variance_estimation_mask: object | None = None, variance_estimation_mask_dims: tuple[str, ...] | None = None, auto_mask_nan_observables: bool = True, parameter_space: str = 'raw', smoothed_tv: bool = False, physical_scales: dict[str, float] | None = None, balance_parameters: bool = True, data_normalization: str = 'roi', device: str | Device = 'cpu', reference_image: object | None = None, *, data_loss: Callable[[Array, Array], Array] | None = None) → Tuple[Callable[[dict], Array], dict, Callable[[dict], dict]]#

Build loss(params) combining data misfit and model regularization.

data_variance supplies known relative observation variances as a scalar, per-frame array, spatial array, or array broadcastable to the data. Pass "auto" to robustly estimate per-frame variances before constructing the loss. The data misfit is an inverse-variance-weighted mean of RMS-scaled squared residuals. The loss is invariant to a common variance multiplier. None selects uniform variance.

reference_image multiplies relative model predictions by a fixed spatial reference. Supply measured signal intensities as the data in this mode.

data_normalization="roi" computes RMS over observations retained by finite-data, observable, ROI and frame masks. "full" retains the previous finite-image normalization. Fractional masks weight residuals. Their positive support determines the RMS sample set.

data_loss optionally maps RMS-scaled residuals and their nonnegative weights to a scalar differentiable data misfit. It is independent of the optimizer. Model regularizers are still added by this function.

mrax.core.loss_builder.make_model_callable(experiment: Experiment, model: Model, study_globals: dict[str, Quantity] | None = None, *, allow_raw_observables: bool = False, reference_image: object | None = None)#

Build predictions, optionally multiplying a relative model by a fixed reference.

mrax.core.data_losses.pseudo_huber_loss(residual, weights, *, delta, group_size=1)#

Weighted pseudo-Huber loss, optionally grouping consecutive frames.

delta is a positive cutoff in the RMS-scaled residual’s units. With group_size > 1, the whole group’s weighted RMS determines its common influence weight. The first dimension must contain consecutive groups. Other dimensions remain independent. Near zero, this agrees with weighted mean squared error. It approaches linear growth in the group’s RMS for large residuals. The rationalized expression avoids cancellation at zero.

Execution and continuation#

run_fit returns fitted fields with units and a loss history. return_model_callable=True adds the prediction callable. return_fit_info=True adds FitInfo after it. Study globals and observables are merged by make_model_callable.

step_size accepts a constant or Optax schedule. chunk_size sets the interval between host progress and finiteness checks. A progress callback may cancel by raising an exception. Early stopping uses convergence_tolerance, parameter_tolerance, convergence_patience and min_steps, with num_steps as the maximum.

History entries precede updates. info.final_loss evaluates the returned fields. info also records completed updates, termination and the complete checkpoint. Continue with initial_state=info.state and matching model, data, regularizers and optimizer. initial_params instead starts a fresh optimizer. Solver-family and state-layout changes require fresh optimizer state.

FitError reports nonfinite updates and failed proximal/backtracking certificates. Its last_valid_state and loss_history preserve the latest verified checkpoint when available.

mrax.core.loss_builder.run_fit(experiment: Experiment, model: Model, dataset: DataSet, optimizer_name: str | None = None, step_size: float | Callable[[Array], Array] = 0.02, num_steps: int = 200, 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, optimizer_factory=None, optimizer=None, mask: object | None = None, mask_dims: tuple[str, ...] | None = None, mask_fill_value: float | int | Array | None = 0.0, study_globals: dict[str, Quantity] | None = None, frame_mask: object | None = None, data_variance: object | None = None, variance_estimation_mask: object | None = None, variance_estimation_mask_dims: tuple[str, ...] | None = None, auto_mask_nan_observables: bool = True, return_model_callable: bool = False, compute_derived_maps: bool | None = None, progress_callback: Callable[[int, int, str], None] | None = None, chunk_size: int = 32, initial_state: FitState | None = None, convergence_tolerance: float | None = None, parameter_tolerance: float = 1e-05, convergence_patience: int = 5, min_steps: int = 0, return_fit_info: bool = False, proximal_tolerance: float | None = None, proximal_max_steps: int | None = None, bregman_penalty: float = 1.0, bregman_inner_steps: int = 1, balance_physical_parameters: bool = True, physical_metric: str = 'curvature', proximal_max_step_size: float | None = None, grad_clip_norm: float | None = None, data_normalization: str = 'roi', parameter_space: str = 'auto', fit_active_only: bool = False, device: str | Device = 'cpu', reference_image: object | None = None, *, fista_restart: str = 'gradient', fista_backtracking: str = 'full', data_loss: Callable[[Array, Array], Array] | None = None)#

Fit the model to data for a given experiment.

Supports Optax optimizers plus split_bregman and fista with optional proximal regularizers, box constraints, explicit parameter initializations, and per-parameter regularizer configs/weights (override model defaults). Custom Optax optimizers can be injected via optimizer or optimizer_factory. frame_mask and auto_mask_nan_observables let you ignore frames with missing per-frame observables (e.g., incomplete sat_time/b1 grids). data_variance applies inverse-variance weighting while retaining RMS loss scaling. Pass "auto" to estimate robust per-frame variances before optimization. None (the default) gives every included sample uniform variance. reference_image fits measured signal intensities by multiplying relative model predictions by a fixed spatial reference. Observations retain their measured signal scale. variance_estimation_mask optionally identifies a background/noise-only region for automatic estimation and is independent of the fitting mask. mask_fill_value controls how masked output fields are filled (use None to skip masking). NaN/inf entries in data or masks are treated as masked during fitting. compute_derived_maps controls derived map evaluation. When None, derived maps are automatically computed for diffusion models that provide derived_maps. step_size also accepts an Optax-compatible learning-rate schedule. chunk_size bounds device-side execution between progress/finiteness checks. Convergence is opt-in: convergence_tolerance and parameter_tolerance must hold for convergence_patience consecutive updates after min_steps. initial_state resumes raw parameters and optimizer moments from a previous mrax.core.fit_execution.FitInfo. It is mutually exclusive with initial_params. return_fit_info appends mrax.core.fit_execution.FitInfo to the normal return tuple. Its final_loss evaluates the returned parameters. History entries precede updates. Nonfinite fits raise mrax.core.fit_execution.FitError with the last valid chunk checkpoint. data_normalization="roi" uses retained observations for RMS scaling. Select "full" to reproduce the previous finite-image normalization. physical_metric selects a fixed curvature or initial-gradient block metric for true-TV fitting. Coordinates, boxes and TV weights are rescaled together. balance_physical_parameters=False disables this balancing. proximal_max_step_size optionally caps line-search step growth. parameter_space="physical" also permits affine coordinates with smooth model penalties. "auto" retains the default optimizer-dependent choice. fit_active_only=True packs the positive mask support and native TV graph while retaining the original forward-model geometry and output fields. grad_clip_norm optionally clips gradients of built-in optimizers. Proximal convergence checks still use the unmodified gradient. Split Bregman uses one safeguarded Newton/CG primal iteration by default. bregman_inner_steps controls additional primal work before shrinkage and the Bregman multiplier update. proximal_max_steps bounds each CG solve. Named, injected and factory-based proximal fits share defaults.

Study plans and diagnostics#

Study plans order experiments by their observable dependencies and may reuse precomputed fields. Shared options use run_fit_kwargs. Per-experiment options use run_fit_overrides. By default, experiments requiring additional observables receive skipped=True.

mrax.core.loss_builder.build_study_losses(study: Study, device: str | Device = 'cpu')#

Build per-experiment losses for a collection bundled as a Study.

mrax.core.study_runner.plan_study_fits(study: Study, target_names: Sequence[str] | None = None, precomputed_fields: dict[str, dict] | None = None) → list[PlannedFit]#

Return a sequential plan for a Study (optionally filtered/cached).

mrax.core.study_runner.execute_study_plan(plan: Sequence[PlannedFit], run_fit_kwargs: dict | None = None, run_fit_overrides: dict[str, dict] | None = None, *, skip_missing_observables: bool = True, warn_on_skip: bool = True, device: str | Device = 'cpu')#

Execute a planned Study fit in order, returning result entries and field cache.

When skip_missing_observables is True, experiments missing required observables are skipped with an explanatory warning and a skipped result entry.

run_fit_kwargs are passed to every fit. A value can be a mapping keyed by plan entry name to provide per-experiment values, except for dict-valued run_fit options such as regularizer_weights and study_globals. Use run_fit_overrides for explicit per-experiment keyword overrides.

mrax.core.fit_sanity.check_fit_sanity(experiment: Experiment, model: Model, dataset: DataSet, *, study_globals: Mapping[str, Quantity] | None = None, check_data: bool = True) → FitSanityReport#

Validate fitting inputs. Disable check_data for metadata-only preflight.

class mrax.core.fit_sanity.FitSanityReport(experiment_name: str, model_name: str, dataset_shape: tuple[int, ...], errors: list[str] = <factory>, warnings: list[str] = <factory>, notes: list[str] = <factory>, missing_observables: list[str] = <factory>, missing_any_of: list[tuple[str, ...]] = <factory>)#

Structured report describing whether a fit is ready to run.

mrax.core.variance.estimate_data_variance(experiment: Experiment, dataset: DataSet, *, mask: object | None = None, mask_dims: tuple[str, ...] | None = None, method: str = 'auto', min_samples: int = 32, shrinkage: float = 32.0) → VarianceEstimate#

Estimate robust per-frame observation variances before model fitting.

method="auto" first looks for a low-signal background region. Nonnegative magnitude data uses the Rayleigh-background median-square estimator. Signed real or complex data uses a median-absolute-deviation estimate. Ambiguous background support selects "wavelet_mad", which applies a normalized diagonal Haar high-pass transform over the two largest spatial axes. mask defines the noise-sampling region.

Estimates with limited support are shrunk toward the median frame variance. Magnitude MRI is treated with the usual high-SNR Gaussian approximation. Low-SNR Rician or noncentral-chi data require an acquisition-specific noise model.

class mrax.core.variance.VarianceEstimate(variance: ndarray, sample_count: ndarray, method: str, pooled_variance: float, warnings: tuple[str, ...] = ())#

Per-frame observation-variance estimate and estimator diagnostics.

variance uses squared data units. For complex data it estimates \(E[|n|^2]\), the sum of real- and imaginary-channel variances.

property standard_deviation: ndarray#

Return per-frame standard deviations in data units.

property relative_variance: ndarray#

Return variances normalized to a median of one.