Parameter trend models

class asymmetry.core.fitting.parameter_models.ParameterModelComponentDefinition(name, description, function, param_names, param_defaults, param_info, formula_template, latex_equation='', scopes=('common',), fwhm_factor=None, user=False, category='General')[source]

Bases: object

Descriptor for a parameter-vs-x basis function.

name
description
function
param_names
param_defaults
param_info
formula_template
latex_equation = ''
scopes = ('common',)
fwhm_factor = None

For centred-peak components, FWHM = fwhm_factor * Bwid (None otherwise).

user = False

True for components registered through the user-function facade (asymmetry.core.fitting.user_functions); see ComponentDefinition.user.

category = 'General'

Library-panel grouping (mirrors ComponentDefinition.category). Assigned in bulk via _PARAMETER_MODEL_CATEGORIES below rather than per-definition, so the taxonomy is reviewable in one place.

__init__(name, description, function, param_names, param_defaults, param_info, formula_template, latex_equation='', scopes=('common',), fwhm_factor=None, user=False, category='General')
class asymmetry.core.fitting.parameter_models.ParameterCompositeModel(component_names, operators=None, open_parentheses=None, close_parentheses=None)[source]

Bases: object

Flat composite model for parameter-vs-x fitting.

__init__(component_names, operators=None, open_parentheses=None, close_parentheses=None)[source]
classmethod from_expression(expression)[source]

Construct a ParameterCompositeModel from a component-name expression.

component_expression_string()[source]

Return the builder-facing expression using component names.

parameter_identities()[source]

Map every unique parameter name to what that parameter is.

A trend model has no fraction groups and no suppressed amplitudes, so every parameter belongs to one component instance. Keyed identities let parameter state follow a component across a model edit instead of being matched by its collision-driven name (see asymmetry.core.fitting.parameter_carry).

component_param_name(component_index, local_name)[source]

Global (possibly index-suffixed) param name for a component’s param.

For ["GaussianLCR", "LorentzianLCR"] the second component’s "B0" is "B0_2"; for a single component it is the bare "B0". Lets callers address a component’s parameters by name instead of positional arithmetic over param_names.

formula_string()[source]

Return a readable formula string for display.

latex_terms()[source]

Return the trend model as typeset (mathtext) additive terms.

group is always None (parameter-vs-x models have no fraction groups). The quadrature operator ⊕ renders a flat chain as \sqrt{a^{2} + b^{2}}. Parenthesised or ⊕-mixed expressions that are ambiguous to lay out fall back to a single \mathrm{...} term. Never raises and never returns an empty list for a valid model.

latex_string()[source]

Return the whole trend model as one mathtext string.

function(x, **kwargs)[source]

Evaluate the composite model with arithmetic precedence.

additive_component_indices()[source]

Return indices for additive components (first term, ‘+’ and ‘⊕’ terms).

Quadrature (⊕) combines whole components like + does, so each operand is a distinct curve worth plotting on its own; subtractive and multiplicative terms are not standalone contributions.

evaluate_components(x, *, additive_only=False, **kwargs)[source]

Evaluate individual component curves for plotting/export.

to_dict()[source]

Return a JSON-serializable representation of the model.

classmethod from_dict(data)[source]

Construct a ParameterCompositeModel from serialized data.

class asymmetry.core.fitting.parameter_models.ParameterModelFitResult(success, chi_squared=0.0, reduced_chi_squared=0.0, parameters=<factory>, uncertainties=<factory>, message='', error_mode='column', n_points=0, n_starts_tried=0, seed_beat_user_start=False, params_at_bound=(), covariance=None, computation_revision=None, input_width_context=None)[source]

Bases: object

Result of fitting a parameter-vs-x model.

success
chi_squared = 0.0
reduced_chi_squared = 0.0
parameters
uncertainties
message = ''
error_mode = 'column'

Error mode the fit was run with (χ²ᵣ carries no goodness information for "none"/"scatter" — quality verdicts should be suppressed).

n_points = 0

Number of points that entered the fit (0 when unknown/legacy).

n_starts_tried = 0

How many initial-value candidates the multi-start machinery actually tried (1 for the default single-start path; more with extra_starts).

seed_beat_user_start = False

True iff the winning fit came from a non-user start (a data-aware or perturbed seed beat the user’s provided parameters). Advisory only.

