Knight shift

Convert fitted oscillation components to the muon Knight shift and fit its angular dependence. See Knight shift for the physics and the GUI workflow.

Muon Knight-shift conversion from fitted precession frequencies.

The Knight shift is the relative frequency shift of the muon precession away from the free-muon Larmor frequency of the applied field:

K = (ν_µ − ν_ref) / ν_ref (dimensionless)

with two reference conventions (both supported here):

  • Applied field — ν_ref = γ_µ · B_ext, the free-muon Larmor frequency of the applied field. This needs no measured reference line, so it is the default for low-background systems. (Amato, Intro to MuSR, Eq. 5.54; Blundell, Muon Spectroscopy, Eq. 16.14: K = (B_µ − B_ext)·B_ext / B_ext².)

  • Designated component — ν_ref is the fitted frequency of a reference oscillation component measured in the same fit (e.g. a diamagnetic line). The two frequencies are then correlated, so the covariance is carried through the error propagation.

This module computes the directly-measured K_exp. The Lorentz/demagnetizing correction to the intrinsic K_µ (Amato Eqs. 5.59–5.60) needs sample geometry and susceptibility and is intentionally out of scope.

Knight shifts span a wide range — tens of ppm for diamagnets up to a few percent for paramagnets (Amato p.194) — so resolve_auto_unit() picks a sensible display unit from the data.

asymmetry.core.fitting.knight_shift.MUON_LARMOR_MHZ_PER_G = 0.013553880950000001

Free-muon Larmor frequency per unit applied field, γ_µ/(2π) in MHz/G (≈ 0.013554 MHz/G). Derived from the single γ_µ·B conversion in asymmetry.core.fitting.spectral so the Larmor slope cannot drift from the frequency-domain field axis.

asymmetry.core.fitting.knight_shift.larmor_frequency_mhz(field_gauss)[source]

Free-muon Larmor frequency (MHz) for an applied field in Gauss.

asymmetry.core.fitting.knight_shift.knight_shift(nu, nu_ref, *, sigma_nu=0.0, sigma_ref=0.0, cov=0.0)[source]

Knight shift K = ν/ν_ref − 1 and its 1σ uncertainty.

cov is the covariance between nu and nu_ref — non-zero only when both are fitted in the same fit (the designated-component reference). For the applied-field reference nu_ref = γ_µ·B is treated as exact, so the caller leaves sigma_ref and cov at zero.

Returns (nan, nan) when nu_ref is zero (no reference to shift against). The error propagation is the standard first-order expansion of the ratio:

σ_K² = σ_ν²/ν_ref² + ν²·σ_ref²/ν_ref⁴ − 2·ν·cov/ν_ref³

class asymmetry.core.fitting.knight_shift.KnightShiftUnit(*values)[source]

Bases: Enum

Display unit for a Knight shift (stored internally as a fraction).

FRACTION = 'fraction'
PPM = 'ppm'
PERCENT = 'percent'
AUTO = 'auto'
asymmetry.core.fitting.knight_shift.resolve_auto_unit(values)[source]

Pick ppm vs percent for a set of Knight shifts (fractions).

Returns KnightShiftUnit.PPM when the largest finite \(|K|\) is below asymmetry.core.fitting.knight_shift._AUTO_PPM_MAX, else KnightShiftUnit.PERCENT. An empty or all-non-finite set defaults to ppm.

asymmetry.core.fitting.knight_shift.concrete_unit(unit, values)[source]

Resolve AUTO against the data; pass concrete units through unchanged.

asymmetry.core.fitting.knight_shift.scale_for_unit(unit)[source]

Factor to multiply an internal fraction by for display in unit.

asymmetry.core.fitting.knight_shift.label_for_unit(unit)[source]

Short unit suffix for an axis/legend label (empty for a bare fraction).

asymmetry.core.fitting.knight_shift.REFERENCE_APPLIED_FIELD = 'applied_field'

Reference conventions for the Knight shift.

class asymmetry.core.fitting.knight_shift.KnightShiftConfig(enabled=False, reference_mode='applied_field', reference_component=None, unit=KnightShiftUnit.AUTO, components=<factory>)[source]

Bases: object

User configuration for converting fitted frequencies to Knight shifts.

