Skip to content

fit.py

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 a grid of fit curves.

Parameters:

Name Type Description Default
curves dict

Mapping from (frame, channel) to (x, y, yfit) tuples.

required
frames iterable

If provided, only include these frames.

None
channels iterable

If provided, only include these channels.

None
ncols int

Preferred number of columns in the plot grid.

3
xlim tuple

Axis limits forwarded to each subplot.

None
ylim tuple

Axis limits forwarded to each subplot.

None
suptitle str

Optional figure-level title.

None

Returns:

Type Description
fig, axes : tuple

Matplotlib figure and axes array for the created grid.

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)

Overlay multiple channels for a single frame.

Parameters:

Name Type Description Default
curves dict

Mapping from (frame, channel) to (x, y, yfit) tuples.

required
frame int

Frame index to draw.

required
channels iterable

If provided, only include these channels.

None
xlim tuple

Axis limits.

None
ylim tuple

Axis limits.

None
title str

Axis title.

None
cmap str

Matplotlib colormap name used to assign channel colors.

'tab10'
line_width float

Width of the model lines.

1.0
line_alpha float

Transparency for model lines.

0.95
scatter_size float

Size for scatter points.

8.0
scatter_alpha float

Alpha for scatter points.

0.35
legend_cols int or None

Number of columns for the legend. If None a sensible default is chosen.

None

Returns:

Type Description
fig, ax : tuple

Matplotlib figure and axis containing the overlay plot.

plot_single(res, xlim=None, ylim=None, title=None, ax=None)

Plot a single fit result (data and optional model curve).

Parameters:

Name Type Description Default
res dict

Result dictionary as returned by fit (must contain x and y; may contain yfit).

required
xlim tuple

X-axis limits as (xmin, xmax). Defaults to the fitter's nm_window.

None
ylim tuple

Y-axis limits as (ymin, ymax).

None
title str

Plot title.

None
ax Axes

Axis to draw into. If None a new figure and axis are created.

None

Returns:

Name Type Description
ax Axes

The axis containing the plot.