params_at_bound = ()

Names of free parameters whose fitted value sits within tolerance of a finite min/max bound — a sign the data did not determine them.

covariance = None

(names, matrix) of the free-parameter covariance from Minuit, in the same order as names (free parameters only, fixed parameters excluded). None when unavailable: the fit failed/invalid or Minuit produced no covariance (e.g. HESSE did not run/converge).

computation_revision = None
input_width_context = None
__init__(success, chi_squared=0.0, reduced_chi_squared=0.0, parameters=<factory>, uncertainties=<factory>, message='', error_mode='column', n_points=0, n_starts_tried=0, seed_beat_user_start=False, params_at_bound=(), covariance=None, computation_revision=None, input_width_context=None)
class asymmetry.core.fitting.parameter_models.ModelFitRange(x_min, x_max, model, parameters, result=None, windows=None)[source]

Bases: object

A model and fit results over a specific x-range.

windows optionally restricts the range to a union of (min, max) intervals: a point enters the fit if it falls in any window (OR-combination), with one model fitted across the union. When absent, the plain x_min/x_max bounds apply.

x_min
x_max
model
parameters
result = None
windows = None
__init__(x_min, x_max, model, parameters, result=None, windows=None)
class asymmetry.core.fitting.parameter_models.ParameterModelFit(parameter_name, x_key, ranges=<factory>, active=True, use_x_errors=False)[source]

Bases: object

Model fits attached to a single parameter trace.

parameter_name
x_key
ranges
active = True
use_x_errors = False

When the x-axis is a fitted parameter (x_key == "param:<name>"), account for its per-point uncertainty via effective-variance weighting.

__init__(parameter_name, x_key, ranges=<factory>, active=True, use_x_errors=False)
class asymmetry.core.fitting.parameter_models.ParameterModelFitExecution(range_index, x, y, result)[source]

Bases: object

Fitted model with sampled curve ready for plotting/export.

range_index
x
y
result
__init__(range_index, x, y, result)
class asymmetry.core.fitting.parameter_models.ParameterGroupData(group_id, group_name, x, y, yerr, group_variable_value, xerr=None, input_computation_revisions=(), width_context=None)[source]

Bases: object

Input data for one selected group in a cross-group parameter fit.

group_id
group_name
x
y
yerr
group_variable_value
xerr = None

Optional per-point x-uncertainty (aligned to x), used only for an effective-variance fit when the abscissa is itself a fitted parameter.

input_computation_revisions = ()
width_context = None
to_dict()[source]

Canonical, JSON-safe serialization (numpy arrays -> lists).

classmethod from_dict(data)[source]

Tolerant deserialization: missing arrays default to empty.

__init__(group_id, group_name, x, y, yerr, group_variable_value, xerr=None, input_computation_revisions=(), width_context=None)
class asymmetry.core.fitting.parameter_models.CrossGroupFitResult(success, chi_squared, reduced_chi_squared, global_parameters=<factory>, local_parameters=<factory>, fixed_parameters=<factory>, global_uncertainties=<factory>, local_uncertainties=<factory>, message='', error_mode='column', n_points=0, uses_effective_variance=False, per_group_chi_squared=<factory>, per_group_n_points=<factory>, global_correlations=None, input_width_contexts=<factory>, computation_revision=None)[source]

Bases: object

Result container for cross-group parameter fits.

success
chi_squared
reduced_chi_squared
global_parameters
local_parameters
fixed_parameters
global_uncertainties
local_uncertainties
message = ''
error_mode = 'column'

Error mode the fit was run with (χ²ᵣ carries no goodness information for "none"/"scatter" — quality verdicts should be suppressed).

n_points = 0

Number of points that entered the fit across all groups (0 if unknown).

uses_effective_variance = False
per_group_chi_squared

Per-group costs use the same mask and weighting as the joint objective. SCATTER rescales uncertainties, leaving these unit-weight RSS values unchanged.

per_group_n_points

Number of points that entered the fit for each group (post mask/window).

global_correlations = None

(names, matrix) of free GLOBAL parameter correlations derived from the Minuit covariance (corr_ij = cov_ij / sqrt(cov_ii * cov_jj)). None when unavailable: fewer than two free global parameters, a failed fit, or no covariance from Minuit.

