calamari.boundary.fit_boundary#

calamari.boundary.fit_boundary(points, model, *, swept_axis=None, compare=(), yerr_sys=None, exclude=(), initial=None, limits=None, fixed=None)#

Fit a stated form to one criterion’s points, one per sweep, and say how far to trust it.

The second stage of the two-stage route: detection and select() give each sweep at most one point, and this fits a curve through them – the location against the held coordinate, weighted by each point’s error – with fit() (iminuit MIGRAD + HESSE, FT-1). The form is the caller’s assumption. The points cannot choose it: two forms can pass through the same points inside their errors and disagree everywhere else, which is why compare= and the band’s restriction to the data range exist.

Parameters:
  • points (TransitionResult | DataFrame) –

    One point per sweep, in one of two forms.

    • A TransitionResult that has been select()-ed on the swept axis. Its selection sets the criterion (method/sign). An unselected result is refused, because a sweep then holds several candidates and they would be counted as separate data. The family is every sweep the result knows of: searched (params['per_sweep']) and skipped (skipped); sweeps swept along the other axis belong to the other family, and their ids are recorded in params['other_axis_sweep_ids'].

    • A DataFrame with one row per sweep and the columns POINT_COLUMNS names for swept_axis: sweep_id, the held coordinate, the location, its statistical error and criterion. Optional columns: significance, the systematic error (T_err_sys_K or H_err_sys_T, instead of yerr_sys=) and measurement_file. A row with a NaN location is a sweep with no point, and is listed as such. This is the form for per-sweep fit_breakpoint() results: T_K=x_break, T_err_K=x_break_err, and a criterion such as 'breakpoint:segmented_linear'. Duplicate sweep_id values are refused: several smoothing windows or fitting ranges of one sweep are one point with a systematic spread, never several rows.

  • model (str | ModelDefinition) – The form: a registered model name or a ModelDefinition, called as f(held, *params) and returning the location. A monotonic boundary means a monotonic parametric form; nonparametric isotonic regression is not offered in this version (it gives no parameters and no band).

  • swept_axis (str | None) – Which coordinate the criterion located. 'T': T_K +/- T_err_K against the held H_T. 'H': H_T +/- H_err_T against the held T_K. Required for a DataFrame, and for a result selected on both axes; otherwise taken from the one selection.

  • compare (Sequence[str | ModelDefinition]) – Simpler forms to fit to the same points with the same errors, for BoundaryFit.comparison. Each starts from its own param_defaults and guess; to seed one differently, define it with different defaults.

  • yerr_sys (float | Mapping | Series | None) – A systematic error per sweep, supplied by the caller: the half-spread of a feature’s location across the smoothing windows of a scan_smoothing() scan, say, or across the ranges of a fit_windows() run. A mapping (or Series) from sweep_id to the error, in the location’s unit, with a finite, non-negative value for every sweep with a point, or one number for all. Nothing is derived by default. When given, the fit is made twice and both are reported: with the statistical errors alone (the returned object) and with statistical and systematic in quadrature (.total).

  • exclude (Iterable) – Points to leave out of the fit. They stay in sweeps, marked 'excluded by caller', with their residual from the fit made without them, and in params['exclude'].

  • initial (dict[str, float] | None) – As for fit(), for the stated model. The jackknife refits use the same limits and fixed values, seeded at the full fit.

  • limits (dict[str, tuple[float, float]] | None) – As for fit(), for the stated model. The jackknife refits use the same limits and fixed values, seeded at the full fit.

  • fixed (dict[str, float] | None) – As for fit(), for the stated model. The jackknife refits use the same limits and fixed values, seeded at the full fit.

Return type:

BoundaryFit

Returns:

BoundaryFit – The fit with statistical errors, its diagnostics and the recipe; the stat+sys fit, when there is one, in .total.

Raises:
  • ValueError – For an unselected result, or one selected on another axis; a result selected on both axes without swept_axis; a DataFrame without swept_axis, missing a required column (named), or with a missing or duplicate sweep_id; points of more than one criterion; a used point whose held coordinate is not finite or whose error is not finite and positive; exclude or yerr_sys naming a sweep that is unknown or has no point; a malformed yerr_sys, or one given beside a systematic column.

  • FitConstraintError – A forwarded fixed value conflicts with its limits; propagated from fit() before minimisation.

  • KeyError – For an unknown model name, here or in compare, or an unknown parameter in initial, limits or fixed.

