Fit engine
- class asymmetry.core.fitting.engine.FitEngine[source]
Bases:
objectFit μSR asymmetry data to a model function using iminuit.
Example
from asymmetry.core.fitting import FitEngine, ParameterSet, Parameter from asymmetry.core.fitting.models import MODELS engine = FitEngine() model = MODELS["ExponentialRelaxation"] # Set up parameters params = ParameterSet() params.add(Parameter(name="A0", value=0.2, min=0, max=1)) params.add(Parameter(name="lambda", value=0.5, min=0)) result = engine.fit(dataset, model.function, params) print(f"χ²ᵣ = {result.reduced_chi_squared:.3f}")
- fit(dataset, model_fn, parameters, t_min=None, t_max=None, method='migrad', minos=False, cancel_callback=None, frequency_offsets=None, cost_factory=None, migrad_kwargs=None, *, error_oversampling=1.0)[source]
Run a single-dataset fit.
To fit a bare
(t, A, σ)triple with no dataset in hand — a custom detector pairing, a background-corrected export — usefit_arrays(), which shares this method’s entire implementation.- Parameters:
dataset (MuonDataset) – The data to fit. The engine uses the dataset object’s
time,asymmetry, anderrorarrays as provided, optionally clipped only byt_min/t_max. Those arrays are in percent (0–100) by theMuonDatasetscale convention, so parameter seeds must be percent-scale too (the built-in models defaultA0to25); a fraction-scale seed against percent data converges to the wrong minimum and tripsAsymmetryScaleWarning. See “Asymmetry units across the API” in the docs.model_fn (callable) –
f(t, **params) -> array.parameters (ParameterSet) – Initial parameter values and constraints.
t_min, t_max (float, optional) – Restrict fit range.
method (str) – Minimization method (
"migrad"for gradient-based,"simplex"for Nelder-Mead).cost_factory (CostFactory, optional) – Gaussian least squares by default.
POISSON_COSTrequires raw counts and an expected-count model; its reported statistic is Cash.migrad_kwargs (dict, optional) – Forwarded to
m.migrad/m.simplexvia the shareddrive_minuit()seam (e.g.ncallto cap iterations for a cheap screening fit).Nonekeeps the historical unbounded drive.frequency_offsets (dict[str, float], optional) – Rotating-reference-frame offsets
{param: ν₀}resolved byasymmetry.core.fitting.rrf_offset.rrf_frequency_offsets(). When given, each named parameter is shifted by its offset before the model is evaluated, so the raw lab-frame data is fitted while the fitted values read as rotating-frame offsets δν (lab = δν + ν₀ viaapply_rrf_offsets()). This is the engine-level home of the RRF offset wrapper — fitting through it is bit-for-bit identical to wrappingmodel_fnwithrrf_offset_model().error_oversampling (float, optional) – For zero-padded FFT data, pass the spectrum’s padding factor
s(metadata["fourier_padding"]); native time/count fits use1.0. Interpolation adds samples without independent information. Fors > 1, the effective point count ismax(round(ndata / s), 1)anddof = max(ndata_eff - nfree, 1). The reported chi-squared ism.fval / s; reduced chi-squared uses that value and effective dof. HESSE/MINOS errors scale bysqrt(s)and covariance bys; fitted parameter values remain unchanged.FitResult.warningsrecords this approximate correction for correlated observations.
- Returns:
FitResult – Container with fit results including χ², parameters, and uncertainties.
- fit_arrays(time, asymmetry, error, model_fn, parameters, t_min=None, t_max=None, method='migrad', minos=False, cancel_callback=None, frequency_offsets=None, cost_factory=None, migrad_kwargs=None, *, error_oversampling=1.0, run_number=None)[source]
Fit Gaussian arrays using the same minimizer as
fit().Time is in microseconds. Values and their stated standard deviations share the caller’s scale; built-in μSR model seeds use percent (0–100). Arrays must be one-dimensional, non-empty and equally sized, with finite times/values and finite positive errors.
t_minandt_maxselect an inclusive fit window. Invalid observations raiseFitInputError.run_numbersupplies error-message context. Bare arrays carry no field metadata, so the fixed-frequency advisory is omitted. All remaining options and returned diagnostics followfit(). Poisson fits takePoissonCountsthroughfit_observations().
- fit_observations(observations, model_fn, parameters, *, method='migrad', minos=False, cancel_callback=None, migrad_kwargs=None)[source]
Fit a validated observation value without rechecking its input arrays.
- global_fit(datasets, model_fn, global_params, local_params, initial_params, t_min=None, t_max=None, method='migrad', max_calls=10000, migrad_iterations=5, use_simplex_rescue=True, minuit_strategy=None, minuit_tol=None, initial_step_sizes=None, minos=False, screening=False, strategy='joint', use_varpro=False, cancel_callback=None, cost_factory=None, local_param_groups=None, *, error_oversampling=1.0, observations=None)[source]
Simultaneous fit of multiple datasets with shared and local parameters.
- Parameters:
datasets – List of datasets to fit simultaneously. Their
asymmetry/errorarrays are in percent (0–100) by theMuonDatasetconvention, exactly as infit(), and every dataset must be on that one scale — concatenating a fraction-scale curve with percent-scale ones puts an unresolvable factor of 100 inside a shared amplitude.model_fn – Model function applied to each dataset.
global_params – Names of parameters shared across all datasets (e.g., [“A0”]).
local_params – Names of parameters that vary per dataset (e.g., [“lambda”]).
initial_params – Dictionary mapping dataset run_number to initial ParameterSet. Global parameters should have the same value in all sets.
t_min, t_max – Optional time range restriction applied to all datasets.
method – Minimization method (“migrad” or “simplex”).
max_calls – Maximum function evaluations for minimization. Limits runtime for large global fits.
strategy – Minimiser architecture for the shared-parameter problem.
"joint"(default) builds one Minuit problem over the globals plus every dataset’s locals — the historical, byte-for-byte path."profiled"runs an outer Minuit over the free globals only and, for each candidate global vector, solves each dataset’s locals independently (viafit()with the globals held fixed). The two share the same objective, so at the optimum they agree on values and χ²; profiled drops the per-fit Hessian from(n_global+n_local·G)²ton_global²plusGsmall block Hessians, so cost scales ~linearly inGrather than super-linearly. Profiled requires at least one free global (with none, the joint problem is already block-separable and the fast path below handles it)."least_squares"keeps the joint parameter vector but hands it toscipy.optimize.least_squares()(bounded trust-region reflective) over the residual vector rather than to Minuit over a scalar cost, declaring the problem’s block-sparse Jacobian pattern (asymmetry.core.fitting.engine._coupled_jacobian_sparsity). The coupled Jacobian is arrow-shaped — every residual depends on the globals and on exactly one run’s locals — so a finite-difference Jacobian costs aboutn_global + n_localresidual evaluations rather than one per parameter, and the trust-region solve itself stays sparse. On a wide series (a 12-run phase of ~9 free parameters per run over ~200 k points) that is the difference between minutes and seconds, and the joint Minuit problem at that width may not converge at all. The covariance is the Gauss–Newton(JᵀJ)⁻¹at the solution, which for residuals in σ units is Minuit’serrordef = 1covariance. Only the plain least-squares cost is supported, so acost_factoryraises, as doesminos=True(MINOS is a Minuit likelihood scan). The Minuit-only controls —method,migrad_iterations,use_simplex_rescue,minuit_strategy,minuit_tol,screeningandinitial_step_sizes— name algorithms and step heuristics with no trust-region counterpart and are ignored here;max_callsboundsmax_nfev. A caller’s simplex rescue therefore becomes a second trust-region solve from the rescue seed, which is still a genuine second attempt from a different start.use_varpro – Deferred — not implemented. Passing
use_varpro=Truecurrently raisesNotImplementedError; the defaultFalseis the only supported value. Variable projection (technique M) is planned as a follow-up: it would solve the parameters flagged linear in the model metadata (amplitudes, constant backgrounds; seeasymmetry.core.fitting.models.default_linear_params()) by weighted linear least-squares inside each residual and remove them from the nonlinear Minuit vector, still counting them indof/ the ICk. It is deferred because, once the"profiled"strategy has already separated the per-dataset locals, VarPro is only a constant-factor per-fit win (it does not change the G-exponent), and reproducing the current engine’s marginal parameter errors needs a final full Hessian over all parameters. The role-based linear-parameter metadata is in place for that follow-up.
- Returns:
results (dict[int, FitResult]) – Dictionary mapping run_number to individual FitResult for each dataset.
global_result (ParameterSet) – The fitted global parameters with uncertainties.
local_param_groups – Optional per-local-parameter sharing.
local_param_groups[pname]maps a dataset run number to a group key; datasets with the same key share one fitted value forpname(a third scope between fully global and fully per-dataset). Absent →pnameis per-dataset.error_oversampling (float, optional) – Correction for correlated samples (zero-padded FFT spectra), applied to every dataset’s reported
chi_squared/reduced_chi_squared/dof/uncertainties/covariance/minos_errorsthe same way asfit()— see that method’s docstring for the exact relations, the WiMDA precedent, and why fitted parameter values are unaffected. Keyword-only, default1.0(no correction); pass the common zero-padding factor of the fitted spectra (metadata["fourier_padding"]), or1.0for time-domain/count fits.
Notes
Fixed parameters (where param.fixed=True) are held constant during fitting.
- joint_fit(blocks, shared_columns, *, strategy='least_squares', method='migrad', max_calls=10000, minos=False, cancel_callback=None)[source]
Fit several blocks at once, holding the shared columns equal across them.
The generalisation of
global_fit(): where a global fit shares parameters across the runs of one series under one model, a joint fit also shares columns across series that carry different models. A sample measured through a magnetic transition needs an oscillating function below T_c and a relaxing one above it; the background, alpha or initial asymmetry is the same physical quantity in both, and only a fit that says so propagates the constraint into every uncertainty.Each block brings its own model, global/local partition, fit window and seeds;
SharedColumnnames the one fitted column two or more of them resolve a parameter from. A block that pins a shared member on a given dataset uses its own pinned value there, exactly as a global fit does for a metadata-pinned global — the constraint never overrides a measured quantity.strategyis"least_squares"(bounded sparse trust region, the default: a joint problem is wider than a single series’ and the arrow structure is what makes it affordable) or"joint"(one Minuit over the whole vector)."profiled"has no joint counterpart — it profiles the set of globals over datasets that all share one model — and raises.Raises
FitCancelledErrorthroughcancel_callbackexactly asglobal_fit()does, so a cancelled joint run records nothing.
Known histogram datasets carry RatioValidity
independently of their full display arrays. Gaussian dataset fitting selects
usable observations within the fit window; array inputs keep strict validation.
observation_report records exclusive used/undefined/zero-variance counts.
residual_time and residual_sigma describe exactly the residual support
and stated errors used by the objective, including after counts-first merging.
- class asymmetry.core.data.ratio_validity.ObservationReport(used, undefined_ratio=0, zero_variance=0)[source]
Counts within the requested Gaussian fit support; reasons are exclusive.
- used
- undefined_ratio = 0
- zero_variance = 0
- __init__(used, undefined_ratio=0, zero_variance=0)
Asymmetry global
- class asymmetry.core.fitting.asymmetry_global.GlobalFitResult(success, global_parameters, global_uncertainties=<factory>, dataset_results=<factory>, chi_squared=0.0, dof=0, reduced_chi_squared=0.0, message='')[source]
Result bundle for an asymmetry-domain global (shared-parameter) fit.
dataset_resultsis keyed by the caller’s dataset keys (positional indices for a sequence input, or the mapping keys for a mapping input). EachFitResultcarries that dataset’s fitted globals and locals (with uncertainties and its own χ²/dof), so a caller can read either the shared physics or a single dataset’s nuisances from one place.
- asymmetry.core.fitting.asymmetry_global.fit_global(datasets, model_fn, *, global_params, local_params, initial_params, t_min=None, t_max=None, method='migrad', max_calls=10000, minos=False, strategy='joint', use_varpro=False, fit_engine=None, cancel_callback=None)[source]
Fit one model across several asymmetry traces, sharing chosen parameters.
This is the asymmetry-domain global (shared-parameter) fit: one combined iminuit least-squares cost
Σ_d Σ_i ((A_i − μ_i)/σ_i)²over the datasets’.asymmetrytraces, with a single shared value perglobal_paramsentry and an independent value per dataset for eachlocal_paramsentry.It wraps
asymmetry.core.fitting.engine.FitEngine.global_fit()(the shared minimiser seam) and adds the asymmetry-domain ergonomics: datasets need not carry unique run numbers,initial_paramsmay be one broadcast seed, and the return value is aGlobalFitResultwith the shared globals, per-dataset locals, and a combined reduced χ². For the statistically-faithful low-count alternative (Cash/Poisson on grouped counts) use the count-domainfit_grouped_series(); seedocs/porting/asymmetry-domain-global-fit/for when to use which.- Parameters:
datasets – Asymmetry datasets to fit simultaneously. A sequence is keyed positionally (
0..N-1); a mapping keeps its keys. Results are keyed the same way.model_fn – Model
f(t, **params) -> arrayreturning the asymmetry/polarization for the named parameters (e.g.CompositeModel.from_expression(expr) .to_model_definition().function).global_params – Names shared across all datasets (one fitted value for the whole series).
local_params – Names estimated independently for each dataset.
initial_params – Either a single
ParameterSetbroadcast to every dataset, or a mappingdataset key -> ParameterSet. Each set must contain every name referenced byglobal_paramsandlocal_params(plus any fixed parameters the model needs). Global seed values and bounds are taken from the first dataset’s set.t_min, t_max – Optional time-range clip applied to every dataset.
method – Minimisation method (
"migrad"or"simplex").max_calls – Maximum cost-function evaluations.
minos – Run MINOS for asymmetric intervals on top of the symmetric HESSE errors.
strategy – Minimiser architecture, forwarded to
global_fit()."joint"(default) is the historical single-Minuit solver;"profiled"runs an outer Minuit over the shared globals only with per-dataset local solves, so per-fit cost scales ~linearly in the number of datasets (technique L). Both converge to the same minimum; profiled reports conditional local errors (globals pinned) while its shared-global errors are marginal.use_varpro – Deferred — not implemented. Forwarded to the engine, where
use_varpro=Truecurrently raisesNotImplementedError; only the defaultFalseis supported. Variable projection (solving linear parameters — amplitudes, constant backgrounds — by least-squares inside the objective) is a planned follow-up; seeglobal_fit()for why it is deferred (constant-factor-only once the profiled strategy separates the per-dataset locals, and marginal-error matching needs a final full Hessian).fit_engine – Optional
FitEngineto reuse; a fresh one is created otherwise.cancel_callback – Cooperative cancel probe polled inside the cost function; a truthy return raises
FitCancelledError.
- Returns:
GlobalFitResult – Shared global estimates and uncertainties, per-dataset results (keyed by the caller’s dataset keys), and the combined reduced χ².
Notes
A single-dataset call behaves like an ordinary single fit: the combined reduced χ² reduces exactly to that dataset’s reduced χ².
Engine
- class asymmetry.core.fitting.engine.AsymmetryScaleWarning[source]
Emitted when fit seeds and data appear to be on different asymmetry scales.
The classic trap: fraction-scale seeds are fitted to a
MuonDatasetwhoseasymmetryis on the percent scale (×100). The fit either converges to a degenerate amplitude or to the wrong minimum. Seeasymmetry.core.data.dataset.MuonDatasetand itsasymmetry_percent/asymmetry_fractionaccessors.
- class asymmetry.core.fitting.engine.FitCancelledError[source]
Raised when a fit is cancelled cooperatively via a
cancel_callback.Mirrors
MaxEntCancelledError. A cancelled fit records no result: the partially-minimised state is discarded entirely, so callers must let this propagate and not pack aFitResultfrom it.
- class asymmetry.core.fitting.engine.FixedFrequencyFieldMismatchWarning[source]
Emitted when a fit pins a precession frequency far from γ_μ·B(field).
The TF trap: a transverse-field oscillation is fitted with its
frequencyparameter fixed (Parameter.fixed=True) to a value that disagrees with the Larmor frequencyν = γ_μ B / 2πimplied by the run’sfieldmetadata. Pinning the line away from its true position pushes the misfit into the damping term, inflating the fitted Gaussiansigma(~8% on a vortex-state superconductor, where the diamagnetic shift moves the line below T_c). Lettingfrequencyfloat removes the bias. Seeasymmetry.core.fourier.units.gauss_to_mhz()for the conversion and the “transverse-field frequency” cookbook entry.
- asymmetry.core.fitting.engine.POISSON_COST
Cash statistic on raw Poisson counts — the count-domain modes’ default, extended to grouped fits via the cost-factory seam. The count-domain and grouped setups behind it read
run.histograms(the deadtime frame normalisation takes its bin width off the first detector), so this cost needs the full record.
One fitted column held equal across two or more blocks.
membersmaps a block key to the parameter name that block spells the quantity with, because the whole point of sharing across series is that two models may call the same physics different things (A_bgin one,baselinein the other). The column carries its own seed and bounds: the shared value is a new fitted quantity, not either series’ row.
- asymmetry.core.fitting.engine.drive_minuit(m, *, method='migrad', migrad_kwargs=None, run_hesse=True, explicit_hesse=False, minos=False, minos_parameters=None)[source]
Drive a constructed, limit-set Minuit through minimisation and report MINOS.
mmust already have its cost function, parameter names, and limits set; this function owns only the post-construction drive.migrad_kwargsis forwarded tom.migrad/m.simplexso each caller keeps its own ncall/iterate/use_simplex tuning.explicit_hesseevaluates the full Hessian after minimisation, before optional MINOS; otherwise MIGRAD’s covariance estimate is retained.When
minosis true and the fit is valid,m.minos()scans every free parameter (or justminos_parameters) and the signed asymmetric offsets{name: (lower, upper)}(lower < 0 < upper) are returned for every scan that succeeded (MError.is_valid). A whole-scan failure or any parameter whose individual scan is invalid simply yields no asymmetric entry for it — the caller keeps the symmetric HESSE σ for that parameter. ReturnsNonewhen MINOS was not requested, the fit is invalid, or no scan produced a valid interval.
Fit quality
- asymmetry.core.fitting.fit_quality.assess_fit_quality(chi_squared, dof, confidence=0.95)[source]
Assess a fitted χ² against the chi-squared distribution.
- Parameters:
chi_squared – The (weighted) sum of squared normalised residuals at the minimum.
dof – Degrees of freedom ν = N − N_free. With ν < 1 no verdict is possible.
confidence – Two-sided confidence level R; clamped to [0.5, 0.999].