Asymmetry Logo

Contents

  • Getting started
  • Analysis workflows
  • Reference
  • Background and design
  • API reference
    • Core data structures
    • Project persistence
    • GUI components
    • Input/output
    • Fitting
      • Fit engine
      • TF calibration
      • Models
      • Composite models
      • Parameter trend models
      • Experiment design
      • Knight shift
      • Frequency-domain helpers
      • Superconductivity models
      • Parameters
      • Fit wizards
      • Count-domain fitting
      • Grouped time-domain fitting
      • Joint fitting
    • Fourier analysis
    • Data transforms
    • Negative-muon analysis API (experimental)
  • Contributing
⚠️ Alpha software. Descriptions of µSR data, fitting models, and workflows here may be incomplete or in error — verify the physics against trusted sources.
Asymmetry
  • API reference
  • Fitting
  • Fit wizards
  • View page source

Fit wizards

Single/global automatic merging uses prepare_wizard_dataset() before fit_record and candidate fan-out. Recorded histogram context selects counts before the ratio; unknown and rotated curve observations use independent means. Current reconstruction and numerical reuse identify the same fitted observation. Known histogram Gaussian fits omit undefined ratios and exactly zero propagated variance, carrying the core observation report through worker records, scoring, completion, and rebuilding. Historical scores retain their recorded meaning; compact caches omit residual arrays and current reuse requires the current policy.

Internal spectral diagnostics use prepare_diagnostic_observation(). Uniform input curves retain their samples. Nonuniform captured histogram observations use fixed native bins (factor 1, merge 1) over the actual retained native edge support, after all recorded selections. No Run/recipe-only replay or curve interpolation is inferred. The resulting lightweight owned arrays cross existing process tasks without detector/reference replay buffers.

PeakAnalysis.diagnostic_attribution and SpectrumFingerprint.diagnostic_attribution retain policy, source observation, recipe and actual window/grid. FitResult.spectral_residual_attribution labels a separate fixed count residual view, evaluated with the same model/parameters. Original residual arrays, objective and statistics remain attached to the fit. Absent historical attribution remains None; loading never regenerates it. analyze_dataset_peaks(..., detrend_model=callable) evaluates a trend in percent at the diagnostic times; sampled-only detrend_curve requires the same grid.

Single-spectrum fit-wizard helpers:

class asymmetry.core.fitting.CandidateTemplate(key, title, category, rationale, model, is_current_model_baseline=False)[source]

One curated candidate model considered by the fit wizard.

key
title
category
rationale
model
is_current_model_baseline = False
property parameter_count[source]
property additive_terms[source]
__init__(key, title, category, rationale, model, is_current_model_baseline=False)
class asymmetry.core.fitting.CandidateAssessment(template, fit_result, sample_count, residual_rms, runs_z_score, max_abs_autocorrelation, residual_fft_peak_snr, residual_gate_passed, residual_gate_reasons, bound_hits, fitted_time, fitted_curve, component_curves, repair_attempted=False, stage=2, disqualification_reasons=(), is_null_baseline=False, refinement_delta_chi_squared=0.0, under_converged=False, timing=None, analysis_history=None)[source]

Fit, comparison data, and optional dense display curves for one candidate.

Only recommended and comparable rows carry dense curves. Score-only rows carry empty arrays, avoiding megabyte-scale buffers per assessed model. assessment_with_curves reconstructs any other row from its fitted parameters; _with_dense_curves owns that transition.

template
fit_result
sample_count
residual_rms
runs_z_score
max_abs_autocorrelation
residual_fft_peak_snr
residual_gate_passed
residual_gate_reasons
bound_hits
fitted_time
fitted_curve
component_curves
repair_attempted = False
stage = 2

Screening stage that produced this assessment — 1 = Stage-1 family representative (cheap first-pass fit), 2 = full assessment.

disqualification_reasons = ()

Targeted-disqualifier reasons that make this candidate unfit to recommend even when it wins by metric (frequency at the resolution floor / pinned at a bound, oscillation amplitude consistent with zero). Empty when the candidate is eligible. Additive — old payloads deserialize to ().

is_null_baseline = False

True for the flat/plain-exponential null baselines fitted unconditionally as a “no significant structure” reference; these never win a normal recommendation and are excluded from the ranked candidate pool.

refinement_delta_chi_squared = 0.0

χ² this candidate gained when re-fitted with a deeper seed ladder (old χ² − new χ², so positive means the deeper search found a better minimum). 0.0 when no refinement pass ran for this candidate. Additive — old payloads deserialize to 0.0.

under_converged = False

True when the refinement pass moved this candidate’s χ² by more than _UNDER_CONVERGENCE_CHI2_TOLERANCE. Its reported score is the deeper one, so the flag is not a warning that the number is wrong — it is the measured statement that this candidate’s ranking is search-limited, and that any family compared against it at the shallower budget was too.

timing = None

How long the fit that produced this row took (asymmetry.core.fitting.fit_wizard._execute_assessment_task). None on a row restored from a cache: it is never persisted, so a past run’s time is never recorded twice (docs/plans/measured-fit-times.md, D1).

analysis_history = None
property residual_diagnostics_available[source]

Whether every recorded residual diagnostic is a finite value.

diagnostic_summary()[source]

Format available residual diagnostics and the core observation report.

property is_disqualified[source]
property parameter_count[source]
property additive_terms[source]
property model_parameter_count[source]

Every parameter the model carries, pinned ones included.

A tie-break below parameter_count, not a replacement for it: the information criteria rightly count only free parameters, but two candidates can now reach exactly the same k by different routes. A zero-field record pins B_L at 0, at which point LongitudinalFieldKT + Constant fits identically to StaticGKT_ZF + Constant on the same three free parameters — the same function reached through a longitudinal machinery it does not use. Prefer the model that never carried it.

property criteria[source]
property aic[source]
property aicc[source]
property bic[source]
unavailable_reason(metric)[source]
metric_value(metric)[source]
property is_successful[source]
__init__(template, fit_result, sample_count, residual_rms, runs_z_score, max_abs_autocorrelation, residual_fft_peak_snr, residual_gate_passed, residual_gate_reasons, bound_hits, fitted_time, fitted_curve, component_curves, repair_attempted=False, stage=2, disqualification_reasons=(), is_null_baseline=False, refinement_delta_chi_squared=0.0, under_converged=False, timing=None, analysis_history=None)
class asymmetry.core.fitting.FitWizardRecommendation(fingerprint, templates, assessments, metric, recommended_key, comparable_keys, summary, peak_analysis=None, multiplet_matches=(), family_reports=(), confidence=ConfidenceTier.NONE, verdict=RecommendationVerdict.NONE, caveat='', scope_note='', rebin_factor=1, analysed_points=0, build_signature='', computation_revision=None)[source]

Full fit-wizard analysis payload plus the current recommendation.

fingerprint
templates
assessments
metric
recommended_key
comparable_keys
summary
peak_analysis = None
multiplet_matches = ()
family_reports = ()
confidence = 'none'

Confidence tier of recommended_key (High = gates passed, Medium = metric winner with structured residuals, None = no recommendation). Additive — old payloads default to NONE.

verdict = 'none'

Whether the recommendation describes real structure or the data are consistent with a null baseline. Additive — old payloads default to NONE (they predate the null-baseline test).

caveat = ''

Human-readable caveat carried when confidence is Medium (the residual gate reasons for the recommended template) or when the null-baseline verdict fires. Empty for a clean High recommendation. GUI-facing.

scope_note = ''

Human-readable note on how the candidate scope was resolved (run geometry, near-zero-field widening, a fluorine sample-name prior — see wizard_scope.ScopeResolution.inference_note). Empty when no scope was resolved (scope=None in build_fit_wizard_recommendation()). Additive — old payloads default to "". GUI-facing.

rebin_factor = 1

Observation merging affects fits; detection uses the full record.

analysed_points = 0

