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
- __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_curvesreconstructs any other row from its fitted parameters;_with_dense_curvesowns 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.0when no refinement pass ran for this candidate. Additive — old payloads deserialize to0.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).Noneon 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 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 pinsB_Lat 0, at which pointLongitudinalFieldKT + Constantfits identically toStaticGKT_ZF + Constanton the same three free parameters — the same function reached through a longitudinal machinery it does not use. Prefer the model that never carried it.
- __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 toNONE.
- 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
confidenceis 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=Noneinbuild_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
- __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_DELTAof the best, or are named by a multiplet pattern match expand to their full Stage-2 portfolios.scoperestricts the families physically (Nonescreens the default superset), andfit_timesjudges which models its slow switch leaves out;user_frequencies_mhzadds trusted peak seeds — blind runs get the same seeds from the matched-apodisation damped-line scan when the data carry a heavily damped line (seedetect_damped_lines());max_workers=1gives a deterministic serial path. Note thatmax_workersbounds fits in flight, not CPU: the vortex-lattice candidates reach a multi-threaded BLAS from inside a single fit, so amax_workers=1run can still saturate the machine — seeasymmetry.core.fitting.process_poolfor the measurement and the environment knob.cancel_callbackis 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 raisesFitCancelledError.executorsupplies 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 anexecutorthe 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_templatesupplies 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 (seeasymmetry.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_candidatesre-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);0disables the pass.instrumentationreceives the standard timing block andstage_callbackthe structured per-stage progress events described inasymmetry.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.stage2andsingle_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_BUDGETpoints 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 inasymmetry.core.fitting.fit_wizard.FitWizardRecommendation.rebin_factorandanalysed_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 becomesNO_SIGNIFICANT_STRUCTUREand 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_curvesmaterialises 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 inglobal_param_names;exemptionsretains 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;
Noneon a role-search node and a screening row.
- analysis_history = None
- 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 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_keyandcomparable_keysselect series-wide assessments.partition_pathdescribes contiguous phases;phase_assessmentsstores each verified (k, segment_index) fit, andrecommended_partition_kselects 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.
- phase_assessment(segment_index)[source]
The recommended assessment of one phase of the optimised partition.
Nonefor an excluded end stub, which never receives a coupled fit.
- sorted_rungs(metric=None)[source]
The sharing ladders’ rungs in display order: what Compare lists under the trend objective.
- __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).
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]
- __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.
objectiveis 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.STATISTICALruns the role search they describe and recommends the bestmetric. One call computes one objective.portfoliois the candidate set to search, normally the series alphabet a phase-1 call returned together with thesingle_fit_recommendations_by_runtable 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_tieris the user-facing effort slider:LOW,BALANCED,THOROUGH,EXHAUSTIVE(defaultEXHAUSTIVE). 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_engineremains available as a lower-level override for existing callers/tests — when given explicitly it takes precedence overeffort_tierfor 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 througheffort_tier.partition_kswitches the whole run from one series-wide answer to one answer per phase: solutionkofpartition_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 carriesphase_assessmentsand a re-scored path instead of arecommended_key. The two arrive together — aknames a row of a specific path — so passing one without the other is a programming error and is refused. Withpartition_k=Nonenothing 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
objectivedecides how: the best trend among the pre-selected ladder rungs,metricbreaking ties, or the bestmetricamong the role-search nodes that pass every run’s residual gate.A partitioned recommendation — one whose
recommended_partition_knames 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 (seebuild_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.
peaksis ordered by SNR descending within a detection pass, with any user-declared peaks first and each pass’s block following: anearly_fftSNR is measured on a short unwindowed crop against a different noise floor, so it is not comparable with anfftSNR from the whole record. A single pass’s output is therefore plainly SNR-descending; a merged one is blocks of it (seemerge_early_peaks()andmerge_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.Nonewhen the scan did not run. Additive — old payloads deserialize toNone.
- 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_curvewhen given, else tail-subtracted) is transformed with a Hann window and 4× zero-padding, then passed todetect_peaks_in_spectrum(). A Burg (all-poles) cross-check may confirm but never add peaks — seeburg_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.4and is rejected byasymmetry.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 (seeasymmetry.core.fitting.peak_detection._running_median).- Parameters:
detrend_curve – Optional model curve aligned with
dataset.timeto 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_curveis used.burg_check –
"auto"(run whenn_points < 512or two peaks fall within2·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
Falseto 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
missingso fitting can be blocked with a clear message instead of the model being silently dropped. Placeholders are per-instance and are never inserted intoCOMPONENTS.
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).asymmetryanderrormay 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.
linesis ordered bydelta_chi_squareddescending. 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 lifetime1/λ).- Type:
float
- amplitude_percent
Amplitude
AofA·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_reasonsto 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)⌋, wheref_maxis 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_maxin the first place.sample_budgetdefaults 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_DELTAof the best, or are named by a multiplet pattern match expand to their full Stage-2 portfolios.scoperestricts the families physically (Nonescreens the default superset), andfit_timesjudges which models its slow switch leaves out;user_frequencies_mhzadds trusted peak seeds — blind runs get the same seeds from the matched-apodisation damped-line scan when the data carry a heavily damped line (seedetect_damped_lines());max_workers=1gives a deterministic serial path. Note thatmax_workersbounds fits in flight, not CPU: the vortex-lattice candidates reach a multi-threaded BLAS from inside a single fit, so amax_workers=1run can still saturate the machine — seeasymmetry.core.fitting.process_poolfor the measurement and the environment knob.cancel_callbackis 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 raisesFitCancelledError.executorsupplies 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 anexecutorthe 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_templatesupplies 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 (seeasymmetry.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_candidatesre-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);0disables the pass.instrumentationreceives the standard timing block andstage_callbackthe structured per-stage progress events described inasymmetry.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.stage2andsingle_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_BUDGETpoints 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 inasymmetry.core.fitting.fit_wizard.FitWizardRecommendation.rebin_factorandanalysed_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_analysislets a caller that has already runanalyze_dataset_peaks()hand the result in. That is not (only) about saving a transform: without it the damped-line candidate carried here and theearly_fftpeaks 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()). Passportfoliotogether with asingle_fit_recommendations_by_runthat already covers it — the pair a previous phase-1 call returned — to skip that work; anything less and phase 1 runs here.effort_tiernarrows the alphabet before the completion fits (seescreening_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 throughprogress_callbackand recorded ininstrumentation.instrumentationadditionally receives the standard timing block (asymmetry.core.fitting.wizard_timing): wall-clock, CPU seconds including reaped pool workers, and a per-stage breakdown.stage_callbackreceivesWizardStageProgressevents 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:
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 withphase1_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 bysingle_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.Completion. The series alphabet is the union of what those runs assessed (
series_template_alphabet()), minus the candidatesalphabet_bound_dropped_keys()proves cannot win any segment (apply_alphabet_bound=Falsekeeps 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_callbackis polled between submissions and while draining in both stages: awaitwith a_PHASE_ONE_CANCEL_POLL_SECONDStimeout 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 raisesFitCancelledErrorand tears the pool down withterminate_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 ashutdown(wait=True), is indistinguishable from a deadlock from the caller’s side.existing_recommendations_by_runis 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
capsurvive.
- 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 templatet’s χ² on runrandIC_{u,r}for templateu’s information criterion there. A segmentSis scored under one template with one sharing pattern, andsharing only ever raises χ² (the all-local fit is the minimum over assignments) and every penalty is non-negative, so the cost of
tonSis at leastΣ_{r∈S} χ²_{t,r};the all-local cost of
uonSis exactlyΣ_{r∈S} IC_{u,r}, an upper bound on the cost of the best structure available onS.
So if some fixed template
usatisfiesχ²_{t,r} ≥ IC_{u,r}on every run, thenu’s all-local score beatst’s best possible score on every segment, andtcan 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):tclears the per-run minimum on both runs and still wins the segment at 24 against 110. Hence the search for a singleubelow.A cell we have no number for is worth nothing. A template a run never assessed contributes
0to 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, sinceIC ≥ χ²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 withinTREND_TIEof 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 onesource="damped_scan"DetectedPeak, Δχ²-descending, carrying the measured λ, amplitude, phase and Δχ² so the seeding path can use them directly.width_mhzis the Lorentzian FWHMλ/πof the line’s own envelope — the honest width of a peak the scan never resolved with a window — andcrop_usisNone: there is no crop. The fullDampedLineAnalysisis attached toPeakAnalysis.damped_lines, since the Δχ² threshold and the trial count live there and not on the peaks.signalshould 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 insignalis 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’sApodisationEarlySignalWarningexists 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 honestresolution_mhz = 1/T_crop.time/signal/errorare the already-centred, already SNR-truncated arraysanalyze_dataset_peaks()transforms; the returned analysis carries the peaks from every rung, de-duplicated across rungs, taggedsource="early_fft"and stamped with the crop that found them (asymmetry.core.fitting.peak_detection.DetectedPeak.crop_us).resolution_mhzis the ladder’s finest (longest crop); a peak’s own resolution is1/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 %.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.
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.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 spacingdfwhen 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 (seeanalyze_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 anrfftis 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 (seeasymmetry.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_usfor 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_peakswith_EARLY_RESERVED_PEAKSslots reserved so a full Hann peak set cannot starve the pass that exists to see what Hann cannot.damped_linesis 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(andcrop_us) so downstream consumers can rank within a pass.The ``max_peaks`` cap survives the merge, with
_EARLY_RESERVED_PEAKSslots 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; nomax_peakscap 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.recordis 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
amplitudedivided 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/Falsewhen a Burg cross-check ran and did / did not find a matching all-poles local maximum;Nonewhen no cross-check ran. AlwaysNonefor"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.Nonefor every other source — the matched-apodisation scan needs no crop, so its peaks carryNonehere and report their envelope directly indamping_rate_per_us.- Type:
float | None
- damping_rate_per_us, amplitude_percent, phase_rad, delta_chi_squared
The measured line parameters a
DampedLinecarries: envelope rate λ (µs⁻¹) ofexp(-λt), amplitudeAofA·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. AllNonefor a peak that carries no such measurement (every pass but"damped_scan", and a"user"peak that inherited nothing). Additive — old payloads deserialize toNone.
- asymmetry.core.fitting.peak_detection.early_window_crops(n_points)[source]
Point counts of the early-window crop ladder for an
n_pointsrecord.Each rung is
n_points // divisorfor the divisors in_EARLY_CROP_DIVISORS, floored at_EARLY_MIN_POINTS. A rung that is not at least_EARLY_CROP_SHRINKshorter 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 barekill()without a followingjoin()leaves the killed child unreaped until someonewaitpid``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 plainconcurrent.futures.ProcessPoolExecutor.shutdown.Best-effort on the private
_processesmap — a missing/renamed attribute (or a non-real pool, e.g. a test fake) degrades to the plain non-blocking shutdown._processesis 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_totalareNonefor stages that are not item-wise.