Warns:

UserWarning – When a fit does not converge, when the scatter is below the errors (LOW_CHI2_TAIL), when a jackknife refit fails, and when a compared model does not converge. Each is also kept in BoundaryFit.warnings, and the result is returned regardless.

Notes

Weights. Each point is weighted by its location error alone (absolute errors, the fit(..., yerr=) convention). significance is shown in sweeps and never used as a weight. It is a normalised strength diagnostic used in filtering, not a calibrated probability that a feature is real. How well the point is located is its error’s job, and a weak feature that is sharply placed is sharply placed. Weighting by significance as well would count the strength twice, and would have no likelihood behind it.

Grid-floored errors. A candidate’s location error is floored at the scan’s grid spacing (docs/DETECTION.md). On clean sweeps the floor is all of it, the points sit far closer to the curve than their errors, and chi2/dof comes out near zero. BoundaryFit.scatter_below_errors flags that, from the chi-squared distribution for the fit’s dof (see LOW_CHI2_TAIL). The HESSE errors and the band are then the floor propagated, not the scatter, and the jackknife standard error, which is driven by the scatter itself, comes out far smaller. Above the floor the error comes from a local quadratic fit to smoothed data, whose residuals the smoothing correlates, so it is somewhat optimistic: chi2/dof well above 1 means that, or a form that does not fit.

The band is value +/- sqrt(J C J^T) at each held value, the first-order propagation of the fit covariance C (derive()). It is exact for a form linear in its parameters and good when the relative errors are small. It describes the model under its assumptions and says nothing about whether the form is right.

The jackknife. Each used sweep is left out and the model refitted. *_shift_sigma is the shift of each parameter, in units of its HESSE error, and the sweep with the largest is the one the curve leans on most. The jackknife standard error, sqrt((n - 1)/n * sum((p_i - p_mean)^2)), estimates the parameter’s spread from the points’ own scatter rather than from their stated errors, so set beside HESSE it is a second check on those errors. With few sweeps it is itself noisy. It is NaN unless every refit succeeded, because the formula needs all n. Leaving one observation out at a time is Quenouille’s jackknife (M. H. Quenouille, “Notes on bias in estimation”, Biometrika 43, 353 (1956)); the variance estimate is the one B. Efron and C. Stein analyse in “The jackknife estimate of variance”, Ann. Statist. 9, issue 3 (1981), doi:10.1214/aos/1176345462.

Information criteria. With the errors taken as known, -2 ln L is chi-squared up to a constant, so AIC = chi2 + 2k and BIC = chi2 + k ln n for k free parameters and n used points. delta_aic and delta_bic are the compared model’s minus the stated model’s, so positive favours the stated model. They inherit the errors’ scale: overstated errors (scatter_below_errors) shrink every chi-squared difference and leave the parameter penalty, which favours the simpler form; understated ones do the opposite. They describe; they do not test.

Examples

>>> import numpy as np
>>> import pandas as pd
>>> from calamari import fit_boundary
>>> rng = np.random.default_rng(5)
>>> h = np.linspace(0.0, 1.8, 10)
>>> t = 14.0 - 1.5 * h**2 + rng.normal(scale=0.05, size=h.size)
>>> points = pd.DataFrame({"sweep_id": range(10), "H_T": h, "T_K": t,
...                        "T_err_K": 0.05, "criterion": "peak/max"})
>>> from calamari.fitting import ModelDefinition
>>> quadratic = ModelDefinition(
...     name="quadratic", function=lambda h, t0, b: t0 - b * np.asarray(h) ** 2,
...     param_names=("t0", "b"), param_defaults={"t0": 10.0, "b": 1.0},
...     description="t0 - b H^2")
>>> bf = fit_boundary(points, quadratic, swept_axis="T", compare=["linear"])
>>> print(bf.estimates[["parameter", "value", "hesse_err"]].round(3).to_string(index=False))
parameter  value  hesse_err
       t0 13.975      0.023
        b  1.477      0.015
>>> bool(bf.comparison.loc[1, "delta_bic"] > 0)   # the straight line fits far worse
True