calamari.fitting.breakpoint.fit_breakpoint#
- calamari.fitting.breakpoint.fit_breakpoint(x, y, *, yerr=None, limits=None, model='segmented_linear')#
Fit two lines meeting at a corner, and compare them with one straight line.
Fits
segmented_linear(seesegmented_linear()) andlinearto the same points, and reports the corner with the evidence for it. The corner isx_break +/- x_break_err(HESSE, canonical under FT-1), and the evidence isdelta_aic/delta_bic. Read the evidence first: with no break in the data, the corner still gets a value and a small error bar, and both are meaningless. So this warns, and setsidentified=False, wheneverdelta_bic <= 0. That threshold is not tuned: it is where the comparison itself changes sign. It warns too when the corner ends within its error of a limit, because then the limit, not the data, is placing it. The result is returned either way (warn, don’t fix).With
model="bent_cable"the corner is rounded by a parabolic bend whose half-widthgammais fitted too (bent_cable()), andx_breakis the centre of the bend. The sharp corner is still fitted, on the same points, so the result compares all three:delta_bicagainst the straight line as before, anddelta_bic_vs_segmentedagainst the sharp corner. Use it when the sharp corner moves with the fitting range (caveat 2 below). Two more warnings apply. One is raised whengammaends within its error of its lower bound, half a sample spacing: the rounding is not resolved, and the sharp corner describes the data as well. The other is raised when the bend leaves fewer than three points on a straight arm:x_breakis where the two arms meet, and it is poorly defined when an arm is not established. That second one setsidentified=False.- Parameters:
x (
ArrayLike) – One sweep’s points, 1-D and finite: pass only the range around the feature, since both lines must describe the data on their side of the corner. Order does not matter.y (
ArrayLike) – One sweep’s points, 1-D and finite: pass only the range around the feature, since both lines must describe the data on their side of the corner. Order does not matter.yerr (
ArrayLike|None) – Per-point errors, used to weight the parameter fits, as infit()(absolute errors).None(default) estimates one scatter from the residuals. The model comparison and the profile ignoreyerr(see Notes).limits (
tuple[float,float] |None) – Bounds onx_break. The default is the range from the 3rd to the 3rd-from-last point in ascendingx, so the corner keeps at least three points strictly on each side: two points fix a line exactly, and three is the fewest that leaves each line a residual degree of freedom. Given limits must lie within that range and contain at least one sample position.model (
str) – The corner: sharp (the default) or rounded. For the bent cablegammais bounded to[s / 2, span], withsthe median spacing of the distinctxandspantheir full range: below half a spacing a bend holds at most one sample and cannot be resolved, and beyond the span every point is already inside it. The bounds are recorded inparams['gamma_limits'].
- Return type:
- Returns:
BreakpointResult– The fits, the corner and slopes with their errors, the comparisons, the RSS profile with its display-only interval,identified, the warnings raised, and the recipe inparams.- Raises:
ValueError – For
xandythat are not 1-D, of equal length and finite; for fewer than seven points; for ayerrof the wrong shape or not finite and positive; forlimitsthat are not a finite(lower, upper)pair inside the default range, or that hold no sample position; and for amodelother than the two above. A fit that fails is not an error: it comes back withidentified=Falseand a warning.- Warns:
UserWarning – When
delta_bic <= 0(no break preferred), when the corner lies within its HESSE error of a limit, and when any fit fails. For the bent cable, also whengammalies within its HESSE error of its lower bound, and when the bend leaves fewer than three points on either arm.
Notes
Why the comparison uses the plain residual sum of squares. Both criteria come from a Gaussian likelihood with one unknown noise level, maximised by ordinary least squares:
-2 ln L = n ln(RSS / n) + const. Hencedelta_aic = n ln(RSS_linear / RSS_segmented) - 2 (4 - 2)anddelta_bic = n ln(RSS_linear / RSS_segmented) - (4 - 2) ln n. They use the unweighted RSS whateveryerris, because a chi-squared built on instrument error columns would inherit their scale, and such columns have been seen 130 to 500 times the real scatter. The comparison then asks only whether the data’s own scatter is reduced enough by a corner.RSS_segmentedis minimised exactly over the corner inside the limits (knots and each interval’s two-line solution), so withyerr=Noneit is the minimum the segmented fit reaches.The profile interval. Holding the corner at
cand solving the rest exactly gives the profiledRSS(c). With the noise level maximised out, the likelihood-ratio statistic for the corner isn ln(RSS(c) / RSS_segmented). The usual one-parameter 68.3 % (1 sigma) construction keeps the corners where that is at most 1, the 68.3 % point of chi-squared with one degree of freedom. So the interval is everycwithRSS(c) <= RSS_segmented * exp(1 / n)(profile_threshold). It is the natural picture for a corner, because it shows asymmetry and a second basin that HESSE cannot. But it is display-only, for the reason in the first caveat below: the chi-squared calibration is asymptotic, and it fails exactly when the break is weak. HESSE stays canonical.The bent cable. The same construction applies with five parameters:
delta_bic = n ln(RSS_linear / RSS_bent_cable) - (5 - 2) ln n, and against the sharp cornerdelta_bic_vs_segmented = n ln(RSS_segmented / RSS_bent_cable) - (5 - 4) ln n(and the AIC forms with2 k). The sharp corner is the bent cable atgamma = 0, a value at the edge of the allowed range, so that comparison has no chi-squared calibration either, and is descriptive too. The bent cable has no closed-form profile, soRSS_bent_cableis found numerically. The centre is held at each sample position, and the half-width is minimised by a logarithmic grid refined by a bounded minimiser, with the three linear parameters exact. The best centre is then refined between samples, and MIGRAD’s own minimum is taken if it is lower. The profile and its interval therefore hold the centre and minimise the half-width at each value: the honest analogue of the sharp corner’s, not a slice at the fittedgamma. Where a bend would reach past an end of the data, only the far end of the bend is constrained, and the profile goes flat. That is the regime of the arms warning.Limitations
Under the no-break hypothesis, the breakpoint location is undefined, so the likelihood-ratio statistic does not follow the usual one-degree-of-freedom chi-squared law [1].
delta_aicanddelta_bicare descriptive comparisons, not significance tests.Rounding and model mismatch can shift the fitted location beyond its HESSE interval. Repeat fits over justified ranges for both sharp and bent-cable models. Asymmetric rounding need not have a unique physically meaningful centre. Correlated residuals are not included in the reported HESSE errors.
The intersecting-line problem is described by [2]. Muggeo [3] describes an iterative linearisation approach; Calamari instead seeds MIGRAD from a least-squares profile. The bent-cable model and its least-squares theory follow [4].
References
Examples
>>> import numpy as np >>> from calamari.fitting import fit_breakpoint, segmented_linear >>> x = np.linspace(4.0, 14.0, 51) >>> rng = np.random.default_rng(7) >>> y = segmented_linear(x, 8.2, 1.0, 0.2, -0.2) + rng.normal(scale=0.004, size=x.size) >>> bp = fit_breakpoint(x, y) >>> print(f"x_break = {bp.x_break:.3f} +/- {bp.x_break_err:.3f}, identified={bp.identified}") x_break = 8.201 +/- 0.010, identified=True