input_width_contexts
computation_revision = None
to_dict()[source]

Canonical, JSON-safe serialization.

ParameterSets serialize as lists of {name, value, min, max, fixed} dicts (see asymmetry.core.fitting.parameter_models._parameter_set_to_dicts), matching the shape already used by the GUI’s project-state serializers.

classmethod from_dict(data)[source]

Read the optional recorded diagnostics alongside the fitted parameters.

__init__(success, chi_squared, reduced_chi_squared, global_parameters=<factory>, local_parameters=<factory>, fixed_parameters=<factory>, global_uncertainties=<factory>, local_uncertainties=<factory>, message='', error_mode='column', n_points=0, uses_effective_variance=False, per_group_chi_squared=<factory>, per_group_n_points=<factory>, global_correlations=None, input_width_contexts=<factory>, computation_revision=None)
asymmetry.core.fitting.parameter_models.component_names_for_x(x_key)[source]

Return available basis functions for a given x-variable.

asymmetry.core.fitting.parameter_models.fit_parameter_model(x, y, yerr, model, parameters, x_min=None, x_max=None, method='migrad', error_mode=ErrorMode.COLUMN, error_value=None, windows=None, xerr=None, extra_starts=0, seed=0, cancel_check=None, width_context=None)[source]

Fit parameter-vs-x observations with optional captured width context.

Windows select a union of intervals; otherwise x_min/x_max bound the fit. Supplied x-errors use effective variance with physical y-errors, and are ignored for unit/scatter weights. Extra starts use the recorded seed. Known Gaussian widths require explicit conversion at Brandt consumers; generic observations with unknown provenance retain their existing meaning.

asymmetry.core.fitting.parameter_models.global_fit_parameter_model(groups, model, global_params, local_params, fixed_params, initial_params=None, parameter_bounds=None, method='migrad', error_mode=ErrorMode.COLUMN, error_value=None, windows=None, xerr=None)[source]

Jointly fit groups with global, local, and fixed parameters.

Each group retains its selected source-width context. Windows select an interval union. Supplied x-errors use effective variance with physical y-errors, and are ignored for unit/scatter weights. SCATTER scales all fitted uncertainties by sqrt(chi_squared / degrees of freedom).

asymmetry.core.fitting.parameter_models.evaluate_parameter_model_fit(fit, num_points=200)[source]

Return sampled curves for each successful active range.

Note

The available parameter-trend component registry is exposed as asymmetry.core.fitting.parameter_models.PARAMETER_MODEL_COMPONENTS.

The angle-only \(K(\theta)\) basis models KnightAnisotropy, AngularCos2, and AngularFourier2 are registered alongside the others (scope="angle").

Field-scan baseline and peak inference

These adapters fit original scan observations. Derivative scans support inspection/export only: their marginal errors do not supply an independent likelihood. The common fit-input boundary also checks the actual selected window’s scalar validity and positional source sharing before seeding. See Integral scan mode (avoided-level-crossing field scans) for baseline propagation and scan units.

Scalar fit adapters and fit_parameter_model accept an optional raising cancel_check. Use an established cancellation exception such as asymmetry.core.fitting.engine.FitCancelledError; it propagates through solver and seed paths rather than returning a failed fit or partial covariance. The default leaves successful numerical methods and results unchanged. ScanBaselineResult.evaluate_baseline, baseline_correction_operator, and baseline_corrected_covariance accept the same poll when these derived operations are needed independently of a peak fit. Their property counterparts retain the ordinary no-callback API. Work-unit limits are described in Integral scan mode (avoided-level-crossing field scans).

asymmetry.core.fitting.fit_scan_baseline(scan, regions, *, model='Linear', parameters=None, method='migrad', cancel_check=None)[source]

Fit a baseline over non-resonant regions and subtract it.

Parameters:
  • scan – The field scan to correct.

  • regions – Inclusive (x_lo, x_hi) windows on the scan’s x-axis marking the non-resonant baseline regions (their union is fitted).

  • model – Baseline model — "Linear" (default), "Constant", or any component/expression.

  • parameters – Optional starting ParameterSet; defaults are used otherwise.

Returns:

ScanBaselineResult – The fitted baseline sampled over all scan points, a corrected FieldScan (value − baseline, marginal propagated errors), and the fit.

