Skip to content

Contrib — Optional Backends

Optional backends that wrap third-party libraries for advanced functionality.

pybaselines Backend

Note

Requires pybaselines: pip install pyspectrakit[baselines]

spectrakit.contrib._pybaselines.pybaselines_method

pybaselines_method(
    intensities: ndarray, method: str, **kwargs: Any
) -> np.ndarray

Apply any pybaselines method through a unified interface.

Parameters:

Name Type Description Default
intensities ndarray

Spectral intensities, shape (W,) or (N, W).

required
method str

Name of the pybaselines method (e.g., "asls", "airpls", "mor").

required
**kwargs Any

Keyword arguments forwarded to the pybaselines method.

{}

Returns:

Type Description
ndarray

Estimated baseline, same shape as intensities.

Raises:

Type Description
DependencyError

If pybaselines is not installed.

ValueError

If the method name is not recognized.

Source code in src/spectrakit/contrib/_pybaselines.py
def pybaselines_method(
    intensities: np.ndarray,
    method: str,
    **kwargs: Any,
) -> np.ndarray:
    """Apply any pybaselines method through a unified interface.

    Args:
        intensities: Spectral intensities, shape ``(W,)`` or ``(N, W)``.
        method: Name of the pybaselines method (e.g., ``"asls"``,
            ``"airpls"``, ``"mor"``).
        **kwargs: Keyword arguments forwarded to the pybaselines method.

    Returns:
        Estimated baseline, same shape as intensities.

    Raises:
        DependencyError: If pybaselines is not installed.
        ValueError: If the method name is not recognized.
    """
    baseline_cls = _get_pybaselines()
    intensities = ensure_float64(intensities)
    validate_1d_or_2d(intensities)

    return apply_along_spectra(
        _pybaselines_1d,
        intensities,
        method=method,
        baseline_cls=baseline_cls,
        **kwargs,
    )

spectrakit.contrib._pybaselines.list_pybaselines_methods

list_pybaselines_methods() -> dict[str, list[str]]

Return a dictionary of available pybaselines methods by category.

Returns:

Type Description
dict[str, list[str]]

Dict mapping category names to lists of method names.

Source code in src/spectrakit/contrib/_pybaselines.py
def list_pybaselines_methods() -> dict[str, list[str]]:
    """Return a dictionary of available pybaselines methods by category.

    Returns:
        Dict mapping category names to lists of method names.
    """
    return dict(_PYBASELINES_CATEGORIES)

lmfit Backend

Note

Requires lmfit: pip install pyspectrakit[fitting]

spectrakit.contrib._lmfit.fit_peaks

fit_peaks(
    intensities: ndarray,
    wavenumbers: ndarray,
    peak_positions: list[float],
    model: str = "gaussian",
    **kwargs: Any,
) -> FitResult

Fit spectral peaks using lmfit models.

Creates a composite model of multiple peaks and fits them to the data. Each peak is initialized near the specified position.

Parameters:

Name Type Description Default
intensities ndarray

Spectral intensities, shape (W,).

required
wavenumbers ndarray

Wavenumber axis, shape (W,).

required
peak_positions list[float]

Approximate peak center positions in wavenumber units.

required
model str

Peak shape model. One of "gaussian", "lorentzian", "voigt", "pseudo_voigt".

'gaussian'
**kwargs Any

Additional keyword arguments passed to lmfit.Model.fit.

{}

Returns:

Type Description
FitResult

FitResult with the best fit, individual components,

FitResult

parameters, and residual.

Raises:

Type Description
DependencyError

If lmfit is not installed.

ValueError

If the model name is not supported.