reference_mode is "applied_field" (ν_ref = γ_µ·B, needs no reference line) or "component" (ν_ref is reference_component’s fitted frequency). components lists the oscillation-frequency parameter names to convert; an empty tuple means “all discovered components”. unit is the display unit (the conversion is stored internally as a dimensionless fraction).

enabled = False
reference_mode = 'applied_field'
reference_component = None
unit = 'auto'
components
to_dict()[source]
classmethod from_dict(data)[source]
__init__(enabled=False, reference_mode='applied_field', reference_component=None, unit=KnightShiftUnit.AUTO, components=<factory>)
class asymmetry.core.fitting.knight_shift.ClogstonJaccarinoResult(slope, intercept, slope_err, intercept_err, n)[source]

Bases: object

Linear K-vs-χ fit (Clogston–Jaccarino), with temperature implicit.

slope is dK/dχ — proportional to the muon hyperfine coupling at the site — and intercept is the χ-independent (orbital/diamagnetic) shift K0. *_err are 1σ uncertainties; n is the number of points used.

slope
intercept
slope_err
intercept_err
n
__init__(slope, intercept, slope_err, intercept_err, n)
asymmetry.core.fitting.knight_shift.clogston_jaccarino_fit(chi, knight, sigma_knight=None)[source]

Weighted linear fit of Knight shift vs susceptibility (API-only).

Fits K = slope·χ + intercept with temperature as the implicit parameter — the Clogston–Jaccarino construction — where the slope dK/dχ measures the muon hyperfine coupling and the intercept the χ-independent shift. Points with a non-finite χ, K, or σ are dropped; sigma_knight (if given) weights the fit by 1/σ² (else unit weights). Raises ValueError with fewer than two points or no spread in χ (the slope is then undetermined).

There is no GUI entry point because the muon experiment does not measure χ; pair the trended Knight shift (exported per Knight shift) with an independent susceptibility and call this directly.

Joint K(θ) fit with per-angle component assignment.

Fitting each raw-labelled Knight-shift component trace independently against angle breaks at crossings, where the underlying grouped fit swaps which physical site a label refers to. This module fits N angle-dependent curves jointly and, at each angle, assigns that angle’s N measured component values to the curves they best match (a one-to-one optimal assignment). Each physical site is then followed continuously through crossings, and the assignment realigns the component identity.

The procedure is a classification-EM / alternating least squares: hold the assignment, fit each curve to its assigned points; then hold the curves, reassign each angle’s points to curves by minimum weighted residual (Hungarian). Because the objective is non-convex (label switching), a few seeds are tried and the lowest-χ² solution kept.

Pure/deterministic — no Qt. Reuses the K(θ) basis models and fit_parameter_model.

asymmetry.core.fitting.angular_assignment.ANGULAR_MODELS = ('KnightAnisotropy', 'AngularCos2', 'AngularFourier2')

K(θ) basis models eligible for the joint fit (angle-scoped, Phase 5/6).

class asymmetry.core.fitting.angular_assignment.AngularAssignmentAlternative(assignment, curves, total_chi_squared, converged)[source]

Bases: object

A near-degenerate runner-up assignment kept for discrimination (§3.3).

Carries the competing per-point assignment (distinct from the winner’s), its converged per-curve curves (canonicalised like the winner), the seed’s total_chi_squared and whether that seed converged. These are the labellings within a Δχ² window of the winner — the ones a new angle could resolve.

assignment
curves
total_chi_squared
converged
__init__(assignment, curves, total_chi_squared, converged)
class asymmetry.core.fitting.angular_assignment.AngularAssignmentResult(success, converged, model_name, angles, curves, assignment, curve_values, curve_errors, total_chi_squared=0.0, dof=0, message='', alternatives=<factory>)[source]

Bases: object

Outcome of a joint K(θ) fit with per-angle component assignment.

curves[m] is the fit of curve m; curve_values[m]/curve_errors[m] are the realigned per-point values assigned to curve m (so curve m is a continuous trace through crossings). assignment[p][c] gives the curve index that component c at scan point p was assigned to. alternatives holds the distinct near-degenerate runner-up labellings (empty unless keep_alternatives > 0 was requested).