Fitted points for this recommendation, including any analysis rebinning. Comparisons require the same resolution; zero denotes an unknown count.

build_signature = ''

Scope and declared frequencies encoded by single_fit_build_signature. Table role distinguishes full analyses from explicit/completed score tables.

computation_revision = None
property recommended_assessment[source]
assessment_for_key(key)[source]
sorted_assessments(metric=None)[source]
__init__(fingerprint, templates, assessments, metric, recommended_key, comparable_keys, summary, peak_analysis=None, multiplet_matches=(), family_reports=(), confidence=ConfidenceTier.NONE, verdict=RecommendationVerdict.NONE, caveat='', scope_note='', rebin_factor=1, analysed_points=0, build_signature='', computation_revision=None)
asymmetry.core.fitting.build_fit_wizard_recommendation(dataset, current_model=None, *, metric=SelectionMetric.AICC, scope=None, fit_times=FitTimeEstimates(seconds_per_run={}), user_frequencies_mhz=None, max_workers=None, executor=None, warm_start_by_template=None, progress_callback=None, cancel_callback=None, refine_top_candidates=3, instrumentation=None, stage_callback=None, diagnostic=None)[source]

Analyze one asymmetry spectrum and recommend a fit candidate.

Tiered screening: every in-scope candidate family gets its cheap Stage-1 representative fitted (fingerprint hints only prioritise — they no longer exclude); families that pass the residual gates, score within _STAGE1_PROMOTE_DELTA of the best, or are named by a multiplet pattern match expand to their full Stage-2 portfolios. scope restricts the families physically (None screens the default superset), and fit_times judges which models its slow switch leaves out; user_frequencies_mhz adds trusted peak seeds — blind runs get the same seeds from the matched-apodisation damped-line scan when the data carry a heavily damped line (see detect_damped_lines()); max_workers=1 gives a deterministic serial path. Note that max_workers bounds fits in flight, not CPU: the vortex-lattice candidates reach a multi-threaded BLAS from inside a single fit, so a max_workers=1 run can still saturate the machine — see asymmetry.core.fitting.process_pool for the measurement and the environment knob. cancel_callback is polled between and inside fits when running serially or on the thread-pool fallback (engine in-fit abort); when the resolved worker count allows a shared process pool, cancellation instead takes effect only between fits (a cancel_callback cannot cross a process boundary) — either way, cancellation raises FitCancelledError.

executor supplies a caller-owned process pool. Given one, this build opens no pool of its own and every fan-out — Stage 1, Stage 2, the null baselines and refinement — submits to it; the pool is never shut down or terminated here, not even on cancellation, because its lifetime belongs to the caller. That is how a series analysis gives one pool to many builds, so one run’s fan-out can use workers another run’s serial stage leaves idle and the per-worker import of the fitting package is paid once for the series rather than twice per run. Without an executor the build opens one pool and shares it across the same four fan-outs, shutting it down on the way out (terminating it on cancellation).

warm_start_by_template supplies already-fitted values per template key — the same models fitted on a neighbouring run of a series, which a series analysis has by the time it reaches this run. They are handed to the Stage-1 and Stage-2 assessments as an additional first variant, ahead of the seed ladder and never in place of it (see asymmetry.core.fitting.fit_wizard._assess_candidate_template), so the answer for a template can only improve or stay the same: the assessment keeps the best attempt, and one more starting point cannot make that worse. A key naming no screened template is simply unused.

refine_top_candidates re-fits that many top-ranked candidates with the full seed ladder and records the χ² gained (asymmetry.core.fitting.fit_wizard.CandidateAssessment.refinement_delta_chi_squared / under_converged); 0 disables the pass.

instrumentation receives the standard timing block and stage_callback the structured per-stage progress events described in asymmetry.core.fitting.wizard_timing, so a headless caller can tell a slow run from a stalled one without inspecting the process tree. Every non-trivial segment of the build is timed, not only the fitting fan-outs: single_fit.detection (Hann pass + damped-line scan + fingerprint), single_fit.stage1, single_fit.residual_detection (peak pass B), single_fit.pattern_match (multiplet lines + envelope banks), single_fit.stage2 and single_fit.refinement. The middle three were once invisible and together accounted for half the wall time of a 10⁵-point run.

On a record above _FIT_SAMPLE_BUDGET points every candidate is fitted on a prepared observation (analysis_rebin_factor()); peak detection and the fingerprint still run on the full record. The result records the factor and the point count it used in asymmetry.core.fitting.fit_wizard.FitWizardRecommendation.rebin_factor and analysed_points, and every information criterion in it refers to that analysed record.

asymmetry.core.fitting.rerank_fit_wizard_recommendation(recommendation, metric)[source]

Apply the recommendation policy against the (already fitted) assessments.

Policy (gates classify, they no longer veto):

  • Recommend the best-by-metric successful, non-null, non-disqualified candidate. Targeted disqualifiers (frequency at the resolution floor / pinned at a bound, zero-consistent oscillation amplitude) drop a candidate to the next survivor.

  • Confidence tier: High when the winner’s residuals pass every gate, Medium when it is the clear metric winner but leaves structured residuals (its gate reasons ride along as a caveat).

  • Null-baseline verdict: if the winner does not beat the better strictly-simpler null baseline by _NULL_BASELINE_MIN_DELTA_AICC, the verdict becomes NO_SIGNIFICANT_STRUCTURE and the recommendation points at the winning null (fixes pure-noise over-confidence). Tolerates missing nulls (old payloads, the explicit-template path): the test is skipped.

Global fit-wizard helpers:

class asymmetry.core.fitting.GlobalParameterRecommendation(name, recommended_role, global_score, local_score, score_delta, rationale)[source]

Recommended role for one parameter in a global fit.

name
recommended_role
global_score
local_score
score_delta
rationale
__init__(name, recommended_role, global_score, local_score, score_delta, rationale)
class asymmetry.core.fitting.GlobalCandidateAssessment(template, fit_results_by_run, global_parameters, global_param_names, local_param_names, fixed_param_names, parameter_recommendations, run_diagnostics, series_warnings, sample_count, fitted_curves_by_run, component_curves_by_run, prescreen_only=False, assessment_key=None, rung=None, analysis_history=None)[source]

Global-fit assessment with complete diagnostics and optional display curves.

Search-internal assessments have empty curve dicts and no residual buffers; diagnostics, criteria, gates, and warnings are computed before buffers drop. Every exposed leaderboard, phase, and pre-screen assessment has curves and matching residuals for each fitted run. _with_dense_curves materialises them; _assemble_assignment_assessment(dense_curves=...) selects the state.

A sharing-ladder rung carries its fitted model in template. All parameter names, curves, apply, and serialisation use that model. Shared amplitudes appear in global_param_names; exemptions retains runs with local values.

template
fit_results_by_run
global_parameters
global_param_names
local_param_names
fixed_param_names
parameter_recommendations
run_diagnostics
series_warnings
sample_count
fitted_curves_by_run
component_curves_by_run
prescreen_only = False
assessment_key = None
rung = None

Set on a rung of a sharing ladder; None on a role-search node and a screening row.

analysis_history = None
property selection_key[source]
property exempt_runs[source]

Runs that keep their own amplitude are left out of the coupled series on apply.

Empty for a role-search node and a screening row, which exempt nothing.

property exemptions[source]

Shared parameter → the runs that keep a value of their own for it (plan D12, D17).

property parameter_count[source]
property additive_terms[source]
property criteria[source]
property aic[source]
property aicc[source]
property bic[source]
unavailable_reason(metric)[source]
metric_value(metric)[source]
property is_successful[source]
property residual_gate_passed[source]

Every available run diagnostic clears its existing threshold.

property residual_diagnostics_available[source]

Unavailable residual measurements cannot establish model evidence.

property applied_roles[source]

The Global/Local/Fixed role each parameter gets when this candidate is applied.

The role search’s recommendations override the assignment’s names; a fixed parameter stays Fixed whatever was recommended.