Source code in src/spectrakit/contrib/_lmfit.py
def fit_peaks(
    intensities: np.ndarray,
    wavenumbers: np.ndarray,
    peak_positions: list[float],
    model: str = "gaussian",
    **kwargs: Any,
) -> FitResult:
    """Fit spectral peaks using lmfit models.

    Creates a composite model of multiple peaks and fits them to the
    data. Each peak is initialized near the specified position.

    Args:
        intensities: Spectral intensities, shape ``(W,)``.
        wavenumbers: Wavenumber axis, shape ``(W,)``.
        peak_positions: Approximate peak center positions in
            wavenumber units.
        model: Peak shape model. One of ``"gaussian"``,
            ``"lorentzian"``, ``"voigt"``, ``"pseudo_voigt"``.
        **kwargs: Additional keyword arguments passed to ``lmfit.Model.fit``.

    Returns:
        ``FitResult`` with the best fit, individual components,
        parameters, and residual.

    Raises:
        DependencyError: If lmfit is not installed.
        ValueError: If the model name is not supported.
    """
    lmfit = _get_lmfit()
    intensities = ensure_float64(intensities)
    wavenumbers = ensure_float64(wavenumbers)

    if model not in SUPPORTED_MODELS:
        raise ValueError(f"Unknown model '{model}'. Supported: {list(SUPPORTED_MODELS.keys())}")

    model_class = getattr(lmfit.models, SUPPORTED_MODELS[model])

    # Build composite model
    composite = None
    params = lmfit.Parameters()

    for i, center in enumerate(peak_positions):
        prefix = f"p{i}_"
        peak_model = model_class(prefix=prefix)

        if composite is None:
            composite = peak_model
        else:
            composite = composite + peak_model

        # Initialize parameters near the peak position
        peak_height = float(intensities[np.argmin(np.abs(wavenumbers - center))])
        params.update(peak_model.make_params())
        params[f"{prefix}center"].set(value=center)
        params[f"{prefix}amplitude"].set(value=peak_height, min=0)

    if composite is None:
        raise ValueError("At least one peak position is required")

    result = composite.fit(intensities, params, x=wavenumbers, **kwargs)

    # Extract components
    components = []
    param_list = []
    for i in range(len(peak_positions)):
        prefix = f"p{i}_"
        component_params = {
            k.replace(prefix, ""): v.value for k, v in result.params.items() if k.startswith(prefix)
        }
        param_list.append(component_params)

        # Evaluate individual component
        comp_model = model_class(prefix=prefix)
        comp_vals = comp_model.eval(
            params=result.params,
            x=wavenumbers,
        )
        components.append(comp_vals)

    return FitResult(
        best_fit=result.best_fit,
        components=components,
        parameters=param_list,
        residual=intensities - result.best_fit,
        success=result.success,
        info={"redchi": result.redchi, "aic": result.aic, "bic": result.bic},
    )

spectrakit.contrib._lmfit.FitResult dataclass

Container for peak fitting results.

Attributes:

Name Type Description
best_fit ndarray

Fitted curve, shape (W,).

components list[ndarray]

Individual peak components, list of arrays.

parameters list[dict[str, float]]

Fitted parameter values per peak.

residual ndarray

Residual (data - fit), shape (W,).

success bool

Whether the fit converged.

Source code in src/spectrakit/contrib/_lmfit.py
@dataclass
class FitResult:
    """Container for peak fitting results.

    Attributes:
        best_fit: Fitted curve, shape ``(W,)``.
        components: Individual peak components, list of arrays.
        parameters: Fitted parameter values per peak.
        residual: Residual (data - fit), shape ``(W,)``.
        success: Whether the fit converged.
    """

    best_fit: np.ndarray
    components: list[np.ndarray]
    parameters: list[dict[str, float]]
    residual: np.ndarray
    success: bool
    info: dict[str, Any] = field(default_factory=dict)

spectrakit.contrib._lmfit.SUPPORTED_MODELS module-attribute

SUPPORTED_MODELS = {
    "gaussian": "GaussianModel",
    "lorentzian": "LorentzianModel",
    "voigt": "VoigtModel",
    "pseudo_voigt": "PseudoVoigtModel",
}