calamari.transitions.TransitionResult#
- class calamari.transitions.TransitionResult(candidates, detections, params, skipped=(), curves=dict(), chains=None, full_candidates=None, full_detections=None, full_chains=None)#
Bases:
objectDetected transition candidates plus the evidence and the recipe.
- candidates#
One row per grouped feature (
CANDIDATE_COLUMNS). The current – possiblyrobust()-filtered andselect()-ed – view, carrying thecross_*columns oncereconcile()has run.- Type:
- detections#
One row per raw detector hit (
DETECTION_COLUMNS), linked bycandidate_id; this is where “the cusp and the steepest slope were 0.3 K apart” stays visible after grouping. Filtered alongsidecandidates: a detection survives iff its candidate does.- Type:
- params#
Every parameter as resolved (methods, criterion priority, windows in physical units, noise source, package version, and – on a filtered result – the
'robust'thresholds and the'select'choices applied, and any'reconcile'tolerances and counts). Measurement-level moment searches also record the exact resolved moment and paired error columns and their native/canonical units inper_signal['moment_emu']['moment_source'](inside eachper_sweepentry for batches). This records detection choices, not a complete replay manifest: retain the input files and external preprocessing, row selections, repeat aggregation and sample facts.- Type:
- skipped#
Batch-level
(path, reason)pairs for sweeps that were refused or failed; empty for single-sweep results. An empty candidates table with a populatedskippedis “everything failed”, not “no transitions”. Theirsweep_idvalues are inparams['skipped_sweep_ids'], in the same order.- Type:
- curves#
One
{'x', 'y_smooth', 'dydx', 'd2ydx2'}mapping per searched sweep and signal – the smoothed representations that produced the hits, for auditing a candidate against the curve behind it. Read one withcurve(), which works the same whatever produced the result; the keys do not. A batch fromdetect_transitions_all()keys by(sweep_id, signal), because a path cannot name a sweep: the isothermssplit_isotherms()cuts from one file, andrestrict()slices of one file, all share its path, and keyed by path each sweep overwrote the one before. A single-sweepdetect_transitions()result keys by(measurement_file, signal), andfind_transitions()by("", ""). The curvature is always present, whether or not'kink'was run: it is how a caller checks whether a feature reported as a derivative extremum is really a slope change. When'fisher'ran, the entry also holds'yT'(the smoothed y*T, in the signal’s unit times K) and'dyT_dT'(its derivative, in the signal’s own unit once the Kelvins cancel).- Type:
- chains#
One row per cross-sweep chain (
CHAIN_COLUMNS) oncelink()has run;Nonebefore that. On a filtered result it lists only chains with a surviving candidate, keeping the statistics as computed at link time – the chain statistic is what justified keeping those rows, so recomputing it from the survivors would erase the evidence.- Type:
- all()#
The unfiltered result this one was filtered from (self if unfiltered).
Undoes both filters,
robust()andselect(), and drops their records fromparams. Chain columns and the chain table survive:link()is not a filter, so undoing the filters must not undo it.reconcile()is dropped with them, columns and record: it is not a filter either, but it describes the selected view, and without the selection there is nothing it could mean.- Return type:
- curve(sweep_id=0, signal=None)#
The smoothed curves one sweep’s candidates were found in.
Why this exists: auditing a candidate means looking at the curve behind it – is a derivative extremum really a slope change, where does the smoothing put the peak – and
curvesis keyed differently by each producer (see the class docstring). A batch cannot key by path, because sweeps cut from one file share it, so a lookup that works on one sweep breaks on a family. This accessor is the one spelling that works on either, and on every filtered or linked view of them: a candidate row’s ownsweep_idandsignalalways address its curve,result.curve(row.sweep_id, row.signal).- Parameters:
sweep_id (
int) – The sweep, as in thesweep_idcolumn. In a batch it is the input position given todetect_transitions_all(). A single-sweep result holds one sweep,0(the default).signal (
str|None) – The searched signal ('chi_real','moment_emu', …).None(the default) takes the sweep’s only signal. It is refused when the sweep has several (signal='all'), because picking one would be picking χ′ or χ″ for you.
- Return type:
- Returns:
dict– A new dict holding'x','y_smooth','dydx'and'd2ydx2', plus'yT'and'dyT_dT'when'fisher'ran. The arrays are the stored ones, not copies.- Raises:
CurveInputError – If
sweep_idis not an integer; if no sweep has that id – naming the ids that do, and saying so when the batch skipped that sweep, with its reason; ifsignalis not among the sweep’s signals; or ifsignal=Noneand the sweep has more than one.
- link(*, t_tol_k=None, h_tol_t=None, by=('signal', 'method', 'sign'))#
Link candidates into chains across a family of sweeps.
Why this exists: a weak phase boundary can recur in every sweep of a family, at a position that varies smoothly with the fixed coordinate, while its per-sweep
significancesits below any threshold worth publishing. Noise candidates land at unrelated positions instead. Recurrence is the physically meaningful robustness signal, and nothing in a per-sweep result records it.Each chain carries
chain_significance=sum(significance) / sqrt(n). This Stouffer-like combination is a diagnostic: its non-negative input ratios are not centred z-scores. Constant positive inputs grow as sqrt(n), including chance chains; neither this score nor chain length establishes a real boundary or a false-alarm probability. Record the linking tolerances and gates; see_stouffer().The linking itself is deterministic (TR-1): within each group of
bycolumns plusswept_axis, seeds are taken in descendingsignificance(ties broken by family value then location), and each seed walks to the adjacent sweep upward and then downward, taking the nearest unclaimed candidate within tolerance and stopping at the first sweep that offers none. The ordered set of sweeps is the sorted distinct family values among all candidates on that swept axis – so a sweep that fired detections but none in this group counts as a gap and ends the chain, rather than being stepped over silently. Every candidate belongs to exactly one chain; a candidate that links to nothing is a chain of one.This is a description, not a filter: nothing is dropped, and gating on the result is
robust()’s job (min_chain_significance=,min_chain_n=). Linking always works from the full detection and re-applies anyrobust()thresholds and then anyselect()afterwards, so linking commutes with both: a selected candidate keeps the chain it has when the whole detection is linked. A recordedreconcile()is recomputed after those.- Parameters:
t_tol_k (
float|None) – How far a T-swept candidate’s temperature may move between adjacent sweeps and still be the same boundary, in K. Required when any candidate was swept along T.h_tol_t (
float|None) – The same for H-swept candidates, in Tesla.by (
Sequence[str]) – Candidate columns that must match within a chain, on top ofswept_axis. DefaultDEFAULT_LINK_BY.
- Return type:
- Returns:
TransitionResult– A new result (DM-1) whose candidates carrychain_id,chain_nandchain_significance, with the per-chain table onchains(CHAIN_COLUMNS) and the settings inparams['link'].- Raises:
ValueError – If the candidates are not (T, H)-coordinated; if the tolerance for a swept axis that is present was not given, or is not positive; or if
bynames a column the table does not have.
- provenance()#
Candidates joined with each method’s name and citations.
The bibliography lives once, in
METHODS; this is the convenience join for a report or a paper’s methods section.- Return type:
- reconcile(*, t_tol_k, h_tol_t)#
Say how far each family’s points sit from the other family’s boundary.
Why this exists: a campaign usually traces one phase boundary two ways – temperature scans at held fields give
T_b(H), isotherms at held temperatures giveH_b(T)– and nothing per sweep says whether the two agree. They need not: the criteria differ (a cusp in M(T) against a step in M(H)), demagnetisation and thermal lag act along different axes, and a family can pick up a feature that is not the boundary at all.reconcilemeasures the disagreement, point by point, in both units and in units of the combined uncertainty.This is a description, not a filter, in the same sense as
link(): it adds columns and a record and drops nothing. Whether a disagreement matters is your call, stated as the two tolerances;cross_concordantapplies them, and nothing acts on it.Both families must already be down to one point per sweep: it requires a
select()on both axes. The boundaries are then drawn from the current view – afterrobust()and both selections – as piecewise-linear interpolants:the T-swept points
(T_N, H_0), sorted by held field, giveT_b(H);the H-swept points
(T_0, H_c), sorted by held temperature, giveH_b(T).
Each H-swept point gets
cross_residual_K = T_0 - T_b(H_c), and each T-swept pointcross_residual_T = H_0 - H_b(T_N): positive means the point lies at higher temperature, or higher field, than the other family’s boundary there. Each residual is NaN on the other axis’s rows.Uncertainty. Take an H-swept point (the T-swept case is the mirror image, with T and H exchanged). To first order, with the sweeps independent, the residual
r = T_0 - T_b(H_c)has variance:sigma_r**2 = sigma_Tb(H_c)**2 + (dT_b/dH)**2 * sigma_Hc**2 + sigma_T0**2
sigma_Tb(H_c)is the T family’s error at the point: the two bracketing nodes’T_err_Kinterpolated linearly, with the same weights as the boundary itself. That is exact at a node and, in between, larger than the quadrature sumsqrt((1-w)^2 s_k^2 + w^2 s_{k+1}^2)that independent node errors would give (by up to sqrt(2) at mid-segment). The larger one is used on purpose: the chord between two sweeps also carries the boundary’s curvature, which no node error describes, so the quadrature sum would be the optimistic choice.dT_b/dHis the slope of the segment containingH_c(on an interior node, the segment above it) andsigma_Hcis the point’s ownH_err_T. Its location error moves it along the boundary, which shiftsT_bby the slope times that error.sigma_T0, the error of the held coordinate, is taken as zero. The row does carryT_span_K, the range of the held temperature over the sweep, but a range is not a standard error. Turning it into one needs an assumption about where in the sweep the crossing happened (uniformly anywhere givesspan/sqrt(12)) that the detection has no evidence for, and every other consumer of the held coordinate –link(),select(), the maps – treats it as exact. The span stays on the row to compare with the residual by eye; it is bounded by the scan-classification tolerances (SCAN_T_TOL_K,SCAN_H_TOL_OE) wheneverdetect_transitions()accepted the sweep as held.
cross_residual_sigmais the residual divided bysigma_r. Wheresigma_ris zero or not finite it is NaN, never infinite. The location errors it rests on are floored at the grid spacing and somewhat optimistic (seefind_transitions()), so read it as a scale, not a calibrated z-score.Coverage. A point is covered only if the other family has at least two points and spans it: an H-swept point’s
H_cmust lie within the T family’s range of held fields (inclusive), and a T-swept point’sT_Nwithin the H family’s range of held temperatures. An uncovered point hascross_covered = Falseand NaN residuals and sigma. The boundary is never extrapolated: beyond the last sweep there is no measurement of it to disagree with.Composition. The columns depend on the selected view, so the call is recorded and recomputed, not carried.
robust(),select()andlink()all rebuild from the full detection and re-apply a recorded reconcile last, after their own work. A looser threshold that restores a point therefore also restores its residual, and moves the boundaries it takes part in.all()drops it, because it undoes the selections it depends on.- Parameters:
- Return type:
- Returns:
TransitionResult– A new result (DM-1), with no candidate dropped, whose candidates carry five more columns:cross_residual_K(float, K) on H-swept rows, NaN elsewhere;cross_residual_T(float, T) on T-swept rows, NaN elsewhere;cross_residual_sigma(float), the row’s residual oversigma_r;cross_covered(bool);cross_concordant(pandas nullableboolean):|residual| <= toleranceon covered rows and<NA>on uncovered ones, where agreement is undefined rather than false.
params['reconcile']recordst_tol_kandh_tol_tand, per swept axis ('T','H'), the residual column andn_points,n_coveredandn_concordantin this view.- Raises:
ValueError – If
params['select']does not hold both'T'and'H'; if a tolerance isNone, not a number, or not positive and finite; or if two selections on one axis share a held value within that axis’s scan tolerance (SCAN_H_TOL_OEfor the field of T-scans,SCAN_T_TOL_Kfor the temperature of isotherms), listing theirsweep_idvalues – a boundary through two locations at one held value would be a guess.
- robust(min_significance=5.0, *, min_n_methods=None, min_sweep_range_over_noise=None, min_chain_significance=None, min_chain_n=None, exclude_edge=True, min_smoothing_n=None, min_smoothing_persistence=None, min_smoothing_sign_consistency=None, max_smoothing_spread_k=None, max_smoothing_spread_t=None, require_smoothing_interval_overlap=None)#
Filter to the candidates worth publishing; thresholds are recorded.
Always filters from the FULL underlying detection (not from a previous
robust()view), so loosening after tightening works. The thresholds land inparams['robust']– they are provenance that belongs in a figure legend or a methods section, andcalamari.plot.overlay_transitions()prints them.min_significancedefaults toDEFAULT_MIN_SIGNIFICANCE– a diagnostic screening convention, see there for what it does and does not mean. The other thresholds have no defaults: they are physics-interest judgements.exclude_edgedrops candidates supported only by a terminal smoothing window, where the Savitzky-Golay derivative artefact is largest.min_chain_significanceandmin_chain_ngate on the cross-sweep chain a candidate belongs to (seelink()), and are the way to keep a boundary that is weak in every sweep but present in all of them: threshold the combined statistic, not the per-sweep one. They require a linked result – gating on a chain that was never computed would silently keep everything.Sensitivity gates require
scan.reference(window). Each is opt-in:min_smoothing_ncounts qualified distinct representations;min_smoothing_persistenceis their fraction of resolved windows;min_smoothing_sign_consistencyis their modal polarity fraction.max_smoothing_spread_k/max_smoothing_spread_tbound the qualified location range on T / H sweeps respectively, in K / Tesla.require_smoothing_interval_overlap=Truerequires a common intersection of all qualified coordinate ± conditional-error intervals. This is a sensitivity description, not a joint confidence test. Empty qualified sets and unassessed tracks never pass an active sensitivity gate. No sensitivity threshold has a universal default. Consultsensitivity_auditfor rejected candidates and reasons.A recorded
select()is re-applied after the thresholds, to the candidates that pass them, sorobust()andselect()commute: whichever order they are called in, the thresholds decide which candidates exist and the selection then picks among those. A recordedreconcile()is recomputed last, on the new view.- Raises:
ValueError – If a requested threshold names a statistic that is NaN on every row – silently dropping everything (NaN fails any comparison) would be indistinguishable from “nothing robust”. Or if a chain threshold is requested on a result that
link()has not been run on.- Return type:
- select(*, swept_axis, method, sign, signal=None, t_window_k=None, h_window_t=None)#
Keep one candidate per sweep: one criterion, inside a physical window.
Why this exists: a phase boundary is drawn from one point per sweep, but a sweep usually yields several candidates – a stronger feature elsewhere in the sweep, a derivative flank, a hump that is significant and still not the transition. Which one marks this boundary is a physics judgement: the criterion you cite (
methodandsign) and where you expect the boundary to be (the window).selectmakes that judgement a recorded call instead of a pandas filter in a script, so a figure or a methods section can state it. Likerobust()it is a filter, never applied inside detection (TR-1).Only candidates swept along
swept_axisare touched; the other axis passes through untouched, so a mixed campaign chains:r.select(swept_axis="T", method="peak", sign="max", t_window_k=(5, 12)).select( swept_axis="H", method="derivative", sign="rise", h_window_t=(1, 4))
On that axis, each sweep (
sweep_id) keeps at most one candidate: among those with the given signal,methodandsignwhose location lies inside the window (inclusive), the one with the highestsignificance, ties broken by location ascending and then bycandidate_id– deterministic, whatever the row order. Every other candidate on that axis is dropped.methodmatches the candidate’s ownmethodcolumn, the criterion that supplied its coordinate: a cusp whose derivative flanks were grouped into it is a'peak'row, and is not offered tomethod='derivative'.What it does not do: judge whether the chosen candidate is real. The best candidate inside a window can be noise, and
selectwill keep it. Compose withrobust()for that.Composition.
selectworks on the current view, so afterrobust()it picks among the candidates that pass. The choice is recorded and re-applied, not carried:robust()andlink()both re-apply it after their own work, so the order of the three calls does not matter – thresholds decide which candidates exist, then the selection picks among them. Selecting the same axis again replaces the earlier choice for that axis (working, likerobust(), from the unselected view, so a window can be widened).all()undoes it along withrobust(). A recordedreconcile(), which needs a selection on both axes, is recomputed on the new selection.detectionskeep the rows of surviving candidates, andchainsthe chains with a surviving member, statistics as at link time.- Parameters:
swept_axis (
str) – Which candidates to select among: those from temperature sweeps or those from field sweeps.method (
str) – The criterion, aMETHODSkey. Required, with no default: letting it vary from sweep to sweep would interleave systematically different criteria along one boundary – the failureCRITERION_PRIORITYexists to prevent.sign (
str) – The extremum, in that method’s vocabulary (peak'max'/'min', derivative and onset'rise'/'fall', kink'up'/'down', fisher'max'/'min'of d(yT)/dT). Required for the same reason.signal (
str|None) – The channel ('chi_real','chi_imag','moment_emu').Nonerequires the candidates on this axis to come from exactly one signal, and raises naming them otherwise.t_window_k (
(float,float)orcollections.abc.Callable, optional) – The window forswept_axis='T', onT_K, in Kelvin.h_window_t (
(float,float)orcollections.abc.Callable, optional) – The window forswept_axis='H', onH_T, in Tesla – the candidates’ unit, not the Oersted ofdetect_transitions()’h_window_oe, which bounds the measurement’s own field column. Only the swept axis’s window is accepted; the other raises (DM-2: a keyword means one quantity). A window is an inclusive(lo, hi)with finitelo < hi, or a callablef(fixed_value) -> (lo, hi)so it can follow a boundary that moves across the family: it is called once per sweep with the sweep’s fixed coordinate,H_T(Tesla) for a T-swept sweep andT_K(Kelvin) for an H-swept one.None(default) searches the whole sweep.
- Return type:
- Returns:
TransitionResult– A new result (DM-1).params['select'][swept_axis]recordsmethod,sign,signal(as resolved),window(the pair, a callable’s name, orNone),windows(each sweep’s resolved window, bysweep_id) andempty_sweeps: thesweep_idof every sweep with candidates on this axis in the full detection but none kept by this selection – nothing in its window, or everything there removed byrobust(). It is never dropped silently. A sweep that produced no candidate on this axis at all is not in the record, since there is nothing to select from;params['per_sweep']andparams['skipped_sweep_ids']of a batch account for those.params['select']is keyed by axis, so a T selection and an H selection are both kept.- Raises:
TypeError – If
methodorsignis not given.ValueError – If the candidates carry no
swept_axis/sweep_id(an array-level result); ifswept_axisis not'T'or'H', or no candidate was swept along it; ifmethodorsignisNoneor not in the vocabulary; ifsignalis ambiguous or absent; if the other axis’s window is given; or if a window, or a callable’s answer for some sweep, is malformed.
- property sensitivity_audit: DataFrame#
Full reference candidates, assessment, sensitivity verdict and current inclusion.
Recomputed from the full detection, so rejected and unassessed rows remain exportable with
to_csvorto_jsonafter any filtering or selection.sensitivity_passis nullable when no gate applies or assessment is unavailable;retaineddescribes the final view including other gates and selection. The complete recipe isparams['smoothing']plusparams['robust'].