Skip to content

fit.py API

bh_molecule.fit

Classes

BHFitter

Blackbody-Hydrogen molecular spectrum fitter.

This class wraps a model object providing full_fit_model and a vis data source exposing spectrum(frame, channel) to perform parameter estimation over a wavelength window and to visualize the resulting fits.

Parameters:

Name Type Description Default
vis object

Data source exposing spectrum(frame, channel) -> (wl, spec).

required
model object

Model providing full_fit_model(x, C, T_rot, dx, w_inst, base, I_R7, I_R8).

required
nm_window tuple

Wavelength window (lo, hi) in nanometers to select data for fitting. Default is (433.05, 433.90).

(433.05, 433.9)
p0 tuple or array - like

Initial guess for fit parameters. Default is (1.0, 4000.0, 0.01, 0.025, 0.0, 1e-3, 1e-3).

(1.0, 4000.0, 0.01, 0.025, 0.0, 0.001, 0.001)
bounds tuple

Lower and upper bounds for parameters. Should be (lower, upper) where each is array-like. Defaults to ([0, 0, 0, 0, -10, 0, 0], [10, 10000, 1, 0.1, 10, 1, 1]).

([0, 0, 0, 0, -10, 0, 0], [10, 10000, 1, 0.1, 10, 1, 1])
maxfev int

Maximum function evaluations passed to the underlying optimizer.

40000
weight (none, poisson)

Weighting scheme for the fit. If 'none' (default) no weighting is used. If 'poisson', sigma is taken as sqrt(y). If a callable is provided it must have signature weight(x, y) -> sigma.

'none'
warm_start bool

If True reuse the last found parameters as initial guess for the next fit. Defaults to False.

False

Attributes:

Name Type Description
param_names list of str

Human-readable parameter names used in result tables.

param_units list of str

Units corresponding to param_names.

Attributes
bounds = (np.asarray(bounds[0], float), np.asarray(bounds[1], float)) instance-attribute
maxfev = int(maxfev) instance-attribute
model = model instance-attribute
nm_window = tuple(map(float, nm_window)) instance-attribute
p0 = np.asarray(p0, float) instance-attribute
param_names = ['C', 'T_rot', 'dx', 'w_inst', 'base', 'I_R7', 'I_R8'] instance-attribute
param_units = ['', 'K', 'nm', 'nm', '', '', ''] instance-attribute
vis = vis instance-attribute
warm_start = bool(warm_start) instance-attribute
weight = weight instance-attribute
Functions
batch(frames, channels, return_curves=False)

Run fits for multiple frames and channels and collect results.

Parameters:

Name Type Description Default
frames iterable

Iterable of frame indices to fit.

required
channels iterable

Iterable of channel indices to fit.

required
return_curves bool

If True, also return a dictionary mapping (frame, channel) to the tuple (x, y, yfit). Default is False.

False

Returns:

Name Type Description
df DataFrame

Table of fit results with one row per attempted fit. Columns include parameter values, parameter errors (<name>_err), chi2_red, R2, npts and any error messages for failed fits.

curves (dict, optional)

Only returned when return_curves is True. Dictionary keyed by (frame, channel) mapping to (x, y, yfit).

fit(frame, channel, return_fit=True, p0=None)

Fit the model to a single frame/channel spectrum.

Parameters:

Name Type Description Default
frame int

Frame index to fit.

required
channel int

Channel index to fit.

required
return_fit bool

If True, include the fitted model curve (yfit) in the result dictionary. Default is True.

True
p0 array - like

Initial guess for the fit parameters. If None uses the fitter's p0 or the last fit parameters when warm_start is enabled.

None

Returns:

Name Type Description
result dict

Dictionary containing fit results and metadata with keys: - frame: frame index - channel: channel index - params: fitted parameter array - cov: covariance matrix from curve_fit - errors: 1-sigma parameter uncertainties - summary: pandas DataFrame with formatted parameter values - x: wavelengths used for the fit - y: observed spectrum used for the fit - yfit: (optional) model-evaluated fit curve when return_fit is True

plot_grid(curves, frames=None, channels=None, ncols=3, xlim=None, ylim=None, suptitle=None)
plot_overlay(curves, frame, channels=None, xlim=None, ylim=None, title=None, *, cmap: str = 'tab10', line_width: float = 1.0, line_alpha: float = 0.95, scatter_size: float = 8.0, scatter_alpha: float = 0.35, legend_cols: int | None = None)
plot_single(res, xlim=None, ylim=None, title=None, ax=None)
set_bounds(lower=None, upper=None)

Update parameter bounds for the fitter.

Parameters:

Name Type Description Default
lower sequence or dict

Lower bounds for parameters. If a sequence is provided it must have the same length as param_names. If a dict is provided, keys must match parameter names and only those bounds will be updated.

None
upper sequence or dict

Upper bounds for parameters. Same rules as lower.

None
Notes

Bounds are stored internally as numpy arrays in self.bounds. This method allows updating either all bounds at once or only selected parameters.

Spectrum fitter for BH A–X band: parameter estimation, channel/frame iteration, and visualization.