Fit Package

The fit package wraps a fitting backend (currently lmfit) behind a small, declarative API. Callers describe the models they want with ModelName enums and a per-model options dict, and receive a FitResult that exposes fitted components by prefix.

Overview

Source module:

tavi.library.fit.fit

Selecting a backend:

class tavi.library.fit.fit.FitPackage(*values)[source]

Supported fitting backends.

lmfit = 'lmfit'

Available models:

class tavi.library.fit.fit.ModelName(*values)[source]

Supported peak/background model shapes.

Custom = 'Custom defined model'
Gaussian = 'Gaussian'
Linear = 'linear model'
Lorentzian = 'Lorentzian'
Voigt = 'Voigt'

Primary class:

class tavi.library.fit.fit.Fit(package: FitPackage = FitPackage.lmfit)[source]

Provide a universal interface for tavi fit.

fit(x: ndarray, y: ndarray, model_dict: list[tuple[ModelName, dict[str, Any]]]) FitResult[source]

Fit a composite model built from one or more named sub-models.

Each sub-model may carry a prefix so its parameters are namespaced in the composite fit (e.g. g1_center, g2_center, exp_decay). Currently only the lmfit backend is supported.

Parameters:
  • x – Independent variable values.

  • y – Measured values to fit.

  • model_dict

    Sequence of (model_name, initial_params) pairs. initial_params is a dict that may hold:

    • prefix: parameter namespace for this component (default “”).

    • guess: if truthy, let the model guess initial parameters from the data instead of using explicit values.

    • center / sigma / amplitude: initial values used when guess is not set.

    • set: optional {param_name: options} mapping applied on top of the initial values, where options is forwarded to lmfit.Parameter.set(). Use it to fix a parameter (vary=False), bound it (min=/max=), or tie it to another (expr=). Names are bare (the prefix is added automatically), e.g. set={"center": dict(value=0.5, vary=False)}.

Returns:

A FitResult with one ComponentResult per component, keyed by prefix.

Result Objects

A fit returns a FitResult aggregating one ComponentResult per model component, keyed by its prefix.

class tavi.library.fit.fit.FitResult(components: dict[str, ComponentResult], reduced_chi_squared: float, best_fit: ndarray, raw: Any, fit_function: Any)[source]

Backend-agnostic result of a (possibly multi-component) peak fit.

Holds one ComponentResult per model component, keyed by prefix, so callers do not depend on any specific fitting library. The native backend result is kept in raw as an escape hatch for advanced use.

For a single-component fit, the common scalar parameters (center, sigma, amplitude, fwhm, height) and their *_err counterparts can be read directly as attributes; they delegate to the only component. With multiple components, read them via result[prefix].

components

Prefix -> ComponentResult for every model component.

Type:

dict[str, tavi.library.fit.fit.ComponentResult]

reduced_chi_squared

Reduced chi-square of the fit.

Type:

float

best_fit

Model evaluated at the input x (same shape as the data).

Type:

numpy.ndarray

raw

The native backend result object.

Type:

Any

fit_function

The (composite) model object used for the fit.

Type:

Any

property peak: ComponentResult

Return the single peak-shaped component (the one with a center).

Lets callers read peak parameters (center, fwhm, height) regardless of how many background components (e.g. a linear term) are present in the composite fit.

Raises:

ValueError – If there is not exactly one component with a center.

property peaks: list[ComponentResult]

Return every peak-shaped component (those with a center).

Background components (e.g. a linear term) have no center and are excluded. Ordered as the components were supplied to the fit.

class tavi.library.fit.fit.ComponentResult(prefix: str, values: dict[str, float], errors: dict[str, float | None])[source]

Fitted parameters for a single model component, identified by its prefix.

A composite fit is made of one or more components (e.g. g1_, g2_, exp_). Each component stores the bare parameter names (with the prefix stripped) so callers can read e.g. component["center"] regardless of the prefix used in the composite model.

prefix

The prefix lmfit assigned to this component (”” if none).

Type:

str

values

Bare parameter name -> fitted value (e.g. center, sigma, amplitude).

Type:

dict[str, float]

errors

Bare parameter name -> 1-sigma uncertainty, or None if not estimated.

Type:

dict[str, float | None]

Model Specification

Models are passed as a list of (ModelName, options) tuples. Each entry adds one component to the composite model; options is forwarded to the backend (for example dict(guess=True) to auto-initialize parameters).

from tavi.library.fit.fit import FitPackage, ModelName

model_dict = [
    (ModelName.Gaussian, dict(guess=True)),
    (ModelName.Linear, dict()),
]

Minimal Example

import numpy as np
from tavi.library.fit.fit import Fit, FitPackage, ModelName

x = np.linspace(-5, 5, 100)
y = np.exp(-(x**2)) + 0.01 * x

fit = Fit(package=FitPackage.lmfit)
result = fit.fit(x, y, [(ModelName.Gaussian, dict(guess=True))])

# Single-component fits expose scalar parameters directly.
print(result.center, result.center_err)
print(result.reduced_chi_squared)

# With multiple components, read each by its prefix instead:
#   result["g1_"].values["center"]