Composite models

class asymmetry.core.fitting.composite.ComponentDefinition(name, description, label, use_when, function, param_names, param_defaults, param_info, param_kinds, formula_template, latex_equation='', category='General', domain='time', fixed_params=(), user=False, missing=False, knight_observable=None, field_geometries=frozenset({FieldGeometry.LF, FieldGeometry.TF, FieldGeometry.ZF}), physics_classes=frozenset({PhysicsClass.CUSTOM}), cost=ComputationalCost.MODERATE)[source]

Bases: object

Descriptor for a baseline-free component function.

name
description
label

Short readable name shown in pickers and docs (e.g. “Dynamic Gaussian KT”).

use_when

One line on when the component applies (e.g. “Fluctuating Gaussian fields”).

function
param_names
param_defaults
param_info
param_kinds

What each parameter measures; one entry per name in param_names.

formula_template
latex_equation = ''
category = 'General'
domain = 'time'
fixed_params = ()

Parameters that should start fixed in a fit (e.g. a nuclear spin the model is piecewise-constant in, or a hyperfine constant that is known). The GUI pre-checks the fix box; the user can always free them.

user = False

True for components registered through the user-function facade (asymmetry.core.fitting.user_functions). Provenance is keyed off this flag — picker badges and the docs-enforcement exemptions — never off name lists.

missing = False

True for the per-instance placeholder definitions that stand in for a user component referenced by a project but not currently registered. Placeholders evaluate to zero and are never inserted into COMPONENTS.

knight_observable = None

For a precession component whose fitted value is the local field/frequency at the muon (so it can be converted to a Knight shift), the name of that parameter ("frequency" or "field"). None for everything else — crucially including muonium components, whose field parameter is the applied field fed into the Breit–Rabi levels, not a local field.

field_geometries = frozenset({FieldGeometry.LF, FieldGeometry.TF, FieldGeometry.ZF})

Applied-field geometries the component is physically meaningful for. The fit wizard uses this to drop components that cannot apply to a run’s geometry. Defaults to all three (no restriction).

physics_classes = frozenset({PhysicsClass.CUSTOM})

Physics-class tags for wizard scoping. CUSTOM is the untagged sentinel default for user functions; every built-in must override it with real class(es) — enforced by tests/test_component_tags.py.

cost = 'moderate'

Relative evaluation-cost hint for tiered wizard screening (the wizard trials cheap components before expensive ones).

__init__(name, description, label, use_when, function, param_names, param_defaults, param_info, param_kinds, formula_template, latex_equation='', category='General', domain='time', fixed_params=(), user=False, missing=False, knight_observable=None, field_geometries=frozenset({FieldGeometry.LF, FieldGeometry.TF, FieldGeometry.ZF}), physics_classes=frozenset({PhysicsClass.CUSTOM}), cost=ComputationalCost.MODERATE)
class asymmetry.core.fitting.composite.CompositeModel(component_names, operators=None, open_parentheses=None, close_parentheses=None, fraction_groups=None, *, allow_missing=False, time_response=TimeResponse(mode='off', separation_us=0.0))[source]

Bases: object

A flat composite model built from baseline-free components.

allow_missing lets a model materialise even when some component names are not registered (see placeholder_component_definition()); callers that fit or edit the model must check missing_component_names.

__init__(component_names, operators=None, open_parentheses=None, close_parentheses=None, fraction_groups=None, *, allow_missing=False, time_response=TimeResponse(mode='off', separation_us=0.0))[source]
classmethod from_expression(expression)[source]

Construct a CompositeModel from a component-name expression.

expression_tree()[source]

Return the model’s expression tree (see build_expression_tree()).

The nodes are frozen dataclasses addressing components by index, so a caller can walk the products and sums the expression denotes.

parameter_mapping()[source]

Return per-component maps of local parameter name → unique fit name.

One dict per entry of components, in the same order. Copies are returned so callers (e.g. the RRF frequency-offset wrapper) cannot mutate the model’s internal mapping.

parameter_identities()[source]

Map every unique parameter name to what that parameter is.

