Skip to content

least_squares

least_squares

Levenberg-Marquardt model fitting for osipy.

This module provides non-linear least squares optimization using xp-compatible operations. Works on any FittableModel — the fitter never knows about modality-specific context (time, AIF, b-values).

NO scipy dependency - uses custom vectorized Levenberg-Marquardt implementation that processes all voxels in parallel via batch operations. Works identically on CPU (NumPy) and GPU (CuPy).

References

Marquardt (1963). An Algorithm for Least-Squares Estimation of Nonlinear Parameters. SIAM Journal on Applied Mathematics.

LevenbergMarquardtFitter

LevenbergMarquardtFitter(
    max_iterations=100,
    tolerance=1e-06,
    chunk_size=None,
    r2_threshold=0.5,
)

Bases: BaseFitter

Vectorized Levenberg-Marquardt fitter.

Processes all voxels simultaneously using batched array operations. GPU/CPU is automatic via xp = get_array_module() — no manual use_gpu flag needed.

Supports analytical Jacobians via FittableModel.compute_jacobian_batch(). Falls back to numerical finite differences when the model returns None.

PARAMETER DESCRIPTION
max_iterations

Maximum number of LM iterations per batch.

TYPE: int DEFAULT: 100

tolerance

Convergence tolerance for relative cost change.

TYPE: float DEFAULT: 1e-06

chunk_size

Number of voxels per processing chunk for memory management. Defaults to get_backend().default_batch_size.

TYPE: int | None DEFAULT: None

r2_threshold

Minimum R-squared value for a valid fit.

TYPE: float DEFAULT: 0.5

Examples:

>>> from osipy.common.fitting.least_squares import LevenbergMarquardtFitter
>>> fitter = LevenbergMarquardtFitter(max_iterations=100)
>>> result = fitter.fit_image(bound_model, data_4d, mask=brain_mask)

fit_batch

fit_batch(model, observed_batch, bounds_override=None)

Fit a batch of voxels using vectorized Levenberg-Marquardt.

PARAMETER DESCRIPTION
model

Model with independent variables bound.

TYPE: FittableModel

observed_batch

Observed data, shape (n_observations, n_voxels).

TYPE: NDArray

bounds_override

Per-parameter bound overrides.

TYPE: dict DEFAULT: None

RETURNS DESCRIPTION
params

Fitted parameters, shape (n_params, n_voxels).

TYPE: NDArray

r2

R-squared values, shape (n_voxels,).

TYPE: NDArray

converged

Convergence flags, shape (n_voxels,).

TYPE: NDArray