Raises:

ValueError – If no valid regions are given; if the regions select fewer usable points (finite value, error > 0) than the baseline has free parameters (an underdetermined fit); or if the baseline fit does not converge. A failed fit never returns a (silently wrong) corrected scan.

class asymmetry.core.fitting.ScanBaselineResult(scan, model, regions, fit, captured_baseline=None)[source]

Baseline estimate and first-order correction of independent scan errors.

The correction operator includes the covariance between the baseline estimate and observations in its fitting regions. Marginal errors alone do not describe the correlations in corrected_covariance.

scan
model
regions
fit
captured_baseline = None
property success[source]
property selection[source]
property n_points[source]
property baseline[source]
evaluate_baseline(cancel_check=None)[source]

Sample the captured baseline, polling around model evaluation.

property correction_operator[source]
baseline_correction_operator(cancel_check=None)[source]

Construct the full baseline influence operator in source coordinates.

property corrected_covariance[source]
baseline_corrected_covariance(cancel_check=None)[source]

Propagate independent source errors through the full correction operator.

property corrected[source]
__init__(scan, model, regions, fit, captured_baseline=None)
asymmetry.core.fitting.fit_scan_peaks(baseline, model, *, parameters=None, initial=None, extra_starts=0, cancel_check=None)[source]

Fit peaks after subtraction, propagating the estimated baseline.

Uses independent source scan errors for Gaussian least squares. Following two-stage estimating-equation propagation (Murphy & Topel, JBES 3, 370, 1985), the covariance adds the baseline correction to the conditional Minuit covariance. The fixed-baseline limit preserves that covariance.

class asymmetry.core.fitting.ScanPeakFit(fit, covariance, effective_dof)[source]

Two-stage peak estimator with baseline-propagated covariance.

fit retains the conditional Minuit result, weighted by source errors. The propagated covariance is first order, conditional on the chosen baseline model and regions; it does not account for peak leakage or bias.

fit
covariance
effective_dof
property uncertainties[source]
property reduced_chi_squared[source]
__init__(fit, covariance, effective_dof)

Captured scalar-scan executions

asymmetry.core.fitting.scan_history stores completed baseline, peak, and RF executions separately from mutable form settings. Records retain fitted support, parameters, available covariance/statistics, computation attribution, and sampled predictions; decoding invokes no optimiser. A peak references the baseline execution used for its first-order covariance propagation. Unknown historical revisions remain unknown. Explicit refitting creates a new execution; persistence does not certify acquisition replay or add uncertainty information.

Captured Gaussian-width inputs

fit_parameter_model accepts optional width_context alongside its already transformed arrays. It checks selected known Gaussian sources at the Brandt second-moment consumers connected to the output by additive, subtractive, or quadrature branches, without applying another scale factor. Product and ratio branches remain unclassified. ParameterGroupData.width_context supplies the same contract per group for global_fit_parameter_model. Unknown context remains usable; it does not certify a convention.

The workflow fit_trend accepts y_transform=AxisTransform.custom("sqrt(2)*x") and applies that existing transform to both values and errors. The GUI supplies the actual transformed arrays and captured lens instead. Recorded results retain the context of the observations that entered the fit, so later model or lens edits do not relabel history. See Gaussian widths at second-moment consumers for the refusal and legacy-data policy.

class asymmetry.core.fitting.sc.trend_width.WidthSource(component, index, parameter, widths=(), unverified_transforms=(), conversion_expression=None)[source]

A captured component parameter and its known width conventions.

Conventions describe known inputs; unverified transforms retain an altered known origin without certifying its output as a physical width. An empty convention tuple means the source is unknown.

component
index
parameter
widths = ()
unverified_transforms = ()
conversion_expression = None
to_dict()[source]

Return a JSON-safe captured source record.

classmethod from_dict(data)[source]

Read a recorded source, preserving unknown legacy conventions.

__init__(component, index, parameter, widths=(), unverified_transforms=(), conversion_expression=None)
class asymmetry.core.fitting.sc.trend_width.TrendWidthContext(column, sources, transform=AxisTransform(kind='identity', expression=''))[source]

Source identities aligned to the actual Y array, with its captured lens.