The identity names the component instance (or fraction group) a parameter belongs to, independent of the collision-driven spelling the model gave it, so parameter state can follow the component across a model edit (see asymmetry.core.fitting.parameter_carry). Suppressed unit amplitudes are not parameters and are excluded; the keys are param_names, in the same order.

parameter_kinds()[source]

Map every unique parameter name to the kind its component declares.

A fraction group’s total is an AMPLITUDE (told from a component’s own amplitude by its GroupAmplitude identity) and its free weights are FRACTION. The keys are param_names, in order.

scale_parameter_name(component_index)[source]

Return the fitted name of a component’s scale, or None.

None means the component owns no scale under the amplitude policy: either it declares no scaling parameter at all, or the policy suppressed its amplitude because another factor of the same product — or, inside a fraction group, the group amplitude — carries that product’s single scale. So walking a product’s leaves through this method yields exactly the one name that scales the product (see CompositeModel._suppressed_scaling_parameters).

knight_observable_params()[source]

Map fitted parameter name → kind for Knight-convertible components.

For each component whose value is a local precession field/frequency (ComponentDefinition.knight_observable set — Oscillatory/Bessel give "frequency", OscillatoryField gives "field"), return its unique fitted parameter name pointing at that kind. Components whose field is the applied field (muonium TF) are excluded, so a Knight-shift conversion never mistakes the applied field for a local one.

component_expression_string()[source]

Return the builder-facing expression using component names.

fraction_weights(values)[source]

Return {name: weight} for every fraction term across all groups.

Both the n-1 free parameters (keyed by their real names, carrying the clamped [0, 1] value) and the derived remainder of each group (keyed by its synthesized display name, carrying 1 - Σ free) appear. A group is skipped entirely when any of its free parameters is missing from values, so callers never receive a partial partition.

normalized_parameter_values(values)[source]

Return a copy with free fraction parameters clamped into [0, 1].

Under the n-1 scheme the fitted values are already the physical free weights, so this only clamps each free fraction into its [0, 1] range (leaving every other entry untouched). Kept because callers rely on it to present display-ready values.

fraction_parameter_groups()[source]

Return the free fraction-parameter names grouped by fraction group.

Each group contributes its n-1 free parameter names; the remainder term has no parameter and is not listed here (see derived_fraction_names() for its display label).

derived_fraction_names()[source]

Return one synthesized display name per group for its remainder term.

These are the f_<Component> labels of each group’s last additive term — display-only names (no fitted parameter) that never collide with a real parameter name. Ordered to match fraction_groups.

derived_fraction_terms()[source]

Return (display_name, group) for each group’s remainder term.

Pairs each derived remainder name with the fraction group it labels, so a caller can place the remainder row and know which group it belongs to.

with_default_fraction_groups()[source]

Return a copy with a top-level additive fraction group when suitable.

domains()[source]

Return the set of analysis domains of the model’s components.

A well-formed model has a single domain ({"time"} or {"frequency"}); a mixed set indicates a model that combines time- and frequency-domain components (e.g. restored from a project saved before domain filtering existed) and should be surfaced to the user rather than silently fitted.

Missing-component placeholders are skipped: their domain is unknowable, and the missing-ness itself is surfaced separately (fit blocking via missing_component_names).

fixed_by_default_params()[source]

Unique parameter names that should start fixed in a fit.

Collected from each component’s ComponentDefinition.fixed_params through the model’s parameter mapping (so duplicated components yield their indexed names, e.g. J_spin_2).

function(t, **kwargs)[source]

Evaluate the composite function with standard arithmetic precedence.

additive_component_indices()[source]

Return component indices that contribute in additive (+) form.

This includes the first component and any component joined with a + operator. Components joined with -, *, or / are excluded because their visual contribution is not an additive area.

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

Evaluate individual component curves.

Parameters:
  • t (array-like) – Time points where components are evaluated.

  • additive_only (bool, optional) – If True, only return additive components (first component and components joined with + operators).

  • **kwargs (float) – Composite-model parameters using unique parameter names.

formula_string()[source]