__init__(template, fit_results_by_run, global_parameters, global_param_names, local_param_names, fixed_param_names, parameter_recommendations, run_diagnostics, series_warnings, sample_count, fitted_curves_by_run, component_curves_by_run, prescreen_only=False, assessment_key=None, rung=None, analysis_history=None)
class asymmetry.core.fitting.GlobalFitWizardRecommendation(series_axis_key, series_axis_label, mixed_axes_warning, fingerprints_by_run, dataset_order, templates, assessments, metric, recommended_key, comparable_keys, summary, partition_path=None, phase_assessments=<factory>, recommended_partition_k=None, objective=SelectionObjective.TREND, computation_revision=None)[source]

Series-wide and partitioned global-fit answers with their search objective.

recommended_key and comparable_keys select series-wide assessments. partition_path describes contiguous phases; phase_assessments stores each verified (k, segment_index) fit, and recommended_partition_k selects the optimized partition. Screening computes the path without fitting phases. Too few runs or no common template leaves the path absent. Changing between TREND ladders and STATISTICAL role searches requires optimization.

series_axis_key
series_axis_label
mixed_axes_warning
fingerprints_by_run
dataset_order
templates
assessments
metric
recommended_key
comparable_keys
summary
partition_path = None
phase_assessments
recommended_partition_k = None
objective = 'trend'
computation_revision = None
ranking_key(metric)[source]

Display order, smaller first: ladder rungs by trend, anything else by metric.

Under the trend objective the rungs lead in trend_sort_key()’s order — the recommended one first — and screening rows follow by the criterion. Under the statistical one every row is ordered by the criterion.

property recommended_assessment[source]
property recommended_partition[source]

The optimised partition solution, when one was optimised.

phase_assessment(segment_index)[source]

The recommended assessment of one phase of the optimised partition.

None for an excluded end stub, which never receives a coupled fit.

assessment_for_key(key)[source]
assessments_for_template_key(template_key)[source]
sorted_assessments(metric=None)[source]
sorted_prescreen_assessments(metric=None)[source]
optimized_assessments()[source]
sorted_optimized_assessments(metric=None)[source]
sorted_rungs(metric=None)[source]

The sharing ladders’ rungs in display order: what Compare lists under the trend objective.

optimization_status_for_key(key)[source]
__init__(series_axis_key, series_axis_label, mixed_axes_warning, fingerprints_by_run, dataset_order, templates, assessments, metric, recommended_key, comparable_keys, summary, partition_path=None, phase_assessments=<factory>, recommended_partition_k=None, objective=SelectionObjective.TREND, computation_revision=None)
class asymmetry.core.fitting.SelectionObjective(*values)[source]

What the wizard’s recommendation optimises (plan D1).

TREND = 'trend'

The fit whose local parameters trend best among those that fit adequately.

STATISTICAL = 'statistical'

The best information criterion over the separable role search.

class asymmetry.core.fitting.global_search.trend_objective.CandidateRung(exempt_runs, series_cost, run_costs, trend, hard_to_justify, pass_disagreements, preselected, amplitude_unshareable_runs, all_local_chi2r)[source]

What being a rung of a sharing ladder adds to a wizard candidate.

preselected

Whether this is the rung its template’s ladder pre-selects (plan D9).

amplitude_unshareable_runs

The end block the template’s ladder could not share the amplitudes through (plan D12). A finding of the whole climb, so every rung of one ladder carries the same runs; empty when the climb found none.

all_local_chi2r

The template’s all-local series χ²ᵣ — what the band compares (plan D9). The same on every rung of one ladder.

classmethod from_ladder_rung(rung, *, preselected, amplitude_unshareable_runs, all_local_chi2r)[source]
to_payload()[source]
classmethod from_payload(payload)[source]
__init__(exempt_runs, series_cost, run_costs, trend, hard_to_justify, pass_disagreements, preselected, amplitude_unshareable_runs, all_local_chi2r)
property offending_runs[source]

Non-exempt runs whose own cost is over the tolerance, in axis order.

property within_tolerance[source]

The series and every non-exempt run cost no more than the tolerance (plan D9).

exempt_runs

Runs that keep their own value of the shared amplitudes (plan D12).

series_cost

Rise of the series χ²ᵣ over the all-local fits, in units of √(2/ν).

run_costs

The same for each run, exempt runs included.

trend

Trend quality of every parameter that is still local.

hard_to_justify

Shared rates and frequencies whose own component’s amplitude is local (plan D3).

pass_disagreements

Local parameters whose acquisition passes disagree, with the passes (plan D15).

asymmetry.core.fitting.build_global_fit_wizard_recommendation(datasets, current_model=None, *, current_parameter_types=None, current_values=None, parameter_bounds=None, single_fit_recommendations_by_run=None, metric=SelectionMetric.AICC, progress_callback=None, instrumentation=None, selected_template_keys=None, scope=None, fit_times=FitTimeEstimates(seconds_per_run={}), user_frequencies_mhz=None, search_engine=None, effort_tier=EffortTier.EXHAUSTIVE, portfolio=None, cancel_callback=None, partition_path=None, partition_k=None, objective=SelectionObjective.TREND)[source]

Analyze one ordered dataset series and recommend a global-fit candidate.

objective is what the recommendation is for (plan D1). TREND, the default, climbs a sharing ladder for every template that fits about as well as the best one and recommends the rung whose local parameters trend best among those that fit adequately (asymmetry.core.fitting.global_search.trend_search); the engine and effort arguments below do not apply to it. STATISTICAL runs the role search they describe and recommends the best metric. One call computes one objective.

portfolio is the candidate set to search, normally the series alphabet a phase-1 call returned together with the single_fit_recommendations_by_run table that covers it; without it the cheap preview portfolio is used and the per-run pre-screen is only taken up when the supplied table happens to cover that.

effort_tier is the user-facing effort slider: LOW, BALANCED, THOROUGH, EXHAUSTIVE (default EXHAUSTIVE). Every tier resolves to the separable role-search engine (see _EFFORT_TIER_SEARCH_ENGINE): the separable search takes the all-local assignment straight from the per-run fits, ranks every sharing pattern with a full-covariance GLS surrogate, and walks backward elimination with one warm coupled fit per step, so it costs O(P) coupled fits per template where the wavefront costs O(2^P) — and it is the honest answer at every tier, not a coarser one. The enum and its payload are retained so a future scope-based quick-look tier can be added without a schema/UI change.

search_engine remains available as a lower-level override for existing callers/tests — when given explicitly it takes precedence over effort_tier for engine selection. "separable" is the default engine; "exhaustive" and "thorough" run the exact bounded wavefront (byte-for-byte the frozen-baseline path, and the harness referee the separable engine is measured against); "low" and "balanced" run the retained non-exhaustive heuristic engines (techniques E/F/G/H and the I/J/K knobs), reachable only through this seam for large-P use and regression coverage — never through effort_tier.

partition_k switches the whole run from one series-wide answer to one answer per phase: solution k of partition_path (the path a screening pass computed and stored on its recommendation) is optimised segment by segment, together with the neighbours tier 3 verifies, and the result carries phase_assessments and a re-scored path instead of a recommended_key. The two arrive together — a k names a row of a specific path — so passing one without the other is a programming error and is refused. With partition_k=None nothing about this function changes.

asymmetry.core.fitting.rerank_global_fit_wizard_recommendation(recommendation, metric)[source]

Reuse existing global-fit assessments and recompute the recommendation.

The recommendation’s own objective decides how: the best trend among the pre-selected ladder rungs, metric breaking ties, or the best metric among the role-search nodes that pass every run’s residual gate.

A partitioned recommendation — one whose recommended_partition_k names an optimised solution — keeps that partition and summarises its transitions instead of the series-wide winner. The partition itself is not re-selected: breaks are scored with BIC whatever ranking metric the user picked (see build_global_fit_wizard_screening_recommendation()), so changing the metric changes which candidate wins within a phase, never where the phases are.