success
converged
model_name
angles
curves
assignment
curve_values
curve_errors
total_chi_squared = 0.0
dof = 0
message = ''
alternatives
__init__(success, converged, model_name, angles, curves, assignment, curve_values, curve_errors, total_chi_squared=0.0, dof=0, message='', alternatives=<factory>)
asymmetry.core.fitting.angular_assignment.fit_assigned_angular_curves(angles, component_values, component_errors=None, *, model_name='KnightAnisotropy', max_iter=25, keep_alternatives=0, alternative_delta_chi2=9.0)[source]

Jointly fit N K(θ) curves, assigning each angle’s components one-to-one.

component_values is [scan_point][component]; N curves are fitted (one per component). Returns the per-curve fits, the per-point assignment, and the realigned per-curve traces. The fit is seeded from both the identity (raw-label) and value-continuity assignments and the lowest-χ² result kept.

When keep_alternatives > 0, each seed’s converged outcome is collected and the runners-up whose assignment differs from the winner (and each other) and whose total_chi_squared lies within alternative_delta_chi2 of the winner are exposed, χ²-ordered and capped at keep_alternatives, on asymmetry.core.fitting.angular_assignment.AngularAssignmentResult.alternatives (canonicalised like the winner). The default (keep_alternatives = 0) leaves behaviour unchanged.

Knight-shift analysis session: a GUI-free pipeline from fitted frequencies to K.

This module is the core model behind the Knight shift analysis window. It owns the derivation pipeline that previously lived inline in the trend panel:

fitted components (ν or B_µ per run) → K per component per run

→ crossing detection along the scan

The three pieces are deliberately separate:

  • KnightAnalysisInput — an immutable snapshot of the measured quantities: one KnightPoint per source run (abscissa, applied field, fitted component values/errors/covariance). The GUI builds it from the live trend rows; scripts can build it directly.

  • KnightShiftConfig — the user’s conversion choices (reference, unit, component subset), reused unchanged.

  • evaluate() — the pure derivation producing a KnightAnalysisResult of per-component KnightBranch traces plus detected crossings. Nothing upstream is mutated.

Only the configuration and the source binding (which series, which axis) are persisted — see KnightAnalysisState. The point snapshot is rebuilt from the source series on load, so saved projects cannot carry a stale copy of the fitted values.

asymmetry.core.fitting.knight_analysis.KNIGHT_COMPONENT_KINDS = ('frequency', 'field')

Oscillation components convertible to a Knight shift, by base parameter name. frequency components are in MHz (referenced to γ_µ·B); field components are the fitted local field in Gauss (referenced to B itself).

class asymmetry.core.fitting.knight_analysis.KnightPoint(run_number, run_label, x, field_gauss, values, errors, covariance=None, include=True)[source]

Bases: object

One source run’s contribution to the analysis snapshot.

x is the scan abscissa (already resolved by the caller — for a rotation scan the unfolded angle in degrees; NaN drops the point). values / errors carry the fitted component parameters; covariance is the (optional) nested parameter-covariance map used by the designated-component reference. include mirrors the trend include-gate so excluded runs stay visible-but-skipped rather than silently vanishing.

run_number
run_label
x
field_gauss
values
errors
covariance = None
include = True
__init__(run_number, run_label, x, field_gauss, values, errors, covariance=None, include=True)
class asymmetry.core.fitting.knight_analysis.KnightAnalysisInput(x_key, x_label, components, points, source_label='', batch_id=None, group_id=None)[source]

Bases: object

Immutable snapshot of everything evaluate() reads.

components lists the convertible components as (name, kind) in model order (kind per KNIGHT_COMPONENT_KINDS); it is the source series’ model-derived observable map when available, so muonium components whose field is the applied field are already excluded. x_key/x_label identify the scan axis for display and persistence; source_label names the originating series/batch for the window header.

x_key
x_label
components
points
source_label = ''
batch_id = None
group_id = None
component_names()[source]
__init__(x_key, x_label, components, points, source_label='', batch_id=None, group_id=None)
class asymmetry.core.fitting.knight_analysis.KnightBranch(name, component, kind, subscript, x, k, k_err, run_numbers, included)[source]

Bases: object

One component’s Knight-shift trace along the scan.

Values are dimensionless fractions; the result-level unit applies a display scale. Entries align with run_numbers (points with a NaN abscissa or a missing component are dropped and counted at the result level; excluded points are kept, flagged by included, so the GUI can grey them out).