Describe the prediction, including consumed response settings.

latex_terms()[source]

Return the model as a list of typeset (mathtext) additive terms.

Splits at top-level +/- operators; each term carries its separator (”” for the first, “ + “/” - “ otherwise) and the sole fraction group its component range intersects (or None). Never raises and never returns an empty list for a valid model — a single multiplicative chain yields one term.

latex_string()[source]

Return the whole model as one mathtext string.

The concatenation "".join(sep + latex) over latex_terms().

to_model_definition(name='Composite')[source]

Create a ModelDefinition-compatible wrapper for the fit engine.

with_time_response(response)[source]

Return a source model snapshot with the supplied fixed time response.

to_dict()[source]

Return a JSON-serializable representation of the model.

classmethod from_dict(data, *, allow_missing=False)[source]

Construct a CompositeModel from serialized data.

With allow_missing=True, component names that are not registered materialise as named zero-valued placeholders instead of raising — the degrade path for projects referencing user functions that are not installed in this session (the original names round-trip unchanged through to_dict()).

Note

The available time-domain component registry is exposed as asymmetry.core.fitting.composite.COMPONENTS.

Diffusive longitudinal-field relaxation model.

Implements field-dependent relaxation rates for diffusive spin excitations:

  • lambda(B_LF) = lambda_diff(B_LF) + lambda_0D

  • lambda_diff(B_LF) = (C^2 / 4) * J(omega)

  • omega = gamma_e * B_LF

The diffusion autocorrelation uses the nD form from Pratt (J. Phys.: Conf. Ser. 2462 012038, 2023), with n in {1, 2, 3}:

S_nD(t) = [exp(-2 D_nD t) I0(2 D_nD t)]^n

[exp(-2 D_perp t) I0(2 D_perp t)]^(3-n)

Numerics

The spectral density is a one-sided cosine transform:

J(omega) = 2 * integral_0^inf S(t) cos(omega t) dt

Two evaluation strategies are available:

  • A fast, vectorized Filon transform (the default): S(t) is sampled once on a shared log-spaced grid up to a finite t_max chosen from the diffusion rates, and J(omega) is evaluated for the whole omega vector at once. Within each grid segment S(t) is treated as piecewise linear and the oscillatory cos(omega t) factor is integrated analytically. Because the oscillation is handled in closed form per segment, the grid only has to resolve the smooth envelope S(t) – not the (arbitrarily fast) cosine – so a modest grid stays accurate even when omega is very large. See _spectral_density_fast for the design notes and accuracy bounds.

  • The original scalar scipy.integrate.quad cosine-weighted integrator, retained as _spectral_density_quad. It is used as a parity reference in the tests, as an automatic fall-back for the very-slow-diffusion corner where the fixed grid would need an impractically large t_max (see _DIFFUSION_MIN_RATE_FLOOR), and as a global escape hatch when the environment variable ASYMMETRY_DIFFUSION_QUAD is set to a truthy value.

A finite upper limit t_max is chosen adaptively from the diffusion rates to provide stable and reproducible behavior suitable for GUI fitting workflows.

asymmetry.core.fitting.diffusion.autocorrelation_nD(t, D_nD, D_perp=0.0, n=2)[source]

Return S_nD(t) for n-dimensional diffusion.

Parameters:
  • t – Time in microseconds.

  • D_nD – In-plane diffusion rate in us^-1.

  • D_perp – Perpendicular diffusion rate in us^-1.

  • n – Dimensionality, one of 1, 2, or 3.

asymmetry.core.fitting.diffusion.spectral_density(omega, D_nD, D_perp=0.0, n=2)[source]

Return one-sided cosine spectral density J(omega).

Uses the convention J(omega) = 2 * integral_0^inf S(t) cos(omega t) dt. For omega = 0, this function returns +inf because the integral diverges for algebraic long-time tails relevant to low-dimensional diffusion.

asymmetry.core.fitting.diffusion.lambda_diff(B_LF, C, D_nD, D_perp=0.0, n=2)[source]

Return field-dependent diffusive relaxation rate lambda_diff(B_LF).