Spectral peak analysis

class asymmetry.core.fitting.peak_detection.PeakAnalysis(peaks, noise_floor, resolution_mhz, nyquist_mhz, detrended, detrend_template_key=None, burg_order=None, burg_hit_boundary=False, damped_lines=None, diagnostic_attribution=None)[source]

The outcome of a peak-detection pass over one spectrum.

peaks is ordered by SNR descending within a detection pass, with any user-declared peaks first and each pass’s block following: an early_fft SNR is measured on a short unwindowed crop against a different noise floor, so it is not comparable with an fft SNR from the whole record. A single pass’s output is therefore plainly SNR-descending; a merged one is blocks of it (see merge_early_peaks() and merge_user_peaks()).

peaks
noise_floor
resolution_mhz
nyquist_mhz
detrended
detrend_template_key = None
burg_order = None
burg_hit_boundary = False
damped_lines = None

Full outcome of the matched-apodisation damped-line scan that produced this analysis’s "damped_scan" peaks — the Δχ² threshold, the trial count and the τ ladder, which the peaks themselves do not carry. None when the scan did not run. Additive — old payloads deserialize to None.

diagnostic_attribution = None
__init__(peaks, noise_floor, resolution_mhz, nyquist_mhz, detrended, detrend_template_key=None, burg_order=None, burg_hit_boundary=False, damped_lines=None, diagnostic_attribution=None)
asymmetry.core.fitting.peak_detection.analyze_dataset_peaks(dataset, *, detrend_curve=None, detrend_template_key=None, detrend_model=None, max_peaks=6, min_snr=2.5, burg_check='auto', damped_pass=True, diagnostic=None, cancel_check=None)[source]

Detect oscillation lines in a time-domain dataset via FFT + Burg check.

The residual (asymmetry − detrend_curve when given, else tail-subtracted) is transformed with a Hann window and 4× zero-padding, then passed to detect_peaks_in_spectrum(). A Burg (all-poles) cross-check may confirm but never add peaks — see burg_check.

A second, matched-apodisation damped-line scan then runs over the record (analyze_damped_scan_peaks()) and its peaks are merged in (merge_damped_scan_peaks()). That pass is what lets the wizard see an oscillation whose lifetime is a small fraction of the record — the case the Hann window structurally deletes — and, unlike the crop ladder it replaced (analyze_early_window_peaks(), kept importable but no longer wired here), it measures the envelope rate instead of inferring it from a crop length.

The two passes are complementary, and neither is a superset of the other. The damped scan deliberately declines a line whose envelope is not fast compared with its own period — a conventional transverse-field precession at, say, 0.69 MHz with λ ≈ 1.8 µs⁻¹ has f/λ ≈ 0.4 and is rejected by asymmetry.core.fitting.damped_line_scan._is_oscillation, which is correct: at that ratio the matched-apodisation rung cannot tell a cosine from the relaxation it rides on. Such a line is the Hann pass’s to find, and it is why the local noise floor next to DC has to be estimated honestly (see asymmetry.core.fitting.peak_detection._running_median).

Parameters:
  • detrend_curve – Optional model curve aligned with dataset.time to subtract before transforming on the same uniform grid (the “residual FFT” path).

  • detrend_model – Model callable evaluated on diagnostic times when count preparation changes the grid; sampled detrend arrays cannot supply those values.

  • diagnostic – Shared owned diagnostic observation prepared for this input.

  • cancel_check – Cooperative cancellation check between numerical passes.

  • detrend_template_key – Provenance label recorded on the analysis when detrend_curve is used.

  • burg_check – "auto" (run when n_points < 512 or two peaks fall within 2·resolution), "always" or "never". The cross-check is scoped to the Hann pass: Burg is known to return a featureless 1/f-like spectrum on a short, heavily damped window, so letting it judge damped-scan peaks would veto exactly the lines that pass exists to find.

  • damped_pass – Set False to run the historical Hann-only detection.

Composite

asymmetry.core.fitting.composite.COMPONENTS

Registry of composite-model components.

asymmetry.core.fitting.composite.placeholder_component_definition(name)[source]

Return a named placeholder for an unregistered (user) component.

Used when a project references a component that is not registered in this session (typically a user function whose plugin is not installed): the model still opens with its original expression — the placeholder evaluates to zero and is flagged missing so fitting can be blocked with a clear message instead of the model being silently dropped. Placeholders are per-instance and are never inserted into COMPONENTS.

Damped line scan

asymmetry.core.fitting.damped_line_scan.detect_damped_lines(time, asymmetry, error, *, max_lines=3, false_rate=0.01, sample_budget=16384, min_snr=5.0, max_candidates=12)[source]

Find heavily damped oscillations in an asymmetry record.

The record is truncated to its statistically informative window (effective_analysis_window()) and scanned over a matched apodisation ladder. Clustered scan peaks are shortlisted, strongest first, and each is verified by a look-elsewhere-corrected Δχ² test; the first candidate to pass is accepted, subtracted from the record, and the ladder is scanned again on the residual, so the next line is looked for in a spectrum the accepted one no longer shapes — neither as a peak nor as a lifted local noise floor. An accepted line also joins the nuisance basis, so a strong line’s leakage cannot manufacture a second one. No time crop is asked of the caller: the ladder replaces it.

When no further line can be accepted, every line is re-fitted with all the others in the nuisance basis (asymmetry.core.fitting.damped_line_scan._polish_lines), and the Δχ², amplitude and phase each one reports come from that fit — on the full informative record, leave-one-out — so two lines’ numbers are comparable and the threshold means the same thing for each. The (f, λ) search itself runs on a short per-candidate record purely for speed (asymmetry.core.fitting.damped_line_scan._verification_record).

asymmetry and error may be on either asymmetry scale; every amplitude in the result is on the scale supplied (percent, by the library’s convention). Lines are returned Δχ²-descending.

class asymmetry.core.fitting.damped_line_scan.DampedLineAnalysis(lines, threshold_delta_chi_squared, n_trials, taus_us, window_end_index, sample_budget, false_rate)[source]

The outcome of a damped-line scan over one record.

lines is ordered by delta_chi_squared descending. Lines are found sequentially (peeling), but the Δχ² each one carries is measured after the last acceptance with all the others in the nuisance basis, so the ordering is a ranking of comparable numbers rather than of the order they were found in.

class asymmetry.core.fitting.damped_line_scan.DampedLine(frequency_mhz, damping_rate_per_us, amplitude_percent, phase_rad, delta_chi_squared, tau_us, snr)[source]

One accepted damped oscillation.

frequency_mhz

Refined line frequency in MHz.

Type:

float

damping_rate_per_us

Refined envelope rate λ in µs⁻¹ (exp(-λt), 1/e lifetime 1/λ).

Type:

float

amplitude_percent

Amplitude A of A·exp(-λt)·cos(2πft + φ) referred to the start of the analysis window, on the scale of the input asymmetry (the library convention is percent), corrected for the bin-averaging attenuation of this module’s own rebinning.

Type:

float

phase_rad

Phase φ in radians, in (-π, π], referred to the same origin.

Type:

float

delta_chi_squared

Weighted χ² improvement from adding this line to a nuisance basis that already contains the slow-decay dictionary and every other accepted line, measured on the full informative record. Leave-one-out and on one common record, so two lines’ values mean the same thing and both can be compared with threshold_delta_chi_squared.

Type:

float

tau_us

Matched apodisation lifetime of the rung that found the line. Note it is an estimate of 1/λ only for an isolated line: inside a cluster the shorter rungs’ local noise floor is lifted by the neighbours, which biases the rung of maximum SNR long.

Type:

float

snr

That rung’s scan SNR (MAD units), for provenance and ranking within the scan; the acceptance decision is delta_chi_squared.

Type:

float

DampedLineAnalysis.threshold_delta_chi_squared

Fit wizard

