Fit engine

class asymmetry.core.fitting.engine.FitEngine[source]

Bases: object

Fit μ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 — use fit_arrays(), which shares this method’s entire implementation.

Parameters:
  • dataset (MuonDataset) – The data to fit. The engine uses the dataset object’s time, asymmetry, and error arrays as provided, optionally clipped only by t_min/t_max. Those arrays are in percent (0–100) by the MuonDataset scale convention, so parameter seeds must be percent-scale too (the built-in models default A0 to 25); a fraction-scale seed against percent data converges to the wrong minimum and trips AsymmetryScaleWarning. 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_COST requires raw counts and an expected-count model; its reported statistic is Cash.

  • migrad_kwargs (dict, optional) – Forwarded to m.migrad/m.simplex via the shared drive_minuit() seam (e.g. ncall to cap iterations for a cheap screening fit). None keeps the historical unbounded drive.

  • frequency_offsets (dict[str, float], optional) – Rotating-reference-frame offsets {param: ν₀} resolved by asymmetry.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 = δν + ν₀ via apply_rrf_offsets()). This is the engine-level home of the RRF offset wrapper — fitting through it is bit-for-bit identical to wrapping model_fn with rrf_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 use 1.0. Interpolation adds samples without independent information. For s > 1, the effective point count is max(round(ndata / s), 1) and dof = max(ndata_eff - nfree, 1). The reported chi-squared is m.fval / s; reduced chi-squared uses that value and effective dof. HESSE/MINOS errors scale by sqrt(s) and covariance by s; fitted parameter values remain unchanged. FitResult.warnings records 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_min and t_max select an inclusive fit window. Invalid observations raise FitInputError.

run_number supplies error-message context. Bare arrays carry no field metadata, so the fixed-frequency advisory is omitted. All remaining options and returned diagnostics follow fit(). Poisson fits take PoissonCounts through fit_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/error arrays are in percent (0–100) by the MuonDataset convention, exactly as in fit(), 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 (via fit() 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)² to n_global² plus G small block Hessians, so cost scales ~linearly in G rather 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 to scipy.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 about n_global + n_local residual 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’s errordef = 1 covariance. Only the plain least-squares cost is supported, so a cost_factory raises, as does minos=True (MINOS is a Minuit likelihood scan). The Minuit-only controls — method, migrad_iterations, use_simplex_rescue, minuit_strategy, minuit_tol, screening and initial_step_sizes — name algorithms and step heuristics with no trust-region counterpart and are ignored here; max_calls bounds max_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=True currently raises NotImplementedError; the default False is 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; see asymmetry.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 in dof / the IC k. 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 for pname (a third scope between fully global and fully per-dataset). Absent → pname is 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_errors the same way as fit() — see that method’s docstring for the exact relations, the WiMDA precedent, and why fitted parameter values are unaffected. Keyword-only, default 1.0 (no correction); pass the common zero-padding factor of the fitted spectra (metadata["fourier_padding"]), or 1.0 for 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; SharedColumn names 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.

strategy is "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 FitCancelledError through cancel_callback exactly as global_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
property omitted[source]
to_dict()[source]
summary()[source]
__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_results is keyed by the caller’s dataset keys (positional indices for a sequence input, or the mapping keys for a mapping input). Each FitResult carries 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’ .asymmetry traces, with a single shared value per global_params entry and an independent value per dataset for each local_params entry.

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_params may be one broadcast seed, and the return value is a GlobalFitResult with 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-domain fit_grouped_series(); see docs/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) -> array returning 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 ParameterSet broadcast to every dataset, or a mapping dataset key -> ParameterSet. Each set must contain every name referenced by global_params and local_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=True currently raises NotImplementedError; only the default False is supported. Variable projection (solving linear parameters — amplitudes, constant backgrounds — by least-squares inside the objective) is a planned follow-up; see global_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 FitEngine to 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 MuonDataset whose asymmetry is on the percent scale (×100). The fit either converges to a degenerate amplitude or to the wrong minimum. See asymmetry.core.data.dataset.MuonDataset and its asymmetry_percent / asymmetry_fraction accessors.

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 a FitResult from 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 frequency parameter fixed (Parameter.fixed=True) to a value that disagrees with the Larmor frequency ν = γ_μ B / 2π implied by the run’s field metadata. Pinning the line away from its true position pushes the misfit into the damping term, inflating the fitted Gaussian sigma (~8% on a vortex-state superconductor, where the diamagnetic shift moves the line below T_c). Letting frequency float removes the bias. See asymmetry.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.

class asymmetry.core.fitting.engine.SharedColumn(name, members, value, min=-inf, max=inf)[source]

One fitted column held equal across two or more blocks.

members maps 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_bg in one, baseline in 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.

m must already have its cost function, parameter names, and limits set; this function owns only the post-construction drive. migrad_kwargs is forwarded to m.migrad/m.simplex so each caller keeps its own ncall/iterate/use_simplex tuning. explicit_hesse evaluates the full Hessian after minimisation, before optional MINOS; otherwise MIGRAD’s covariance estimate is retained.

When minos is true and the fit is valid, m.minos() scans every free parameter (or just minos_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. Returns None when 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].

Information criteria

asymmetry.core.fitting.information_criteria.information_weights(scores)[source]

Normalised exp(−Δ/2) weights; unavailable scores receive zero weight.

Likelihood

class asymmetry.core.fitting.likelihood.FitInputError[source]

An observation cannot be used under the requested likelihood.

class asymmetry.core.fitting.likelihood.PoissonCounts(time, counts, source, run_number=None, t_min=None, t_max=None)[source]

Owned read-only integer counts from an uncorrected acquisition.