name
component
kind
subscript
x
k
k_err
run_numbers
included
__init__(name, component, kind, subscript, x, k, k_err, run_numbers, included)
class asymmetry.core.fitting.knight_analysis.KnightAnalysisResult(unit, unit_label, scale, branches, crossings, skipped_points=0)[source]

Bases: object

Output of evaluate(): branches, crossings, and the resolved unit.

unit
unit_label
scale
branches
crossings
skipped_points = 0

Points dropped from every branch — non-finite abscissa or missing component.

branch(name)[source]
__init__(unit, unit_label, scale, branches, crossings, skipped_points=0)
asymmetry.core.fitting.knight_analysis.SAMPLE_SHAPE_DEMAG_FACTORS = {'custom': None, 'cylinder_axial': 0.0, 'cylinder_transverse': 0.5, 'plate_parallel': 0.0, 'plate_perpendicular': 1.0, 'sphere': 0.3333333333333333}

Demagnetization factor N along the applied field for standard sample shapes (SI convention, ΣN = 1). custom defers to the user-entered value.

class asymmetry.core.fitting.knight_analysis.KnightCorrection(enabled=False, shape='sphere', custom_n=0.3333333333333333, chi_volume_si=0.0)[source]

Bases: object

Lorentz/demagnetizing-field correction to the measured shift.

Applies Amato & Morenzoni Eq. 5.60: K_µ = K_exp − (1/3 − N)·χ, with N the demagnetization factor along the applied field (SI convention, sphere = 1/3 — for which Lorentz and demagnetizing fields cancel and the correction vanishes) and chi the volume susceptibility in SI dimensionless units (multiply a CGS emu/cm³ value by 4π). The correction is a constant offset per branch, exact for an ellipsoidal sample whose shape is fixed relative to the field; for a rotating non-spheroidal sample N itself varies with angle, which this scalar form does not capture.

enabled = False
shape = 'sphere'
custom_n = 0.3333333333333333
chi_volume_si = 0.0
demag_factor()[source]
offset()[source]

The additive correction to a dimensionless K fraction (Eq. 5.60).

to_dict()[source]
classmethod from_dict(data)[source]
__init__(enabled=False, shape='sphere', custom_n=0.3333333333333333, chi_volume_si=0.0)
asymmetry.core.fitting.knight_analysis.branch_name(component)[source]

Trace name for a component’s Knight shift (K[<component>]).

asymmetry.core.fitting.knight_analysis.selected_components(analysis_input, config)[source]

The (name, kind) components the config actually converts.

Applies the config’s component subset (empty = all) and, for the designated-component reference, restricts to components of the same kind as the reference — dividing a frequency (MHz) by a field (Gauss) is meaningless — excluding the reference itself. Returns an empty tuple when the designated reference is not among the snapshot’s components (emit nothing rather than guess).

asymmetry.core.fitting.knight_analysis.evaluate(analysis_input, config, correction=None)[source]

Derive the Knight-shift branches and crossings for a snapshot + config.

Pure: the snapshot is not mutated, and calling twice with the same inputs gives the same result. A disabled config yields an empty result (no branches, no crossings) with the unit still resolved so axis labels stay stable while the user toggles the conversion. correction (optional) applies the Lorentz/demagnetizing offset of Eq. 5.60 to every shift; the offset is common to all branches, so crossings and branch ordering are unaffected. K uncertainties do not include a χ uncertainty.

class asymmetry.core.fitting.knight_analysis.KnightJointCurve(branch_name, parameters, chi_squared, reduced_chi_squared, n_points, success, covariance=None)[source]

Bases: object

One fitted physical curve of a joint K(θ) fit.

branch_name is the K[...] trace this curve occupies after realignment. parameters are (name, value, error) triples in the fit unit (see KnightJointFitState.unit). covariance mirrors asymmetry.core.fitting.parameter_models.ParameterModelFitResult.covariance — (names, matrix) for the curve’s free parameters, in the same order as names. It is already in the display unit: run_joint_fit() scales the values into the display unit before fitting, so the Minuit covariance it reads back is already unit² in that display unit — no extra scaling is applied here. None when the underlying fit produced no covariance (HESSE failed/didn’t run) or the curve predates this field (legacy project).