column
sources
transform = AxisTransform(kind='identity', expression='')
classmethod for_column(column, source_maps, transform=AxisTransform(kind='identity', expression=''))[source]

Capture one column’s per-row source records at data assembly.

select(mask)[source]

Apply the numerical fit mask to its aligned source identities.

to_dict()[source]

Capture source identities and the actual Y transform.

classmethod from_dict(data)[source]

Restore captured context; absent historical attribution stays unknown.

property converts_gaussian[source]

Only the documented sqrt(2)*x expression declares this conversion.

property preserves_width[source]

Recognise identity without evaluating sampled values.

known_widths()[source]

Return the known subset without inferring facts about unknown rows.

unverified_transforms()[source]

Retain unverified changes to known widths across fitted width outputs.

effective_widths()[source]

Known inherited conventions; arbitrary transforms establish none.

validate(model)[source]

Refuse known incompatible inputs at a bare second-moment consumer.

__init__(column, sources, transform=AxisTransform(kind='identity', expression=''))

Parameter models

asymmetry.core.fitting.parameter_models.suggest_trend_seeds(model, x, y)[source]

Data-aware seed overrides for critical-temperature trend components.

The CriticalDivergence and OrderParameter components default to Tc = 10, which is far from where real datasets transition (spin-glass T_g ≈ 88 K, EuO T_c ≈ 69 K), so the trend fit will not converge until Tc is reseeded by hand. This helper derives a starting Tc from the boundary of the fitted x-range — and a cheap amplitude/baseline seed — so the fit converges out of the box.

Returns a mapping of unique parameter name (matching model.param_names, accounting for repeated-component suffixing) to suggested value. Only the parameters it is confident about are returned; the caller merges these over model.param_defaults and leaves everything else untouched. Returns an empty mapping when the model has no trend component or the data is unusable (all-NaN x). Pure and Qt-free.

The seed direction follows each model’s physics:

  • CriticalDivergence (a·|x − Tc|^{-ν} + c) diverges at Tc and is fitted with data above it, so Tc is placed just below min(x) (a small margin keeps the nearest point off the singularity) and the baseline c is seeded from the flat, far-from-Tc end of the trace.

  • OrderParameter (y0·[1 − (T/Tc)^α]^β) vanishes at Tc and is fitted with data below it, so Tc is placed just above max(x) and the amplitude y0 is seeded from the largest observed value.

  • FermiStep (A2 + (A1 − A2)/(e^{(T−Tc)/dT} + 1)) has its midpoint inside the data, so the plateaus are seeded from the coldest and warmest fifth of the trace, Tc from the half-step crossing, and dT from the 10–90 % crossings (see asymmetry.core.fitting.parameter_models._fermi_step_seeds).

Exponents (ν, β, α) keep their physical defaults.

asymmetry.core.fitting.parameter_models.suggest_model_seeds(model, x, y, yerr=None, *, known, cancel_check=None)[source]

Data-aware seed overrides keyed by unique param name (model.param_names).

known holds the values the caller already has (starting values and fixed values, by unique name). Each estimator reads its component’s share as inputs — RFResonanceMuP needs nu_RF to place its couplings — and the known values are returned as given, over any estimate.

A generic, per-component extension of suggest_trend_seeds(): for every component with a registered closed-form estimator (see asymmetry.core.fitting.parameter_models._MODEL_SEED_ESTIMATORS) the estimator runs on the finite (x, y) subset and its base-name results are mapped to the model’s unique names via the same component/mapping idiom the trend seeder uses. The critical-temperature components (CriticalDivergence/OrderParameter) are delegated to suggest_trend_seeds() and merged in, so its behaviour is preserved exactly. The components of asymmetry.core.fitting.parameter_models._GROUP_SEEDERS are each seeded as a group instead, so several resonances/half-rises start on successive features rather than all on the same one.

Only parameters the estimators are confident about, and the known values, are returned; the caller merges these over param_defaults and leaves everything else untouched. Returns just the known values when the data is unusable (fewer than two finite points). Pure and Qt-free.

ParameterCompositeModel.param_names
ParameterCompositeModel.param_defaults

Default values keyed by the composite model’s parameter names.

Parameter models

asymmetry.core.fitting.parameter_models.PARAMETER_MODEL_COMPONENTS

Registry of parameter-model components.