asymmetry.core.fitting.fit_wizard.MIN_CYCLES_IN_EFFECTIVE_WINDOW

Minimum oscillation cycles inside the SNR-truncated effective window for a fitted frequency to be a supportable claim. Real muSR errors explode with t, so the statistically informative record is often much shorter than the fit window; a free-phase oscillation completing fewer than ~2 cycles there is indistinguishable from a smooth envelope + systematics, however well it scores by AICc (the validation programme’s flat-Ag/Cu-ZF and KT-plus-drift false positives were all of this kind). Generalises the 1/T_full floor in _disqualification_reasons to the window that actually carries information.

asymmetry.core.fitting.fit_wizard.analysis_rebin_factor(dataset, peak_analysis=None, *, field_gauss=None, sample_budget=None)[source]

Value-rebinning factor for the record the wizard’s candidates are fitted on.

Two constraints, and the smaller wins:

  • Cost. n // sample_budget — enough to bring a 10⁵-point record down to the budget. Below the budget the factor is 1 and nothing is rebinned.

  • Bandwidth. ⌊1 / (_FIT_SAMPLES_PER_CYCLE · f_max · dt)⌋, where f_max is the highest frequency anything will be seeded at — the peaks eligible to seed an oscillatory component (asymmetry.core.fitting.fit_wizard._multiplet_seed_peaks: a user, early-window or damped-scan line, or a Hann/residual peak above _MULTIPLET_MIN_SNR), or the Larmor frequency of the applied field when there are none. Rebinning past this point aliases the very line the seeds name, so the cost constraint is not allowed to override it. A sub-threshold residual-FFT peak is not protected: nothing will be seeded at it, and one such peak near the Nyquist frequency would otherwise pin the whole record at full resolution. With no eligible peaks and no field there is nothing to protect and only the cost constraint applies.

For uniform fits dt retains the existing spacing. For nonuniform fits the largest centre separation bounds additional cost packing; it is not an FFT interval or a universal aliasing guarantee.

Never returns less than 1. Peak detection and the fingerprint are NOT rebinned: they are cheap relative to a Stage-2 fit set and they need the full bandwidth to find f_max in the first place.

sample_budget defaults to the module global _FIT_SAMPLE_BUDGET, read at call time rather than bound as a default argument so a test can move it.

asymmetry.core.fitting.fit_wizard.build_fit_wizard_recommendation(dataset, current_model=None, *, metric=SelectionMetric.AICC, scope=None, fit_times=FitTimeEstimates(seconds_per_run={}), user_frequencies_mhz=None, max_workers=None, executor=None, warm_start_by_template=None, progress_callback=None, cancel_callback=None, refine_top_candidates=3, instrumentation=None, stage_callback=None, diagnostic=None)[source]

Analyze one asymmetry spectrum and recommend a fit candidate.

Tiered screening: every in-scope candidate family gets its cheap Stage-1 representative fitted (fingerprint hints only prioritise — they no longer exclude); families that pass the residual gates, score within _STAGE1_PROMOTE_DELTA of the best, or are named by a multiplet pattern match expand to their full Stage-2 portfolios. scope restricts the families physically (None screens the default superset), and fit_times judges which models its slow switch leaves out; user_frequencies_mhz adds trusted peak seeds — blind runs get the same seeds from the matched-apodisation damped-line scan when the data carry a heavily damped line (see detect_damped_lines()); max_workers=1 gives a deterministic serial path. Note that max_workers bounds fits in flight, not CPU: the vortex-lattice candidates reach a multi-threaded BLAS from inside a single fit, so a max_workers=1 run can still saturate the machine — see asymmetry.core.fitting.process_pool for the measurement and the environment knob. cancel_callback is polled between and inside fits when running serially or on the thread-pool fallback (engine in-fit abort); when the resolved worker count allows a shared process pool, cancellation instead takes effect only between fits (a cancel_callback cannot cross a process boundary) — either way, cancellation raises FitCancelledError.

executor supplies a caller-owned process pool. Given one, this build opens no pool of its own and every fan-out — Stage 1, Stage 2, the null baselines and refinement — submits to it; the pool is never shut down or terminated here, not even on cancellation, because its lifetime belongs to the caller. That is how a series analysis gives one pool to many builds, so one run’s fan-out can use workers another run’s serial stage leaves idle and the per-worker import of the fitting package is paid once for the series rather than twice per run. Without an executor the build opens one pool and shares it across the same four fan-outs, shutting it down on the way out (terminating it on cancellation).

warm_start_by_template supplies already-fitted values per template key — the same models fitted on a neighbouring run of a series, which a series analysis has by the time it reaches this run. They are handed to the Stage-1 and Stage-2 assessments as an additional first variant, ahead of the seed ladder and never in place of it (see asymmetry.core.fitting.fit_wizard._assess_candidate_template), so the answer for a template can only improve or stay the same: the assessment keeps the best attempt, and one more starting point cannot make that worse. A key naming no screened template is simply unused.

refine_top_candidates re-fits that many top-ranked candidates with the full seed ladder and records the χ² gained (asymmetry.core.fitting.fit_wizard.CandidateAssessment.refinement_delta_chi_squared / under_converged); 0 disables the pass.

instrumentation receives the standard timing block and stage_callback the structured per-stage progress events described in asymmetry.core.fitting.wizard_timing, so a headless caller can tell a slow run from a stalled one without inspecting the process tree. Every non-trivial segment of the build is timed, not only the fitting fan-outs: single_fit.detection (Hann pass + damped-line scan + fingerprint), single_fit.stage1, single_fit.residual_detection (peak pass B), single_fit.pattern_match (multiplet lines + envelope banks), single_fit.stage2 and single_fit.refinement. The middle three were once invisible and together accounted for half the wall time of a 10⁵-point run.

On a record above _FIT_SAMPLE_BUDGET points every candidate is fitted on a prepared observation (analysis_rebin_factor()); peak detection and the fingerprint still run on the full record. The result records the factor and the point count it used in asymmetry.core.fitting.fit_wizard.FitWizardRecommendation.rebin_factor and analysed_points, and every information criterion in it refers to that analysed record.

asymmetry.core.fitting.fit_wizard.fingerprint_spectrum(dataset, *, peak_analysis=None, diagnostic=None, cancel_check=None)[source]

Extract deterministic features used to shortlist candidate models.

peak_analysis lets a caller that has already run analyze_dataset_peaks() hand the result in. That is not (only) about saving a transform: without it the damped-line candidate carried here and the early_fft peaks that seed the candidates are two independent computations of the same thing, free to disagree once the merge policy drops one of them. Passed in, they are the same peaks by construction.

asymmetry.core.fitting.fit_wizard.single_fit_build_signature(scope, user_frequencies_mhz=None, *, dataset=None, table_role='analysis', time_response=TimeResponse(mode='off', separation_us=0.0))[source]

Encode scope, declared frequencies, and the numerical binning contract.

A missing or different identity cannot qualify a historical recommendation for current screening. The canonical JSON identity survives persistence.

CandidateAssessment.refinement_delta_chi_squared
CandidateAssessment.under_converged
FitWizardRecommendation.rebin_factor
FitWizardRecommendation.analysed_points

Global fit wizard

asymmetry.core.fitting.global_fit_wizard.build_global_fit_wizard_screening_recommendation(datasets, current_model=None, *, current_parameter_types=None, current_values=None, parameter_bounds=None, single_fit_recommendations_by_run=None, metric=SelectionMetric.AICC, progress_callback=None, scope=None, fit_times=FitTimeEstimates(seconds_per_run={}), user_frequencies_mhz=None, cancel_callback=None, effort_tier=EffortTier.EXHAUSTIVE, portfolio=None, instrumentation=None, stage_callback=None)[source]

Build the ranking table from per-run single-fit wizard results only.