branch_name
parameters
chi_squared
reduced_chi_squared
n_points
success
covariance = None
to_dict()[source]
classmethod from_dict(data)[source]
__init__(branch_name, parameters, chi_squared, reduced_chi_squared, n_points, success, covariance=None)
class asymmetry.core.fitting.knight_analysis.KnightJointFitState(model_name='KnightAnisotropy', max_iter=25, unit='percent', correction_offset=0.0, converged=False, total_chi_squared=0.0, dof=0, message='', assignment=<factory>, curves=())[source]

Bases: object

Persisted joint K(θ) fit: model, per-run assignment, per-curve parameters.

assignment[run_number][component] is the curve index that component was assigned to at that run — the durable representation (run numbers survive refits and reordering; scan-point indices would not). unit records the concrete display unit the fit ran in: the assignment is unit-independent, but the curve parameters are not, so a unit change marks the curves stale until the fit is re-run.

model_name = 'KnightAnisotropy'
max_iter = 25
unit = 'percent'
correction_offset = 0.0

Lorentz/demag offset (fraction units) active when the fit ran — like unit, a bookkeeping value: a changed correction shifts every K, so the fitted curves go stale (the assignment does not — a common offset cannot reorder branches).

converged = False
total_chi_squared = 0.0
dof = 0
message = ''
assignment
curves = ()
to_dict()[source]
classmethod from_dict(data)[source]
__init__(model_name='KnightAnisotropy', max_iter=25, unit='percent', correction_offset=0.0, converged=False, total_chi_squared=0.0, dof=0, message='', assignment=<factory>, curves=())
asymmetry.core.fitting.knight_analysis.run_joint_fit_outcome(result, *, model_name='KnightAnisotropy', max_iter=25, correction_offset=0.0, keep_alternatives=0)[source]

Run the joint K(θ) fit and return both the persisted state and the outcome.

The persisted KnightJointFitState is exactly what run_joint_fit() returns; the second element is the raw AngularAssignmentResult from the classification-EM fit. The outcome carries the near-degenerate runner-up labellings on alternatives when keep_alternatives > 0 — the input the assignment-discrimination bridge (suggest_assignment_discriminating_angle()) needs. It is deliberately not folded into the state: the state is persisted, but the alternatives are in-memory only (per the study), so a project load never carries them.

keep_alternatives is forwarded to fit_assigned_angular_curves(). Raises ValueError with fewer than two branches or two shared points.

asymmetry.core.fitting.knight_analysis.run_joint_fit(result, *, model_name='KnightAnisotropy', max_iter=25, correction_offset=0.0)[source]

Jointly fit all branches’ K(θ) with per-angle component assignment.

A thin bridge to fit_assigned_angular_curves(): builds the aligned matrices in the result’s display unit (so curve parameters read in the plotted unit), runs the classification-EM fit, and re-keys the assignment by run number. Delegates to run_joint_fit_outcome() and returns only the persisted state, so its public behaviour is unchanged (the EM runner-up alternatives are discarded). Raises ValueError with fewer than two branches or two shared points.

asymmetry.core.fitting.knight_analysis.apply_assignment(result, joint)[source]

Realign the branches so each follows its physical curve through crossings.

For every run in the joint fit’s assignment, the component values are permuted onto the branch of the curve they were assigned to (perm[component] = curve). Runs outside the assignment (new points, or points not shared by all branches at fit time) keep their raw labels. The input result is not mutated.

asymmetry.core.fitting.knight_analysis.assignment_swap_positions(result, joint)[source]

Scan positions (midpoints) where the fitted assignment swaps curves.

These are the crossings the joint fit actually resolved — a firmer signal than the raw proximity flags, so the window marks these when a fit is active. Points not covered by the assignment are skipped.

asymmetry.core.fitting.knight_analysis.suggest_next_angle(result, joint, *, x_min, x_max, target=None, sigma_goal=None, n_candidates=257)[source]

Suggest the next scan angle that best constrains the joint K(θ) fit (§3.1).