asymmetry.core.fitting.diffusion.lambda_total(B_LF, C, D_nD, lambda_0D=0.0, D_perp=0.0, n=2)[source]

Return total LF relaxation lambda(B_LF) including field-independent term.

asymmetry.core.fitting.diffusion.is_scipy_available()[source]

Return whether SciPy is available.

With eager imports, SciPy is now a hard requirement loaded at module import. This function always returns True; it exists for backward compatibility.

Muon-fluorine models

Dipolar Hamiltonian helpers for muon-fluorine spin systems.

asymmetry.core.fitting.muon_fluorine.dipolar.omega_d_mu_f_rad_per_us(distance_angstrom)[source]

Return mu-F dipolar angular frequency in rad/us.

asymmetry.core.fitting.muon_fluorine.dipolar.omega_d_f_f_rad_per_us(distance_angstrom)[source]

Return F-F dipolar angular frequency in rad/us.

asymmetry.core.fitting.muon_fluorine.dipolar.omega_dipolar_rad_per_us(distance_angstrom, gamma_i_mhz_per_t, gamma_j_mhz_per_t)[source]

Return dipolar angular frequency in rad/us for a spin pair.

asymmetry.core.fitting.muon_fluorine.dipolar.r_mu_f_from_omega_d(omega_d_rad_per_us)[source]

Invert omega_d_mu_f_rad_per_us(): mu-F distance in angstrom.

omega_d scales as r^-3, so r = (omega_d(1 A) / omega_d)^(1/3).

asymmetry.core.fitting.muon_fluorine.dipolar.three_spin_hamiltonian_rad_per_us(coupling_mu_f1, coupling_mu_f2, coupling_f1_f2, n_mu_f1, n_mu_f2, n_f1_f2)[source]

Construct the full 8x8 dipolar Hamiltonian (angular-frequency units).

Muon-fluorine polarization functions for entangled spin states.

asymmetry.core.fitting.muon_fluorine.polarization.mu_f_polarization(t, r_muF)[source]

Analytical mu-F longitudinal polarization, D_z(t), for one fluorine.

asymmetry.core.fitting.muon_fluorine.polarization.linear_fmuf_polarization(t, r_muF)[source]

Analytical collinear F-mu-F polarization from the classic ionic-crystal model.

asymmetry.core.fitting.muon_fluorine.polarization.dynamic_fmuf_polarization(t, r_muF, nu)[source]

Strong-collision dynamicized linear F-mu-F polarization (WiMDA dyn F-u-F).

The static collinear F-mu-F polarization G_s (eqn 4.81 of Blundell, De Renzi, Lancaster & Pratt, Muon Spectroscopy, OUP 2022) dynamicized by the strong-collision integral equation (eqn 5.30):

G_d(t) = e^{-nu t} G_s(t) + nu * integral_0^t G_d(t - t’) e^{-nu t’} G_s(t’) dt’

modelling muon hopping away from the F-mu-F site (or fluctuation of the coupling) at rate nu (µs⁻¹). Because G_s is a constant plus three cosines, the equation has an exact closed-form solution: a sum of seven exponentials whose rates and weights come from a 7x7 eigenproblem (asymmetry.core.fitting.models._strong_collision_modes). It is evaluated directly at the requested times – no integration grid, cache, call-count-dependent accuracy or fast-fluctuation crossover – and is valid at every rate: nu = 0 reduces exactly to the static linear_fmuf_polarization(), and for nu >> omega_d it tends to the motional-narrowing exponential exp(-2 omega_d^2 t / nu) (with the Abragam-form quadratic onset at short times). WiMDA instead integrates on a user-visible tmax grid and jumps to the bare narrowing exponential at a fixed rate, leaving a discontinuity in the model.

asymmetry.core.fitting.muon_fluorine.polarization.general_fmuf_polarization(t, r1, r2, theta)[source]

Numerical powder-averaged polarization for a general F-mu-F geometry.

The geometry is parameterized by two mu-F distances (r1, r2) in Angstrom and a bond angle theta in degrees. The eigenspectrum for each geometry is cached to keep fitting workloads feasible when the same geometry is re-evaluated.