Phase 1 comes first and the portfolio comes out of it: every run is analysed by the single-run Fit Wizard, the series alphabet is the union of what those runs assessed, and every run is then scored against every alphabet template at one series rebin factor (build_or_complete_single_fit_wizard_recommendations_for_global_portfolio()). Pass portfolio together with a single_fit_recommendations_by_run that already covers it — the pair a previous phase-1 call returned — to skip that work; anything less and phase 1 runs here.

effort_tier narrows the alphabet before the completion fits (see screening_templates_for_effort_tier()): Low and Balanced score a trimmed candidate set, while Thorough and Exhaustive — the default — score all of it. Templates a run’s peak search positively identified are never trimmed. The skipped candidates are announced through progress_callback and recorded in instrumentation.

instrumentation additionally receives the standard timing block (asymmetry.core.fitting.wizard_timing): wall-clock, CPU seconds including reaped pool workers, and a per-stage breakdown. stage_callback receives WizardStageProgress events as each stage starts, advances and ends, which is what a caller needs to time out on lack of progress rather than on total runtime.

asymmetry.core.fitting.global_fit_wizard.build_or_complete_single_fit_wizard_recommendations_for_global_portfolio(datasets, current_model=None, *, existing_recommendations_by_run=None, progress_callback=None, scope=None, fit_times=FitTimeEstimates(seconds_per_run={}), user_frequencies_mhz=None, cancel_callback=None, effort_tier=EffortTier.EXHAUSTIVE, metric=SelectionMetric.AICC, instrumentation=None, stage_callback=None, phase1_concurrency=None, apply_alphabet_bound=True)[source]

Run phase 1 of the global fit wizard: per-run analysis, then completion.

Two stages, and the first is the whole point:

  1. Every run goes through the single-run Fit Wizard (build_fit_wizard_recommendation()) — tiered family screening, peak analysis including the matched-apodisation damped-line scan, peak-seeded multiplet templates, null baselines and refinement. That is what finds the heavily damped pair describing only the low-temperature half of a series; a portfolio built from the median fingerprint cannot. A few runs are analysed at once (asymmetry.core.fitting.global_fit_wizard._phase_one_concurrency, overridable with phase1_concurrency), all submitting to phase 1’s single shared pool, and each warm-started from the nearest already-finished run along the sweep axis (asymmetry.core.fitting.global_fit_wizard._run_single_run_analyses). An existing recommendation is reused when it answers the same question — same scope, same user-declared frequencies, encoded by single_fit_build_signature() — which is the whole of the reuse rule; a table derived from some other portfolio carries no signature and is never reused.

  2. Completion. The series alphabet is the union of what those runs assessed (series_template_alphabet()), minus the candidates alphabet_bound_dropped_keys() proves cannot win any segment (apply_alphabet_bound=False keeps them, which is what the benchmark harness compares against), narrowed by the effort tier; the series search resolution is the smallest per-run rebin factor (series_rebin_factor()). Every (run, template) cell the run’s own table does not already hold at that factor is fitted, warm-started and peak-seeded — one task per cell (asymmetry.core.fitting.global_fit_wizard._plan_run_completion), not one per run. The result is a rectangular table whose information criteria are mutually comparable.

Both stages share one spawn pool, opened here at the host’s core count and handed down: to each per-run analysis as its executor, and to the completion cells. It is shut down on the way out and terminated on the way out of a cancel. When it cannot open at all (no spawn-safe environment) both stages run serially, as they did before.

cancel_callback is polled between submissions and while draining in both stages: a wait with a _PHASE_ONE_CANCEL_POLL_SECONDS timeout re-checks it each iteration, so a cancel is honoured within one poll interval instead of one in-flight table’s duration (a fit already running in a worker still cannot be interrupted). A truthy callback raises FitCancelledError and tears the pool down with terminate_spawn_pool() — non-blocking, and force-killing the workers so nothing is orphaned. This matters because phase 1 is a minutes-long job: a drain that only blocks on completion, followed by a shutdown(wait=True), is indistinguishable from a deadlock from the caller’s side.

existing_recommendations_by_run is replaced in place with the run’s own single-run analyses (stage 1’s product), never with the completed table, so a caller’s cache keeps answers that stay reusable.

asymmetry.core.fitting.global_fit_wizard.series_template_alphabet(recommendations_by_run, *, cap=24)[source]

The series’ candidate alphabet: the union of what its runs assessed.

Every template any run’s single-fit wizard successfully fitted is a candidate for the series — including a multiplet template only a couple of runs produced, which is exactly the shape a median-fingerprint portfolio loses. Null baselines are excluded: they are a per-run reference for “no significant structure”, never a model for a coupled series fit.

Order is the order to spend a bounded budget in: templates a run chose (recommended, or scored comparable to the recommendation) first, then by the best rank any single run gave them, then by first appearance in run order. The first cap survive.

asymmetry.core.fitting.global_fit_wizard.alphabet_bound_dropped_keys(recommendations_by_run)[source]

Alphabet candidates that provably cannot win any segment of the series.

The completion pass costs one fit per (run, template) cell, so a template that no partition of the series could ever select is pure expense. This is the exact bound on that, and it is a dominance argument, run by run.

Write χ²_{t,r} for template t’s χ² on run r and IC_{u,r} for template u’s information criterion there. A segment S is scored under one template with one sharing pattern, and

  • sharing only ever raises χ² (the all-local fit is the minimum over assignments) and every penalty is non-negative, so the cost of t on S is at least Σ_{r∈S} χ²_{t,r};

  • the all-local cost of u on S is exactly Σ_{r∈S} IC_{u,r}, an upper bound on the cost of the best structure available on S.

So if some fixed template u satisfies χ²_{t,r} ≥ IC_{u,r} on every run, then u’s all-local score beats t’s best possible score on every segment, and t can be dropped. The template must additionally never have been chosen — recommended or comparable — by any run’s own analysis; that is not part of the arithmetic but keeps a run’s own verdict in the alphabet whatever the sums say.

Two things the argument needs, and does not assume away:

The dominator has to be fixed. Comparing χ²_{t,r} with that run’s best criterion, min_u IC_{u,r}, is not exact, because the argmin may move from run to run while a segment is scored under one template. Two runs, IC_{u1} = (10, 100), IC_{u2} = (100, 10), χ²_t = (11, 11): t clears the per-run minimum on both runs and still wins the segment at 24 against 110. Hence the search for a single u below.

A cell we have no number for is worth nothing. A template a run never assessed contributes 0 to its own floor, so a template assessed on only part of the series is effectively never dropped — which is the honest answer, since the completion fit that would produce the missing χ² has not been run. The dominator, conversely, must be successful on every run: it has to be a structure the whole segment could actually use.

IC_{u,r} is taken as the largest of AIC, AICc and BIC, so the bound holds whichever criterion the caller ranks with and whichever the partition search later scores with (the plan scores partitions with BIC regardless of the ranking metric). Dominators are not restricted to templates that survive the bound themselves: dominance chains are sound, since IC ≥ χ² makes the relation transitive, and their minimal elements are never dropped.

The caller applies the result to the capped alphabet (series_template_alphabet()), so what the bound saves is completion fits rather than slots handed to the next-ranked candidate.

asymmetry.core.fitting.global_fit_wizard.series_rebin_factor(datasets, recommendations_by_run)[source]

One observation-merge factor for the whole series: the smallest per run.

Every run’s own factor already respects that run’s bandwidth (see analysis_rebin_factor()), so the minimum respects all of them. The series needs a single factor because the information criteria of two runs are only summable when both refer to records of the same construction.

asymmetry.core.fitting.global_fit_wizard.screening_templates_for_effort_tier(templates, effort_tier, *, pattern_template_keys=())[source]

Split a candidate portfolio into (screened, skipped) for one effort tier.

Templates named by a multiplet pattern match are never skipped: those are positively identified by the data, so dropping them would change the answer rather than coarsen it. Everything else is ranked cheapest-and-simplest first — the order in which a shorter portfolio should be spent — and the tier’s budget applied.

