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: object

Detected transition candidates plus the evidence and the recipe.

candidates#

One row per grouped feature (CANDIDATE_COLUMNS). The current – possibly robust()-filtered and select()-ed – view, carrying the cross_* columns once reconcile() has run.

Type:

pandas.DataFrame

detections#

One row per raw detector hit (DETECTION_COLUMNS), linked by candidate_id; this is where “the cusp and the steepest slope were 0.3 K apart” stays visible after grouping. Filtered alongside candidates: a detection survives iff its candidate does.

Type:

pandas.DataFrame

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 in per_signal['moment_emu']['moment_source'] (inside each per_sweep entry 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:

dict

skipped#

Batch-level (path, reason) pairs for sweeps that were refused or failed; empty for single-sweep results. An empty candidates table with a populated skipped is “everything failed”, not “no transitions”. Their sweep_id values are in params['skipped_sweep_ids'], in the same order.

Type:

tuple

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 with curve(), which works the same whatever produced the result; the keys do not. A batch from detect_transitions_all() keys by (sweep_id, signal), because a path cannot name a sweep: the isotherms split_isotherms() cuts from one file, and restrict() slices of one file, all share its path, and keyed by path each sweep overwrote the one before. A single-sweep detect_transitions() result keys by (measurement_file, signal), and find_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:

dict

chains#

One row per cross-sweep chain (CHAIN_COLUMNS) once link() has run; None before 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:

pandas.DataFrame or None

all()#

The unfiltered result this one was filtered from (self if unfiltered).

Undoes both filters, robust() and select(), and drops their records from params. 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:

TransitionResult

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 curves is 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 own sweep_id and signal always address its curve, result.curve(row.sweep_id, row.signal).

Parameters:
  • sweep_id (int) – The sweep, as in the sweep_id column. In a batch it is the input position given to detect_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:

dict

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_id is 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; if signal is not among the sweep’s signals; or if signal=None and the sweep has more than one.

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 significance sits 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 by columns plus swept_axis, seeds are taken in descending significance (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 any robust() thresholds and then any select() afterwards, so linking commutes with both: a selected candidate keeps the chain it has when the whole detection is linked. A recorded reconcile() 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 of swept_axis. Default DEFAULT_LINK_BY.

Return type:

TransitionResult

Returns:

TransitionResult – A new result (DM-1) whose candidates carry chain_id, chain_n and chain_significance, with the per-chain table on chains (CHAIN_COLUMNS) and the settings in params['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 by names 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:

DataFrame

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 give H_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. reconcile measures 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_concordant applies 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 – after robust() and both selections – as piecewise-linear interpolants:

  • the T-swept points (T_N, H_0), sorted by held field, give T_b(H);

  • the H-swept points (T_0, H_c), sorted by held temperature, give H_b(T).

Each H-swept point gets cross_residual_K = T_0 - T_b(H_c), and each T-swept point cross_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_K interpolated linearly, with the same weights as the boundary itself. That is exact at a node and, in between, larger than the quadrature sum sqrt((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/dH is the slope of the segment containing H_c (on an interior node, the segment above it) and sigma_Hc is the point’s own H_err_T. Its location error moves it along the boundary, which shifts T_b by the slope times that error.

  • sigma_T0, the error of the held coordinate, is taken as zero. The row does carry T_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 gives span/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) whenever detect_transitions() accepted the sweep as held.

cross_residual_sigma is the residual divided by sigma_r. Where sigma_r is zero or not finite it is NaN, never infinite. The location errors it rests on are floored at the grid spacing and somewhat optimistic (see find_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_c must lie within the T family’s range of held fields (inclusive), and a T-swept point’s T_N within the H family’s range of held temperatures. An uncovered point has cross_covered = False and 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() and link() 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:
  • t_tol_k (float) – Largest |cross_residual_K| still called concordant, in K. Required, positive and finite, with no default: how far apart two criteria may sit and still mark one boundary is physics only you can supply, as for link().

  • h_tol_t (float) – The same for |cross_residual_T|, in Tesla.

Return type:

TransitionResult

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 over sigma_r;

  • cross_covered (bool);

  • cross_concordant (pandas nullable boolean): |residual| <= tolerance on covered rows and <NA> on uncovered ones, where agreement is undefined rather than false.

params['reconcile'] records t_tol_k and h_tol_t and, per swept axis ('T', 'H'), the residual column and n_points, n_covered and n_concordant in this view.

Raises:

ValueError – If params['select'] does not hold both 'T' and 'H'; if a tolerance is None, 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_OE for the field of T-scans, SCAN_T_TOL_K for the temperature of isotherms), listing their sweep_id values – 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 in params['robust'] – they are provenance that belongs in a figure legend or a methods section, and calamari.plot.overlay_transitions() prints them.

min_significance defaults to DEFAULT_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_edge drops candidates supported only by a terminal smoothing window, where the Savitzky-Golay derivative artefact is largest.

min_chain_significance and min_chain_n gate on the cross-sweep chain a candidate belongs to (see link()), 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_n counts qualified distinct representations; min_smoothing_persistence is their fraction of resolved windows; min_smoothing_sign_consistency is their modal polarity fraction. max_smoothing_spread_k / max_smoothing_spread_t bound the qualified location range on T / H sweeps respectively, in K / Tesla. require_smoothing_interval_overlap=True requires 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. Consult sensitivity_audit for rejected candidates and reasons.

A recorded select() is re-applied after the thresholds, to the candidates that pass them, so robust() and select() commute: whichever order they are called in, the thresholds decide which candidates exist and the selection then picks among those. A recorded reconcile() 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:

TransitionResult

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 (method and sign) and where you expect the boundary to be (the window). select makes that judgement a recorded call instead of a pandas filter in a script, so a figure or a methods section can state it. Like robust() it is a filter, never applied inside detection (TR-1).

Only candidates swept along swept_axis are 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, method and sign whose location lies inside the window (inclusive), the one with the highest significance, ties broken by location ascending and then by candidate_id – deterministic, whatever the row order. Every other candidate on that axis is dropped. method matches the candidate’s own method column, the criterion that supplied its coordinate: a cusp whose derivative flanks were grouped into it is a 'peak' row, and is not offered to method='derivative'.

What it does not do: judge whether the chosen candidate is real. The best candidate inside a window can be noise, and select will keep it. Compose with robust() for that.

Composition. select works on the current view, so after robust() it picks among the candidates that pass. The choice is recorded and re-applied, not carried: robust() and link() 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, like robust(), from the unselected view, so a window can be widened). all() undoes it along with robust(). A recorded reconcile(), which needs a selection on both axes, is recomputed on the new selection. detections keep the rows of surviving candidates, and chains the 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, a METHODS key. Required, with no default: letting it vary from sweep to sweep would interleave systematically different criteria along one boundary – the failure CRITERION_PRIORITY exists 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'). None requires the candidates on this axis to come from exactly one signal, and raises naming them otherwise.

  • t_window_k ((float, float) or collections.abc.Callable, optional) – The window for swept_axis='T', on T_K, in Kelvin.

  • h_window_t ((float, float) or collections.abc.Callable, optional) – The window for swept_axis='H', on H_T, in Tesla – the candidates’ unit, not the Oersted of detect_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 finite lo < hi, or a callable f(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 and T_K (Kelvin) for an H-swept one. None (default) searches the whole sweep.

Return type:

TransitionResult

Returns:

TransitionResult – A new result (DM-1). params['select'][swept_axis] records method, sign, signal (as resolved), window (the pair, a callable’s name, or None), windows (each sweep’s resolved window, by sweep_id) and empty_sweeps: the sweep_id of 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 by robust(). 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'] and params['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 method or sign is not given.

  • ValueError – If the candidates carry no swept_axis / sweep_id (an array-level result); if swept_axis is not 'T' or 'H', or no candidate was swept along it; if method or sign is None or not in the vocabulary; if signal is 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_csv or to_json after any filtering or selection. sensitivity_pass is nullable when no gate applies or assessment is unavailable; retained describes the final view including other gates and selection. The complete recipe is params['smoothing'] plus params['robust'].