Builds one series per fitted curve (model from joint.model_name, parameters/covariance from the curve, empirical noise from its realigned trace) and delegates to suggest_next_point_multi(). target names (branch_name, param_name) for a c-optimal solve (with sigma_goal); None gives the D-optimal information-gain sum. Curves without stored covariance degrade with a warning naming the branch; when every curve lacks covariance the suggestion is empty with a “re-run the joint fit” warning (legacy fits predate stored covariance).

asymmetry.core.fitting.knight_analysis.joint_fit_aic_inputs(joint)[source]

(total_chi_squared, n_curves·n_params) for AIC-weighting a joint fit.

Feeds aic_weights() so the GUI can rank an aligned (lead) fit against a misalignment (alternative) fit (§3.2). n_params is per-curve free-parameter count (all curves share the model), multiplied by the number of curves.

asymmetry.core.fitting.knight_analysis.suggest_model_discriminating_angle(result, joint_lead, joint_alt, *, x_min, x_max, n_candidates=257)[source]

Suggest the angle best distinguishing an aligned vs misaligned fit (§3.2).

Curve identity is preserved: curves are matched across the two joint states by branch_name (an error if the branch sets differ), so the utility is the labelled disagreement sum

U(θ) = Σ_m [f_m^lead(θ) − f_m^alt(θ)]² / 2σ_m²(θ)

with no matching step. σ_m is the lead fit’s realigned per-curve noise (display unit). When the two fits agree within noise everywhere the standard “agree within noise” warning is carried (as in suggest_discriminating_point()).

asymmetry.core.fitting.knight_analysis.suggest_assignment_discriminating_angle(result, outcome, *, x_min, x_max, n_candidates=257)[source]

Suggest the angle best resolving competing per-angle assignments (§3.3).

outcome is an AngularAssignmentResult carrying near-degenerate runner-up labellings (keep_alternatives > 0). The utility is the elementwise max over alternatives of the Hungarian set-matching divergence between the winner’s and each alternative’s predicted value sets (leader-vs-all — the TAS-AI lock-in lesson): it is ~0 where the labellings coincide (e.g. at a crossing) and peaks where they imply genuinely different curve sets. With no alternatives the suggestion is empty (“no near-degenerate assignments to discriminate”).

Per-curve noise comes from the winner’s realigned trace errors (outcome.curve_errors); because the utility is a value²/σ² ratio it is invariant to the common display-unit scale, so result is used only to confirm the curve/branch counts agree.

class asymmetry.core.fitting.knight_analysis.KnightAnalysisState(config=<factory>, correction=<factory>, source_batch_id=None, source_group_id=None, x_key='angle', fold_180=False, show_markers=True, rescale_errors=False, joint=None)[source]

Bases: object

Persisted window state: conversion config + source binding + view hints.

Deliberately excludes the point snapshot (rebuilt from the source series on open — a saved copy could go stale against a refit). source_batch_id / source_group_id re-bind the window to its series; x_key pins the scan axis. fold_180 and show_markers are plot-view preferences. joint carries the (optional) joint K(θ) fit; its run-keyed assignment stays valid across snapshot rebuilds.

config
correction
source_batch_id = None
source_group_id = None
x_key = 'angle'
fold_180 = False
show_markers = True
rescale_errors = False
joint = None
to_dict()[source]
classmethod from_dict(data)[source]
__init__(config=<factory>, correction=<factory>, source_batch_id=None, source_group_id=None, x_key='angle', fold_180=False, show_markers=True, rescale_errors=False, joint=None)
asymmetry.core.fitting.knight_analysis.migrate_legacy_state(fit_parameters_state)[source]

Lift a pre-window trend-panel Knight-shift block into the new state.

Projects saved before the analysis window stored the conversion config under fit_parameters_state["knight_shift"] (with the scan axis in x_axis_key). Returns None when there is nothing to migrate (missing block or conversion never enabled) so callers can skip writing an empty state; the legacy block itself is left untouched for older app versions.

asymmetry.core.fitting.knight_analysis.snapshot_from_rows(rows, *, x_values, x_key, x_label, components, source_label='', batch_id=None, group_id=None)[source]

Build a snapshot from trend-row-shaped objects.

rows are duck-typed against the trend panel’s row records (attributes run_number, run_label, field, values, errors, covariance, include_in_trend); x_values supplies the resolved (unfolded) abscissa for each row, letting the caller keep ownership of the axis resolution. Rows and abscissae must align.