Model order of the retained templates is preserved, so a caller comparing two tiers’ tables reads the same rows in the same order.

Trend objective

asymmetry.core.fitting.global_search.trend_objective.trend_sort_key(assessments, metric)[source]

A key that orders ladder rungs for display, smaller first.

Template by template: the contending templates in the order of trend_contenders(), so the recommended rung leads, then the templates outside the band by how well they fit. Within a template the pre-selected rung, then the other adequate rungs by trend quality, then the rungs that cost too much by their cost.

asymmetry.core.fitting.global_search.trend_objective.trend_contenders(assessments, metric)[source]

The pre-selected rung of each template inside the band, the best trend first.

The band is taken over the templates that have a ladder among assessments: a template climbed because the data identified it, or because the user ticked it, is listed with its rungs but contends only when it fits about as well as the best of them. Rungs whose worst trend quality is within TREND_TIE of the leader’s trend equally well: among them the rung that is not hard to justify leads, then the template that fits best all-local. A rung with no local parameter orders below every rung that has one, so it leads only when nothing else is adequate.

asymmetry.core.fitting.global_search.trend_objective.TREND_TIE

Peak detection

asymmetry.core.fitting.peak_detection.analyze_damped_scan_peaks(time, signal, error, *, max_lines=3)[source]

Run the matched-apodisation damped-line scan and express it as peaks.

The scan (detect_damped_lines()) is the wizard’s damped-line pass: it needs no user-chosen crop, it measures the envelope rate rather than inferring it from a crop length, and it accepts a line on a look-elsewhere-corrected Δχ² test rather than on an SNR gate. Each accepted line becomes one source="damped_scan" DetectedPeak, Δχ²-descending, carrying the measured λ, amplitude, phase and Δχ² so the seeding path can use them directly.

width_mhz is the Lorentzian FWHM λ/π of the line’s own envelope — the honest width of a peak the scan never resolved with a window — and crop_us is None: there is no crop. The full DampedLineAnalysis is attached to PeakAnalysis.damped_lines, since the Δχ² threshold and the trial count live there and not on the peaks.

signal should be the record the lines are actually in — the raw asymmetry, or the residual when a detrend curve is available. The scan carries its own slow-decay nuisance dictionary, so a constant offset or a slow relaxation left in signal is absorbed rather than fitted.

asymmetry.core.fitting.peak_detection.analyze_early_window_peaks(time, signal, error, *, max_peaks=3, min_snr=6.0)[source]

Find heavily damped lines the Hann pass structurally cannot see.

Every windowed transform (hann/cosine/gaussian) is zero at the first sample, so it deletes exactly the leading nanoseconds where a heavily damped oscillation lives — the failure the library’s ApodisationEarlySignalWarning exists to flag. This pass is the seeding-side answer: an unwindowed (window="none"), first-order-detrended transform of a short leading crop of the record, repeated over a small ladder of crops (early_window_crops()), each with its own honest resolution_mhz = 1/T_crop.

time/signal/error are the already-centred, already SNR-truncated arrays analyze_dataset_peaks() transforms; the returned analysis carries the peaks from every rung, de-duplicated across rungs, tagged source="early_fft" and stamped with the crop that found them (asymmetry.core.fitting.peak_detection.DetectedPeak.crop_us). resolution_mhz is the ladder’s finest (longest crop); a peak’s own resolution is 1/peak.crop_us.

The synthetic study behind the constants. All parameters invented; the record is a damped cosine at 300 MHz on a relaxing tail, 1 ns binning over 8 µs, with μSR-like errors growing as exp(t/2τ_μ) capped at 100 %.

  1. Which crops — a fixed ladder, not an envelope-estimated crop. Both shapes the plan called for were built and scored. The adaptive one — high-pass with the apodisation guard’s moving-mean machinery, fit the decay of the high-passed envelope, crop to ~3/λ_est — tracks λ well while λ is slow (10.7 against a true 10, 2.2 against 2) and fails exactly where the feature is needed: at λ = 60 µs⁻¹ it returned an estimate on only 3 draws in 30 and read ~35, because a moving-mean kernel wide enough to be a baseline is already wider than the lifetime being measured. Recovering that would mean scanning kernel scales — which is the crop ladder, with extra machinery in front. It was also the worse citizen on a conventional record, contributing a spurious peak on ~1 draw in 3 where the ladder contributed none. So: a fixed ladder. Ladders of two to four rungs drawn from 1/8 … 1/512 of the record were then scored. Detection is flat across all of them (median SNR within ~5 % at every λ), so the null decides, and short rungs are what damage it: a crop below ~1/128 of the record leaves a band only ~10 resolution elements wide, where the clipped median floor is itself noisy. Adding a 1/256 rung raised the pure-noise maximum from 5.07 to 6.85 and a 1/512 rung to 9.12, neither detecting anything the surviving rungs missed. 1/16 and 1/64 — ~440 ns and ~110 ns on an 8 µs informative window — cover envelope rates from ~2 µs⁻¹ (where the Hann pass sees the line too) to ~100 µs⁻¹ (where it is entirely blind). Beyond ~120 µs⁻¹ the line is not recoverable at any crop at these amplitudes; that is a limit of the pass, not a claim.

  2. Which noise floor. With the default running-median floor the reported SNR of the damped line saturated near 5 whatever its amplitude — on a band ten resolution elements wide the median window sits inside the line’s own Lorentzian skirt, so the ratio measures line shape, not significance — while pure noise reached 6.4. Nothing separated them. The global clipped floor (asymmetry.core.fitting.peak_detection._global_noise_floor) restores SNR ∝ amplitude over an 8× amplitude sweep.

  3. Which threshold (_EARLY_MIN_SNR, re-derived, not inherited). Three null families were drawn through the shipped ladder with the gate open: 500 pure-noise records, 500 relaxing tails with no oscillation, and 400 conventional narrow-line records whose line is alive across the whole record. Raw peaks arrive at 0.08-0.14 per draw and the largest SNR any of them reached was 5.31. The gate sits at 6.0. At that gate all three families contribute exactly zero early-pass peaks, the conventional record’s Hann-pass peaks are bit-identical with the pass on and off, and the damped line is still found (median SNR 9.3 at λ = 60 µs⁻¹).

asymmetry.core.fitting.peak_detection.detect_peaks_in_spectrum(frequencies_mhz, magnitude, *, resolution_mhz, max_peaks=6, min_snr=2.5, source='fft', low_guard_resolutions=0.5, high_guard_resolutions=0.5, global_noise_floor=False, leakage_profile='hann', crop_us=None)[source]

Detect spectral lines in a positive-frequency magnitude spectrum.

Parameters:
  • frequencies_mhz, magnitude – The (possibly zero-padded / oversampled) frequency axis and magnitude.

  • resolution_mhz – The true spectral resolution 1/T — distinct from the bin spacing df when the spectrum is zero-padded.

  • max_peaks, min_snr, source – Cap, SNR threshold and provenance tag.

  • low_guard_resolutions, high_guard_resolutions – Widths of the DC and Nyquist guard bands, in resolution elements. Both default to the historical Hann-pass 0.5; the early-window pass widens both (see analyze_early_window_peaks()). Low: an unwindowed short crop of a relaxing record leaves residual trend curvature in the first few resolution elements, and a line completing only a cycle or two inside such a crop is not a resolvable oscillation there in any case. High: the running-median floor is edge-biased low at both ends, and the last bin of an rfft is real-only (half-normal, not Rayleigh), so noise excursions in the outermost resolution elements clear the SNR gate far more often than the look-elsewhere correction allows for.

  • global_noise_floor – Estimate one sigma-clipped median floor over the whole guarded band instead of the historical running-median floor — what a short crop needs (see asymmetry.core.fitting.peak_detection._global_noise_floor).

  • leakage_profile – "hann" (default) or "rect" — which window’s sidelobe envelope the leakage guard rejects against (see asymmetry.core.fitting.peak_detection._sidelobe_ceiling). The early-window pass transforms unwindowed and must use "rect".

  • crop_us – Stamped onto every returned peak’s asymmetry.core.fitting.peak_detection.DetectedPeak.crop_us for provenance; the early-window pass passes its crop duration here.