asymmetry.core.fitting.muon_fluorine.polarization.fmuf_triangle_polarization(t, r_muF, r3, phi3)[source]

Powder-averaged polarization for F-mu-F plus a third fluorine (16-dim).

A collinear F-mu-F pair (both fluorines at r_muF, as in linear_fmuf_polarization()) plus a third fluorine at distance r3 and angle phi3 (degrees) from the F-mu-F axis, solved exactly in the 16-dimensional muon + 3F Hilbert space with all pairwise dipolar couplings (mu-F and F-F) and a proper powder average.

This supersedes WiMDA’s F-u-F-F ZF PCR, which neglects the F-F couplings and approximates the powder average by (P_z + 2 P_x)/3 for a single crystal orientation pair; see docs/porting/wimda-fit-function-parity/comparison.md. As r3 -> infinity the result approaches the linear F-mu-F polarization.

Fixed time response

class asymmetry.core.fitting.time_response.TimeResponse(mode='off', separation_us=None)[source]

Fixed equal-incident double-delta response, with midpoint origin in µs.

off preserves the supplied callable’s full domain. double_delta evaluates only live ages, including age zero. Separation is supplied, never a fit parameter. Dormant off inputs are unused and canonicalised.

mode = 'off'
separation_us = None
to_dict()[source]

Canonical consumed settings; off has no active separation.

classmethod from_dict(payload)[source]

Restore optional authored settings; absent historical settings are off.

evaluate(source, time, **parameters)[source]

Evaluate the complete source at each live age and normalise survival.

A point before the first birth has no defined normalised prediction. Subtracting the latest live birth in the exponent cancels the common survival factor without underflow at late observation times.

curve_times(t_min, t_max, points)[source]

Sample only the defined prediction interval for a display overlay.

Literal window edges need not coincide with retained bin centres. Clipping extrapolation to the first birth does not omit observations; evaluate() still diagnoses unsupported requested model points.

compose(source)[source]

Wrap a fractional or percent source callable without changing scale.

__init__(mode='off', separation_us=None)

The optional CompositeModel.time_response setting round-trips with the model. asymmetry.core.fitting.composite.CompositeModel.with_time_response() creates a new snapshot. See Fixed double-pulse prediction for normalisation, origin, and conditional errors.

Composite

CompositeModel.components
CompositeModel.param_names
CompositeModel.fraction_groups

Expression tree

asymmetry.core.fitting.expression_tree.build_expression_tree(component_count, operators, open_parentheses, close_parentheses, fraction_groups=())[source]

Return the expression tree denoted by a composite model’s flat form.

*// bind tighter than +/-; parentheses group. The result is normalised so that only the structure survives: a group holding a single node is that node (redundant parentheses vanish), a product factor that is itself a product is flattened into its parent, and a plain sum term that is itself a plain sum is flattened. A fraction-group sum keeps its own terms.

The caller has already validated the parenthesis balance, and the fraction groups are the ones requested: a group is tagged onto the sum of the parenthesis whose span it names, and asymmetry.core.fitting.composite.CompositeModel._validate_fraction_groups then reads the tagged sums back to accept or reject the request.

User functions

asymmetry.core.fitting.user_functions.register_parameter_component(name, function, param_names, *, description, formula_template, param_defaults=None, latex_equation='', applicability='', references=(), scopes=('common',), fwhm_factor=None)[source]

Register a user parameter-vs-x trend component.

function must be vectorised: called as function(x, **params) with x the trend variable (temperature, field, …) and one keyword per entry of param_names. scopes restricts where the component is offered (subset of {"common", "field", "temperature"}).

Returns the registered ParameterModelComponentDefinition (flagged user=True). Raises UserFunctionError on any validation failure, in which case no registry is modified.

class asymmetry.core.fitting.user_functions.UserFunctionError[source]

A user-function registration failed validation.

Raised at registration (load) time with a message naming the offending function and rule, so plugin authors get actionable errors instead of mid-fit failures.

CompositeModel.missing_component_names