Returns:

PeakAnalysis – Peaks SNR-descending, with the representative noise floor, resolution and Nyquist recorded.

asymmetry.core.fitting.peak_detection.merge_damped_scan_peaks(analysis, scan, *, max_peaks=6)[source]

Fold damped-scan peaks into a Hann-pass analysis.

The merge policy is merge_early_peaks()’s, with one addition that only the scan pass makes possible:

  • The Hann pass still wins a collision on frequency — for a line it can see at all, a transform of the whole informative record localises it better than a scan rung does. The collision radius is the scan line’s own linewidth λ/π (or the Hann resolution, whichever is coarser), because that is the width of the thing being matched.

  • …but it inherits the measurement. The scan’s λ, amplitude, phase and Δχ² are copied onto the surviving Hann peak. Dropping them would throw away the only envelope estimate in the pipeline for a line both passes can see — precisely the seeding information the wizard needs.

  • Scan peaks that collide with nothing are additions, capped by max_peaks with _EARLY_RESERVED_PEAKS slots reserved so a full Hann peak set cannot starve the pass that exists to see what Hann cannot.

  • damped_lines is always attached, even when the scan found nothing — the threshold and trial count are the evidence that it looked.

asymmetry.core.fitting.peak_detection.merge_early_peaks(analysis, early, *, max_peaks=6)[source]

Fold early-window peaks into a Hann-pass analysis.

Merge policy, in full:

  • The Hann pass wins a collision. An early-pass peak within the coarser of the two resolutions of an existing Hann-pass peak is dropped: the Hann pass looked at the whole informative record, so for a line it can see at all its frequency estimate is the better one. Early-pass peaks are only ever additions — lines the Hann pass missed.

  • SNRs are never compared across passes. An early-pass SNR is measured on a short crop against a different noise floor; the merged tuple keeps the Hann peaks in their own SNR order, then the early additions in theirs, and each peak keeps its source (and crop_us) so downstream consumers can rank within a pass.

  • The ``max_peaks`` cap survives the merge, with _EARLY_RESERVED_PEAKS slots reserved for early additions — otherwise a full Hann peak set could starve the pass that exists to see what Hann cannot.

asymmetry.core.fitting.peak_detection.merge_user_peaks(analysis, user_frequencies_mhz, *, record=None)[source]

Fold user-declared frequencies into an analysis.

A user frequency within one resolution element of an existing detected peak replaces it — keeping the detected amplitude/width but flagging source="user" with the sentinel SNR. The radius is the matched peak’s OWN pass resolution (an early-window peak’s crop resolution, not the Hann pass’s), so a user frequency and the early-pass line it corresponds to collapse into one seed rather than two. Otherwise the frequency is added as a fresh user peak. User peaks sort first and are never dropped; no max_peaks cap is re-applied here, and the relative order of the detected peaks — which is per-pass, since SNRs are not comparable across passes — is preserved.

A fresh user frequency (one that matched nothing at that radius) still inherits the λ/amplitude/phase/Δχ² of a "damped_scan" peak lying within one linewidth of it, and that peak’s width with them. The radius above is the Hann pass’s spectral resolution, orders of magnitude finer than a heavily damped line’s own λ/π width, so a user click on such a line lands “fresh” while plainly naming the same oscillation — and the envelope the scan measured is the one piece of seeding information the click itself cannot carry.

record is the optional (time, asymmetry, error) the frequencies were read off. Given it, a fresh user peak that inherits nothing from a scan line has its own envelope measured at the stated frequency (asymmetry.core.fitting.peak_detection._measure_fresh_user_peak) — so a hand-seeded damped line seeds the fit with a λ even where the blind scan declined it. This is the seam the measurement enters by: every caller that already holds the record passes it, and one that does not keeps the previous behaviour unchanged.

class asymmetry.core.fitting.peak_detection.DetectedPeak(frequency_mhz, amplitude, snr, width_mhz, prominence, source, burg_confirmed=None, crop_us=None, damping_rate_per_us=None, amplitude_percent=None, phase_rad=None, delta_chi_squared=None)[source]

A single detected spectral line.

frequency_mhz

Sub-bin (parabolically interpolated) line frequency in MHz.

Type:

float

amplitude

Interpolated magnitude at the peak.

Type:

float

snr

amplitude divided by the local noise floor at the peak bin.

Type:

float

width_mhz

FWHM estimated via scipy.signal.peak_widths (rel_height=0.5), converted from bins to MHz.

Type:

float

prominence

Peak prominence from scipy.signal.find_peaks.

Type:

float

source

Provenance: "fft", "residual_fft", "early_fft", "damped_scan" or "user". An "early_fft" SNR is measured on a short unwindowed crop against a different noise floor, and a "damped_scan" SNR is a MAD excess over a matched-apodisation rung’s own floor; neither is comparable with an "fft" SNR from the full record — rank within a pass, never across.

Type:

str

burg_confirmed

True/False when a Burg cross-check ran and did / did not find a matching all-poles local maximum; None when no cross-check ran. Always None for "early_fft" / "damped_scan" peaks: Burg is scoped to the Hann pass (it is unreliable on short, heavily damped windows).

Type:

bool | None

crop_us

Duration of the early-window crop that found this peak, in µs; its spectral resolution is 1/crop_us. None for every other source — the matched-apodisation scan needs no crop, so its peaks carry None here and report their envelope directly in damping_rate_per_us.

Type:

float | None

damping_rate_per_us, amplitude_percent, phase_rad, delta_chi_squared

The measured line parameters a DampedLine carries: envelope rate λ (µs⁻¹) of exp(-λt), amplitude A of A·exp(-λt)·cos(2πft + φ) on the input’s asymmetry scale, phase φ in radians, and the weighted χ² improvement the line bought against the scan’s nuisance basis. All None for a peak that carries no such measurement (every pass but "damped_scan", and a "user" peak that inherited nothing). Additive — old payloads deserialize to None.

asymmetry.core.fitting.peak_detection.early_window_crops(n_points)[source]

Point counts of the early-window crop ladder for an n_points record.

Each rung is n_points // divisor for the divisors in _EARLY_CROP_DIVISORS, floored at _EARLY_MIN_POINTS. A rung that is not at least _EARLY_CROP_SHRINK shorter than the one before it is dropped, so a short record collapses the ladder rather than transforming nearly the same crop twice.

Process pool

asymmetry.core.fitting.process_pool.terminate_spawn_pool(pool)[source]

Tear a spawn pool down now, without waiting for in-flight tasks.

Drops queued work (cancel_futures=True, wait=False) and then force-kills the worker processes, reaping each so a cancelled run leaves no orphaned spawn workers and no zombies (a bare kill() without a following join() leaves the killed child unreaped until someone waitpid``s it). Use this on the cancellation path where a blocking ``shutdown(wait=True) would stall the UI for one in-flight fit’s duration; the normal completion path still calls plain concurrent.futures.ProcessPoolExecutor.shutdown.

Best-effort on the private _processes map — a missing/renamed attribute (or a non-real pool, e.g. a test fake) degrades to the plain non-blocking shutdown. _processes is snapshotted before shutdown because shutdown may clear it.

Wizard timing

class asymmetry.core.fitting.wizard_timing.WizardStageProgress(stage, message, event, items_done=None, items_total=None, elapsed_seconds=0.0, cpu_seconds=0.0)[source]

One structured progress event from a wizard stage.

Emitted when a stage starts, whenever it completes a unit of work, and when it ends. items_done/items_total are None for stages that are not item-wise.

Previous Next

© Copyright 2026, Asymmetry Contributors.

Built with Sphinx using a theme provided by Read the Docs.