Core data structures

The core data layer carries μSR measurements through the fit and analysis pipeline. MuonDataset is the working representation — a time axis, an asymmetry, and an uncertainty, plus a metadata dictionary and a reference back to the Run it was computed from. The Run carries the raw per-detector Histogram records and the grouping payload (see Detector Grouping and Layout) and is what asymmetry.core.io.load() returns for raw-histogram files. The Logbook collects multiple runs into a searchable, tag-filterable run table (see Logbook workflows), and the instrument-geometry classes below define the detector banks and preset groupings for the supported spectrometers.

Dataset

class asymmetry.core.data.dataset.MuonDataset(time, asymmetry, error, metadata=<factory>, run=None, histogram_observation=None, ratio_validity=None, counting_noise=None, effective_recipe=None, computation_revision=None)[source]

Bases: object

Processed asymmetry dataset ready for plotting / fitting.

This is the primary object that users interact with after loading and reducing a run.

Scale convention

asymmetry and error are stored on the percent scale (the WiMDA-style convention the loaders and the time-domain fit models share — a 16 % asymmetry is stored as 16.0, not 0.16, and the built-in models default A0 to 25). The low-level asymmetry.core.transform.asymmetry.compute_asymmetry() primitive instead returns the dimensionless fraction; the loaders multiply by 100 to populate these arrays. When a specific scale is needed, prefer the explicit asymmetry_percent / asymmetry_fraction (and error_percent / error_fraction) accessors so the two can never be silently confused — seeding a fit with fraction-scale amplitudes against this percent-scale data converges to the wrong minimum.

time
asymmetry
error
metadata
run = None
histogram_observation = None
ratio_validity = None
counting_noise = None
effective_recipe = None
computation_revision = None
property n_points[source]
property asymmetry_percent[source]

Asymmetry on the percent scale (the stored convention).

property asymmetry_fraction[source]

Asymmetry as the dimensionless fraction (percent / 100).

property error_percent[source]

Asymmetry error on the percent scale (the stored convention).

property error_fraction[source]

Asymmetry error on the fractional scale (percent / 100).

property run_number[source]
property temperature[source]

Sample setpoint or explicitly selected logged value, or None.

Unlike Run.temperature (which floors a missing value to 0.0), this returns None when no temperature was recorded so a trend point with genuinely-missing metadata is marked off-axis rather than planted at 0 K.

property field[source]

Applied field in gauss (metadata["field"]), or None when absent.

property sample_temperature_logged[source]

Representative logged sample temperature, if recorded.

The explicit selection, or the loader’s sample-thermometer reading (a Temp_Sample NXlog or PSI header sensor 1). metadata["sample_temperature_log_source"] names its source. Without an explicit selection, temperature is the setpoint. None when the file holds no usable reading.

property run_label[source]

Return a user-facing run label.

For co-added datasets this prefers metadata['run_label'] (for example "3039 + 3040") so UI text does not display internal negative combined IDs.

fit_record()[source]

Return this dataset as a fit record: fitted arrays plus provenance, no counts.

A fit record is what crosses a process boundary to be fitted. It carries the time/asymmetry/error arrays a fit reads and the run’s scalar provenance — run number and label, temperature, field, geometry, metadata and grouping — but not the run’s raw detector histograms, which no time-domain fit touches and which dominate the pickled size of a task payload: a run’s counts are of the order of a detector count times a bin count, so a record whose fitted arrays are a fraction of a megabyte pickles to tens of megabytes while it still holds them.

The copy shares fitted arrays and metadata. Its Run omits histograms and period-array caches, and its transient histogram observation is removed. Scalar grouping provenance is retained. A curve without a Run or histogram observation is returned unchanged.

Count-domain fitting, β/α calibration and grouped time-domain fitting do read run.histograms; they must be handed the full record, not a fit record.

merge_curve_bins(factor)[source]

Merge curve bins by averaging values and propagating counting noise.

This operation does not re-reduce raw histograms. Use counts-first reduction with a BinningSpec when raw histograms are available. The returned dataset shares this dataset’s Run for provenance; it leaves the source arrays untouched. Use fit_record() for worker-process transfers.

Retained counting influences are propagated through the mean, preserving known shared acquisition and background-estimator noise. For independent inputs without retained noise, the error is sqrt(sum(error²))/factor. Unknown correlations cannot be recovered from marginal errors alone. Values and errors keep the input fraction or percent scale; timestamps are averaged. A factor of one copies the arrays, and a trailing partial group is dropped. The factor must be an integer >= 1.

time_range(t_min=None, t_max=None)[source]

Return a copy restricted to [t_min, t_max].

Like merge_curve_bins(), the copy shares this dataset’s Run and so keeps its raw histograms: correct in-process, but it means a windowed copy pickles no smaller than the record it came from. Use fit_record() for anything bound for a worker process.

summary()[source]
__init__(time, asymmetry, error, metadata=<factory>, run=None, histogram_observation=None, ratio_validity=None, counting_noise=None, effective_recipe=None, computation_revision=None)
class asymmetry.core.data.dataset.Run(run_number=0, histograms=<factory>, metadata=<factory>, grouping=<factory>, source_file='', source_binding=SourceBinding(expected=None, observed=None))[source]

Bases: object

A single μSR measurement run.

Holds raw histograms, grouping definitions, and run metadata.

run_number = 0
histograms
metadata
grouping
source_file = ''
source_binding = SourceBinding(expected=None, observed=None)
property title[source]
property temperature[source]

Sample setpoint or explicitly selected logged value, in kelvin.

Explicit unknown values (None) are NaN.

property sample_temperature_logged[source]

Representative logged sample temperature, if recorded.

The explicit selection, or the loader’s sample-thermometer reading (a Temp_Sample NXlog or PSI header sensor 1). metadata["sample_temperature_log_source"] names its source. Without an explicit selection, temperature is the setpoint. None when the file holds no usable reading.

property field[source]

Applied field in gauss; explicit unknown values (None) are NaN.

summary()[source]
__init__(run_number=0, histograms=<factory>, metadata=<factory>, grouping=<factory>, source_file='', source_binding=SourceBinding(expected=None, observed=None))
class asymmetry.core.data.dataset.Histogram(counts, bin_width, t0_bin=0, good_bin_start=0, good_bin_end=-1, t0_time_us=None, count_variance=None, counting_observation=None)[source]

Bases: object

Raw detector histogram.

Parameters:
  • counts (NDArray) – Positron counts per time bin.

  • bin_width (float) – Bin width in microseconds.

  • t0_bin (int) – Bin index of t = 0 (muon implantation) — the 0-based index of the bin that contains t0.

  • good_bin_start (int) – First usable bin (absolute bin index, not an offset from t0).

  • good_bin_end (int) – Last usable bin (absolute bin index, inclusive).

  • t0_time_us (float or None) – Exact time of t0 in microseconds from the start of acquisition, on the raw axis where bin k spans [k·w, (k+1)·w) — ISIS time_zero, MusrRoot (Time Zero Bin + 0.5)·w. None when the file carries no sub-bin t0; see t0_time_us_effective.

  • count_variance (NDArray or None) – Independent counting variance on the same acquisition bins. None denotes the raw Poisson assumption. NaN explicitly records unknown noise on an acquisition bin; consumed unknown noise is an operation error. Prepared copies retain noise rather than infer it from corrected counts.

counts
bin_width
t0_bin = 0
good_bin_start = 0
good_bin_end = -1
t0_time_us = None
count_variance = None
counting_observation = None
property n_bins[source]
property t0_time_us_effective[source]

Exact t0 in µs, falling back to the centre of t0_bin.

The fallback (t0_bin + 0.5)·w reproduces the integer-bin stamps (k − t0_bin)·w exactly, so a file without an exact t0 keeps today’s time axis to the last bit.

property time_axis[source]

Time axis in microseconds, centred on t0.

Bin k is stamped at its centre, (k + 0.5)·w − t0, using the exact t0_time_us_effective. Written as the integer-bin axis plus the sub-bin residual so a histogram without an exact t0 keeps the old (k − t0_bin)·w values bit for bit.

__init__(counts, bin_width, t0_bin=0, good_bin_start=0, good_bin_end=-1, t0_time_us=None, count_variance=None, counting_observation=None)

Effective reduction recipe

MuonDataset.effective_recipe is independent of its transient histogram_observation. Historical or unsupported curves have no captured raw provenance. JSON conversion does not grant replay or covariance reconstruction. Source locators are retained in the view and excluded from numerical identity; publishable() returns a detached numerical disclosure without nested local locators or diagnostic prose and preserves numerical identity. Workdir and scan codecs retain the local view. Project result metadata and fitted-input summaries retain captured history separately from recomputed curves. A fit-input digest records sampled values, errors, and support; recipe identity alone cannot verify those observations.

class asymmetry.core.data.reduction_recipe.EffectiveReductionRecipe(canonical_json)[source]

Versioned canonical JSON with no mutable values or executable objects.

identity identifies the recorded interpretation and available source references; it is not a whole-file content fingerprint. to_dict returns a detached view. This record alone never grants histogram replay, covariance, or likelihood eligibility.

canonical_json
classmethod from_dict(value)[source]

Capture a detached JSON record; reject arrays and non-finite numbers.

to_dict()[source]

Return an independent serializable view of the captured authority.

publishable()[source]

Disclose numerical facts without nested source locators or diagnostic prose.

The detached projection retains numerical identity and never mutates the private calibration, reference, or constituent history. Existing export titles and comments have their own disclosure policy.

property identity[source]

SHA-256 of canonical numerical facts, excluding locators and prose.

sources()[source]

Inventory captured result inputs without looking up or certifying files.

Constituent order, signed coefficients, and acquired period selectors survive even when several terms share identical physical file bytes.

with_facts(**facts)[source]

Complete a captured operation with its actual output facts.

scalar_units(*, units, factor)[source]

Describe a scalar conversion with its captured native recipe as the input.

scan_selection(indices, *, derivative)[source]

Keep selected point recipes with scalar scans and source context with derivatives.

curve_operation(operation, **parameters)[source]

Append an ordered curve selection or transform without implying raw replay.

__init__(canonical_json)

Logbook

class asymmetry.core.data.logbook.LogbookEntry(run_number, title='', temperature=0.0, field=0.0, comment='', tags=<factory>, source_file='', extra=<factory>)[source]

Bases: object

One row in the logbook.

run_number
title = ''
temperature = 0.0
field = 0.0
comment = ''
tags
source_file = ''
extra
__init__(run_number, title='', temperature=0.0, field=0.0, comment='', tags=<factory>, source_file='', extra=<factory>)
class asymmetry.core.data.logbook.Logbook[source]

Bases: object

A searchable, sortable table of μSR runs.

__init__()[source]
add(dataset, tags=None)[source]

Register a dataset in the logbook.

remove(run_number)[source]
get_entry(run_number)[source]
get_dataset(run_number)[source]
property run_numbers[source]
filter(**criteria)[source]

Return entries matching all criteria (field=value pairs).

search(text)[source]

Free-text search across title, comment and tags.

create_collection(name, run_numbers)[source]
get_collection(name)[source]
property collections[source]
save(path)[source]

Save logbook metadata to a JSON file.

load_metadata(path)[source]

Restore logbook entries from a JSON file (data files must be reloaded separately).

Scripted grouping preparation

See Load a synthetic run, apply a preset, calibrate, and reduce for synthetic loading, preset application, calibration, and reduction, and Detector Grouping and Layout for policy.

asymmetry.core.workflow.apply_grouping_preset(dataset, preset_name)[source]

Return a newly reduced dataset with an explicitly selected instrument preset.

Recognition and histogram-count variant resolution select the layout; the caller selects the exact preset name. All preset groups must have acquired, non-excluded members. Existing exclusions, timing, binning, and correction policies are retained. Preset projections replace the previous projections and their manually authored balances; scalar balance policies are retained.

Active captured calibration policies cannot survive a change to membership, the selected pair, or projection pairs: such requests raise ValueError. Apply the preset to the original uncalibrated dataset, then calibrate it. Identical grouping retains the canonical coefficient policies and records.

The source dataset is never modified. The returned run shares the acquired histograms, while grouping and curve provenance describe the new reduction. Cached period curves are discarded; all held periods must have raw histograms. Curve-only or rotating-frame inputs, unknown instruments/presets, incompatible labels, and unavailable channels raise explicit errors. No loading defaults are changed.

Scripted calibration packing

Use CalibrationOptions.count_packing to request fixed TF count packing independently of science reduction. See Explicit workflow and CLI calibration for the public-call example, inherited-source behaviour, and quick-method limits.

The request and operation are documented in TF calibration.

Scripted temperature selection

See Explicit temperature channels in scripts for channel, statistic, unit, and failure semantics and Select a logged thermometer for a synthetic example.

asymmetry.core.workflow.select_logged_temperature(dataset, channel)[source]

Return a copy labelled by the arithmetic mean of an exact log channel.

channel must be a full key in metadata['nexus_time_series']; sensor labels and suffixes are never matched. Samples with time >= 0 are included, equally weighted, without interpolation or duration weighting. A non-empty one-dimensional sample list and a finite, equally sized time axis are required. Every included reading must be finite and above 0 K after declared-unit conversion. Missing, unknown, or incompatible units raise ValueError. No header, other channel, or cached summary substitutes for missing readings.

The returned dataset and Run expose the selected value through temperature and sample_temperature_logged. Raw logs and original scalar metadata remain available; temperature_selection records the channel, statistic, sample policy, and original scalar fields. Re-selection retains those original fields. Arrays and histograms are shared; metadata is detached. Loader defaults and the input are unchanged. This statistic does not establish thermal equilibrium.

Instrument geometry

class asymmetry.core.instrument.DetectorSegment(detector_id, sector_index, ring_index, angle_center_deg, angle_half_width_deg, r_inner, r_outer, shape='wedge', label=None, x_center=0.0, y_center=0.0, width=0.0, height=0.0, rotation_deg=0.0, read_only=False)[source]

Bases: object

Geometric description of a single detector element.

Parameters:
  • detector_id (int) – 1-based detector number matching instrument-manual convention.

  • sector_index (int) – Azimuthal sector index within the bank (0-based, 0 = first sector).

  • ring_index (int) – Radial ring index within the sector (0-based, 0 = innermost). For single-ring instruments this is always 0.

  • angle_center_deg (float) – Central azimuthal angle of the segment in degrees. 0° points right and positive rotation is counter-clockwise.

  • angle_half_width_deg (float) – Half the angular width of the segment in degrees.

  • r_inner (float) – Inner radius normalised to the outer disc radius (0–1).

  • r_outer (float) – Outer radius normalised to the outer disc radius (0–1).

  • shape (str) – Rendering primitive. "wedge" is used for circular ISIS detector banks; "rectangle" is used for top-view detector plates such as PSI FLAME. "endon_out" / "endon_in" draw a detector seen end-on — pointing toward (⊙) or away from (⊗) the viewer — used in multi-panel plan layouts to show a detector that is perpendicular to the current view (and therefore editable in the other panel).

  • label (str | None) – Optional short detector label displayed alongside the detector ID.

  • x_center, y_center, width, height, rotation_deg – Rectangle geometry in an arbitrary plan-view coordinate system.

  • read_only (bool) – When True the segment is drawn for spatial context only — it is not clickable and never takes a group colour. A detector that appears in more than one plan panel is active (clickable) in exactly one panel and read_only in the others.

detector_id
sector_index
ring_index
angle_center_deg
angle_half_width_deg
r_inner
r_outer
shape = 'wedge'
label = None
x_center = 0.0
y_center = 0.0
width = 0.0
height = 0.0
rotation_deg = 0.0
read_only = False
property angle_start_deg[source]

Lower bound of the segment arc in degrees (counter-clockwise measured).

property angle_end_deg[source]

Upper bound of the segment arc in degrees (counter-clockwise measured).

__init__(detector_id, sector_index, ring_index, angle_center_deg, angle_half_width_deg, r_inner, r_outer, shape='wedge', label=None, x_center=0.0, y_center=0.0, width=0.0, height=0.0, rotation_deg=0.0, read_only=False)
class asymmetry.core.instrument.BankLayout(name, segments)[source]

Bases: object

Collection of detector segments forming one detector bank.

Parameters:
  • name (str) – Human-readable bank name (e.g. "Forward").

  • segments (tuple[asymmetry.core.instrument.DetectorSegment, …]) – All detector segments that belong to this bank.

name
segments
__init__(name, segments)
class asymmetry.core.instrument.GroupDefinition(name, detector_ids)[source]

Bases: object

A named set of detectors forming one group within a preset.

Parameters:
  • name (str) – Display name for the group (e.g. "Forward", "Pz Backward").

  • detector_ids (tuple[int, …]) – Tuple of 1-based detector IDs belonging to this group.

name
detector_ids
__init__(name, detector_ids)
class asymmetry.core.instrument.PresetGrouping(name, groups, forward_group, backward_group, projections=())[source]

Bases: object

A named, complete grouping assignment for an instrument.

Parameters:
  • name (str) – Human-readable preset name (e.g. "Longitudinal").

  • groups (dict[int, asymmetry.core.instrument.GroupDefinition]) – Mapping from group ID (1-based, matching the Group 1–8 buttons) to GroupDefinition. Unused group IDs should not appear.

  • forward_group (int) – Group ID of the default forward group.

  • backward_group (int) – Group ID of the default backward group.

  • projections (tuple[asymmetry.core.instrument.AsymmetryProjection, …]) – Ordered projections exposed by this preset, when it is a multi-projection (vector / dual-grouping) preset. Empty for ordinary single-pair presets.

name
groups
forward_group
backward_group
projections = ()
__init__(name, groups, forward_group, backward_group, projections=())
class asymmetry.core.instrument.ReferenceArrow(label, start, end, color='#333333')[source]

Bases: object

A labelled direction marker rendered on plan-view schematics.

label
start
end
color = '#333333'
__init__(label, start, end, color='#333333')
class asymmetry.core.instrument.InstrumentLayout(name, n_detectors, banks, presets, view='radial', reference_arrows=(), display_name=None, apply_default_preset_on_load=False)[source]

Bases: object

Complete detector layout description for one muon instrument.

Parameters:
  • name (str) – Canonical instrument name ("HiFi", "MuSR", or "EMU").

  • n_detectors (int) – Total number of detectors / histograms.

  • banks (tuple[asymmetry.core.instrument.BankLayout, …]) – Ordered tuple of BankLayout objects.

  • presets (dict[str, asymmetry.core.instrument.PresetGrouping]) – Ordered dict of preset names to PresetGrouping. The first entry is the default preset.

  • view (str) – Schematic rendering mode, either "radial" or "plan".

  • reference_arrows (tuple[asymmetry.core.instrument.ReferenceArrow, …]) – Optional labelled arrows used by plan-view layouts.

  • display_name (str | None) – Optional user-facing name shown in the instrument dropdown. Defaults to name. Layout variants of one physical instrument (e.g. the 6-detector PSI GPS BIN layout "GPS", the 11-detector ROOT sub-detector layout "GPS-RD" and the 15-detector combined+sub-detector ROOT layout "GPS-RD15") share a display name so the user only ever sees the variant matching their loaded data, while name stays a distinct registry key for detection and persistence.

  • apply_default_preset_on_load (bool) – When True, a loader applies this instrument’s default preset (the first entry in presets) to a freshly loaded run automatically, instead of leaving the loader’s generic label-based grouping in place. Used for instruments whose useful grouping is not the plain forward/backward split the labels imply — HAL-9500, whose per-octant angle-resolved grouping should be live the moment the data loads, without the user having to open the grouping window and click Apply. Off by default so every other instrument keeps its loader grouping untouched.

name
n_detectors
banks
presets
view = 'radial'
reference_arrows = ()
display_name = None
apply_default_preset_on_load = False
property display[source]

User-facing name (display_name if set, else name).

property all_segments[source]

All segments from all banks, in bank order.

In a multi-panel plan layout a detector may appear in more than one bank (active in its home panel, read_only elsewhere), so this can contain several segments per detector_id. Use active_segments for one segment per physical detector.

property active_segments[source]

One clickable segment per detector (the non-read_only segments).

property default_preset_name[source]

Name of the first (default) preset.

__init__(name, n_detectors, banks, presets, view='radial', reference_arrows=(), display_name=None, apply_default_preset_on_load=False)
asymmetry.core.instrument.get_instrument_layout(name)[source]

Return the InstrumentLayout for name.

Parameters:

name – One of the names in INSTRUMENT_NAMES (case-sensitive).

Raises:

KeyError – If name is not a known instrument.

asymmetry.core.instrument.detect_instrument(n_histograms, *, metadata=None, source_file=None)[source]

Guess the instrument name from the number of histograms.

This is a heuristic for the automatic instrument selection in the detector layout editor. The caller should always allow the user to override the returned value.

Parameters:
  • n_histograms – Total number of histograms / raw-detector channels in the run.

  • metadata – Optional run metadata. If an instrument-like field is present, it takes priority over the histogram-count heuristic.

  • source_file – Optional source filename/path used as a final lightweight hint.

Returns:

str or None – Canonical instrument name when detection succeeds, else None.

Simulation

Synthetic-run generation and statistics degradation (see Synthetic runs and degraded statistics): Poisson draws of expected per-detector counts from an instrument template — a loaded run or a built-in idealised instrument — exact binomial thinning of measured runs, per-group amplitude and phase simulation, and the promoted screenshot-archetype builders.

Synthetic μSR run generation and statistics degradation.

Detector d has Poisson counts with lifetime and asymmetry modulation:

N_d(t) = N0_d · exp(−t/τ_μ) · [1 + a_d(t)] + b_d (t ≥ 0) N_d(t) = b_d (t < 0)

Simulation draws Poisson expected counts; errors propagate through reduction. The α calibration enters as the relative efficiency of the forward and backward detector groups: forward-group detectors receive the weight 2α/(1+α) and backward-group detectors 2/(1+α), so the reduction (F − αB)/(F + αB) recovers a(t) with α restored.

Synthetic sources retain deterministic seeds, optional flat backgrounds, and background-only pre-t0 bins. Degradation below one uses binomial thinning.

This module is Qt-free and must stay importable without the GUI.

asymmetry.core.simulate.GroupSignal = collections.abc.Callable[[numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.float64]]], numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.float64]]] | numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.float64]]

A per-group asymmetry signal — a callable evaluated on the time axis in microseconds (returning the fractional asymmetry), or an array on the detector’s post-t0 bin grid (short arrays are zero-padded).

class asymmetry.core.simulate.InstrumentTemplate(key, label, description, n_detectors, n_bins, bin_width_us, t0_bin, forward_detectors, backward_detectors, alpha=1.0, good_frames=1.0, good_bin_start=None, good_bin_end=None, default_total_events=10000000.0, default_background_per_bin=0.0, instrument_name='', field_state='ZF', detector_orientation='Longitudinal', groups=None, group_names=None, group_azimuths=None, default_forward_group=None, default_backward_group=None)[source]

A built-in idealised instrument that can stand in for a loaded run.

simulate_run() only reads structure from its template — detector count, bin width, per-detector t0, the good-bin window and the forward/backward grouping — never the (zero) counts, so a built-in template carries empty histograms and a complete grouping. The default_total_events and default_background_per_bin are teaching-sensible starting points the dialog seeds its spinners with; the continuous instrument carries a non-zero flat background (the time-independent uncorrelated background characteristic of continuous sources — textbook Ch. 14), the pulsed one does not.

key
label
description
n_detectors
n_bins
bin_width_us
t0_bin
forward_detectors
backward_detectors
alpha = 1.0
good_frames = 1.0
good_bin_start = None
good_bin_end = None
default_total_events = 10000000.0
default_background_per_bin = 0.0
instrument_name = ''
field_state = 'ZF'
detector_orientation = 'Longitudinal'
groups = None

Override the plain forward/backward pair with an arbitrary N-group layout (e.g. an azimuthal ring) — group id -> its detector ids. When set, this (plus group_names, default_forward_group and default_backward_group) replaces the two-group forward_detectors / backward_detectors convention; those two fields are still required by the dataclass but are unused.

group_names = None

Group id -> display name, paired with groups. Falls back to f"Group {gid}" per group when groups is set but this is not.

group_azimuths = None

Group id -> azimuthal angle in degrees, for a ring-style groups layout. Carried into grouping["group_azimuths_deg"] (see group_azimuths_deg()) so downstream code — a multi-group fit seed, a phase-vs-geometry plot — can read each group’s detector phase without re-deriving the instrument’s numbering convention.

default_forward_group = None

Forward/backward group ids to use with groups. Default to the lowest group id and, for an even group count, the id diametrically opposite it (groups count // 2 further around), giving a sensible default F/B pair for a ring even though the layout is not a plain two-group split.

default_backward_group = None
build()[source]

Materialise an empty-histogram Run with this geometry.

__init__(key, label, description, n_detectors, n_bins, bin_width_us, t0_bin, forward_detectors, backward_detectors, alpha=1.0, good_frames=1.0, good_bin_start=None, good_bin_end=None, default_total_events=10000000.0, default_background_per_bin=0.0, instrument_name='', field_state='ZF', detector_orientation='Longitudinal', groups=None, group_names=None, group_azimuths=None, default_forward_group=None, default_backward_group=None)
asymmetry.core.simulate.BUILTIN_TEMPLATES = {'ideal_continuous_fb': InstrumentTemplate(key='ideal_continuous_fb', label='Ideal continuous F/B (PSI-style)', description='Continuous-source F/B pair: 1 ns bins over a 10 µs window with a flat uncorrelated background (10 counts/bin/detector).', n_detectors=2, n_bins=10000, bin_width_us=0.001, t0_bin=1000, forward_detectors=(1,), backward_detectors=(2,), alpha=1.0, good_frames=1.0, good_bin_start=None, good_bin_end=None, default_total_events=20000000.0, default_background_per_bin=10.0, instrument_name='IDEAL-CONTINUOUS', field_state='ZF', detector_orientation='Longitudinal', groups=None, group_names=None, group_azimuths=None, default_forward_group=None, default_backward_group=None), 'ideal_continuous_ring8': InstrumentTemplate(key='ideal_continuous_ring8', label='Ideal continuous octant ring (PSI-style)', description='Continuous-source azimuthal ring: 8 detector groups at 45° spacing (one detector each), 1 ns bins over a 10 µs window with a flat uncorrelated background (10 counts/bin/detector) — the geometry ingredient for PSI HAL-9500-style high-TF data.', n_detectors=8, n_bins=10000, bin_width_us=0.001, t0_bin=1000, forward_detectors=(1,), backward_detectors=(5,), alpha=1.0, good_frames=1.0, good_bin_start=None, good_bin_end=None, default_total_events=20000000.0, default_background_per_bin=10.0, instrument_name='IDEAL-CONTINUOUS-RING8', field_state='TF', detector_orientation='Transverse', groups={1: (1,), 2: (2,), 3: (3,), 4: (4,), 5: (5,), 6: (6,), 7: (7,), 8: (8,)}, group_names={1: 'Ring 1', 2: 'Ring 2', 3: 'Ring 3', 4: 'Ring 4', 5: 'Ring 5', 6: 'Ring 6', 7: 'Ring 7', 8: 'Ring 8'}, group_azimuths={1: 90.0, 2: 45.0, 3: 0.0, 4: 315.0, 5: 270.0, 6: 225.0, 7: 180.0, 8: 135.0}, default_forward_group=1, default_backward_group=5), 'ideal_pulsed_fb': InstrumentTemplate(key='ideal_pulsed_fb', label='Ideal pulsed F/B (ISIS-style)', description='Pulsed-source spectrometer: 32 forward + 32 backward detectors, 16 ns bins over a 32 µs window, no uncorrelated background.', n_detectors=64, n_bins=2000, bin_width_us=0.016, t0_bin=100, forward_detectors=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32), backward_detectors=(33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64), alpha=1.0, good_frames=1.0, good_bin_start=None, good_bin_end=None, default_total_events=40000000.0, default_background_per_bin=0.0, instrument_name='IDEAL-PULSED', field_state='ZF', detector_orientation='Longitudinal', groups=None, group_names=None, group_azimuths=None, default_forward_group=None, default_backward_group=None)}

Built-in idealised instruments, keyed for the dialog template combo. The pulsed F/B template mirrors an ISIS-style spectrometer (32 + 32 detectors, 16 ns bins, a 32 µs window); the continuous template a PSI-style F/B pair with fine 1 ns binning, a short 10 µs window and a flat background. The two are the source archetypes the textbook contrasts (Ch. 14).

asymmetry.core.simulate.build_builtin_template(key, *, n_bins=None, bin_width_us=None, t0_bin=None)[source]

Build an empty-histogram Run for a named built-in instrument.

n_bins, bin_width_us and t0_bin override the template’s own values (e.g. a finer or coarser ring binning than BUILTIN_TEMPLATES’s defaults) without needing a bespoke InstrumentTemplate; the good-bin window follows the (possibly overridden) n_bins/t0_bin exactly as InstrumentTemplate.build() computes it. Omitted arguments keep the template’s own value.

Raises KeyError for an unknown key. See BUILTIN_TEMPLATES for the available instruments.

asymmetry.core.simulate.group_azimuths_deg(run)[source]

Per-group azimuthal angle (degrees), if the run’s template recorded one.

Reads run.grouping["group_azimuths_deg"] — populated by InstrumentTemplate.build() for a ring-style built-in template (e.g. "ideal_continuous_ring8") and carried through unchanged by every synthetic-run builder in this module (it is not one of the period keys stripped by asymmetry.core.simulate._synthetic_run_grouping). Returns an empty dict for a template with no azimuthal ring structure.

asymmetry.core.simulate.poisson_asymmetry_errors(asymmetry, counts_per_bin=50000.0)[source]

Per-bin uncertainty (percent) derived from a target counts-per-bin.

The asymmetry σ for a two-detector experiment scales as sqrt((1 - A^2) / N). Picking a counts-per-bin gives a realistic noise envelope without doing a histogram round-trip; use the full simulate_run() pipeline when the errors must come from actual Poisson histograms.

asymmetry.core.simulate.build_run_from_detector_asymmetries(*, run_number, detector_asymmetries, title, temperature_k, field_g, bin_width_us=0.005, n_bins=2400, t0_bin=100, n0_per_detector=1000000.0, lifetime_us=2.1969811, rng=None)[source]

Synthesise a full Run from per-detector asymmetry signals.

Each detector histogram is built as

N_d(t) = N_{0,d} · exp(-t/τ) · (1 + A_d(t)) for t > 0

= N_{0,d} for t ≤ 0

with Poisson counting noise applied. The grouping payload puts one detector per group so the GUI’s Individual Groups domain view shows a trace per detector. The function also returns the F–B asymmetry trace (using the first two groups) and a per-bin error estimate so a wrapper MuonDataset carries a defensible time-domain view.

This is the screenshot-archetype builder promoted into core: the flat pre-t0 plateau at N₀ is its historical convention (kept for byte-stable documentation data). simulate_run() is the template-driven instrument-faithful path, with background-only bins before t0.

Parameters:
  • detector_asymmetries – One dict per detector. Each dict must define "asymmetry" (a (n_bins - t0_bin,) array giving the fractional A_d(t)) plus optional "label" and "n0".

  • lifetime_us – Decay constant of the envelope. Defaults to the canonical muon lifetime; the screenshot archetypes pass their legacy rounded value to keep documentation data byte-stable.

asymmetry.core.simulate.expected_counts(template, group_signals, *, total_events, group_weights=None, background_per_bin=0.0, on_negative_expected='clip')[source]

Expected (noise-free) per-detector count histograms.

The deterministic core of simulate_run_from_group_signals() and simulate_signal_run(), exposed so tests and diagnostics can compare the sampled histograms (or a reduction of them) against the exact expectation.

total_events is the expected number of detected decay events summed over all detectors and the post-t0 histogram window — the per-bin rate at t = 0 uses the exact telescoping normalisation n0 = N_d · (1 − exp(−Δt/τ_μ)), so the window sum equals total_events · (1 − exp(−T/τ_μ)) up to the (simulated) truncation of the lifetime envelope at the histogram end. Background counts are in addition to this budget.

group_weights rescales each group’s per-detector rate; weights are normalised over the assigned detectors so the total event budget is independent of the weighting (this is how the α split is applied without distorting the run-level rate).

background_per_bin is either one flat rate shared by every detector (the original contract) or a group_id -> counts/bin mapping for a per-group background; a group absent from the mapping gets zero.

A signal is allowed to be negative and to exceed |a| > 1 — only the resulting expected count is constrained. on_negative_expected chooses what happens when N0·exp(−t/τ)·(1 + a(t)) + b would go negative for some detector/bin: "clip" (the default, matching every existing caller) floors it at the background level, silently discarding the excess; "raise" (used by simulate_signal_run(), where the signal is caller-supplied and a silent floor would hide a modelling mistake) raises ValueError naming the offending group, detector and time instead.

asymmetry.core.simulate.simulate_run_from_group_signals(template, group_signals, *, total_events, seed=0, group_weights=None, background_per_bin=0.0, run_number=None, title=None, simulation_metadata=None)[source]

Simulate a run from per-group fractional asymmetry signals.

The scriptable multi-group seam: each entry of group_signals assigns a signal a_g(t) to one detector group of the template’s grouping; detectors in unlisted groups receive the bare lifetime envelope. Bin structure, per-detector t0, the good-bin window and the grouping are all taken from template. Sampling is a single seeded numpy.random.Generator drawing poisson(expected) per detector, in detector order — a fixed seed reproduces the run bit-for-bit.

background_per_bin accepts a single flat rate or a per-group group_id -> counts/bin mapping (see expected_counts()).

The returned Run carries metadata["synthetic"] = True and a metadata["simulation"] provenance dict; deadtimes are zeroed in the grouping (the synthetic counts contain no deadtime distortion, so zero is the true instrument description). See simulate_signal_run() for the validating front end this shares its machinery with, when the signal is caller-supplied rather than drawn from the fit-model registry.

asymmetry.core.simulate.simulate_signal_run(template, signals, *, total_events, seed=0, group_weights=None, background_per_bin=0.0, run_number=None, title=None, simulation_metadata=None)[source]

Simulate a run from arbitrary, externally supplied per-group signals.

The first-class entry point for a signal a_g(t) that does not come from the fit-model registry — PSI HAL-9500-style high-transverse-field data, for instance, where each ring group sees an independent, possibly non-analytic polarization trace computed elsewhere (a forward model, a lookup table, a numerical simulation). signals maps a detector group id (a key of template.grouping["groups"]) to a GroupSignal — either a callable a(t_us) -> array in fractional units, or an array pre-sampled exactly on the group’s post-t0 bin grid (see Raises). Groups with no entry in signals receive the bare lifetime envelope (a(t) = 0).

This is a thin, validating front end over the same expected_counts() / asymmetry.core.simulate._sample_and_build_run machinery as simulate_run_from_group_signals() (which already accepts arbitrary per-group signals for the fit-model entry points) — it adds the checks a hand-authored signal needs and the model-driven entry points do not: strict array-length validation against the template, a per-group background, and a hard failure (rather than a silent clip to zero) when a signal would drive the expected counts negative.

Parameters:
  • template – Instrument template — bin structure, t0, grouping. Counts are ignored (see build_builtin_template() when no run is loaded, e.g. the "ideal_continuous_ring8" octant-ring template).

  • signals – Group id -> GroupSignal. Values may be negative and exceed |a| > 1; this is only rejected when it would make the expected counts negative (see Raises).

  • total_events – Expected number of detected decay events, summed over all detectors and the post-t0 window (see expected_counts()).

  • group_weights – Optional per-group relative count-rate (N0) weight, normalised over each group’s own detectors.

  • background_per_bin – Flat background counts per bin, either one value shared by every group or a per-group mapping (group_id -> counts/bin); a group absent from the mapping gets zero.

Raises:

ValueError – If a signal’s group id is not in the template’s grouping, if an array signal’s length does not exactly match the post-t0 bin count of every detector in its group, or if the generation would produce negative expected counts for any detector/bin.

asymmetry.core.simulate.simulate_run(template, model, parameters=None, *, total_events, seed=0, alpha=None, background_per_bin=0.0, run_number=None, title=None)[source]

Simulate a forward/backward run from a fit model (WiMDA Simulate).

model is either a CompositeModel (its function is bound with parameters) or a plain callable returning the asymmetry in percent on a time axis in microseconds — the same convention the fit panel uses. Forward-group detectors see +a(t), backward-group detectors −a(t) (every non-backward group counts as forward, as in WiMDA). The α split fixes the forward/backward group totals at 2α/(1+α) : 2/(1+α) of the event budget, divided equally among each side’s detectors, so the reduction recovers a(t) with α restored regardless of group sizes.

α defaults to the template grouping’s balance factor. See simulate_run_from_group_signals() for the sampling and provenance contract; the generating model expression, parameter values and α are recorded in metadata["simulation"].

asymmetry.core.simulate.simulate_count_run(template, model, parameters=None, *, total_events, seed=0, background_per_bin=0.0, run_number=None, title=None)[source]

Simulate per-group single-histogram count data (WiMDA evfactor path).

The count-domain counterpart of simulate_run(). Where simulate_run imprints the antisymmetric ±a(t) of a forward/backward asymmetry experiment, this imprints the same +a(t) on every detector group, so each group is an independent single-histogram measurement

N_g(t) = N₀_g · exp(−t/τ_μ) · [1 + a(t)] + b (t ≥ 0)

with no balancing backward detector — the non-FB convention WiMDA’s simulate-mode evfactor branch produces. The event budget is divided equally over the detectors (no α split), so each group’s N₀ follows its detector count.

The result is fittable by asymmetry.core.fitting.count_domain.fit_single_histogram() (side="forward" on any group), recovering the generating N₀, a(t) amplitude and flat background. Provenance records count_mode = True. Use simulate_run() when the data must instead exercise the α-free forward/backward count fit (fit_fb_alpha), which needs the antisymmetric pair.

asymmetry.core.simulate.simulate_double_pulse_run(template, model, parameters=None, *, total_events, dpsep_us, alpha=None, background_per_bin=0.0, seed=0, run_number=None, title=None)[source]

Simulate an ISIS double-pulse run (WiMDA double-pulse count model).

Two muon pulses separated by dpsep_us each carry the polarization, evaluated at t ± dpsep/2 and weighted by exp(∓dpsep/2τ_μ); the envelope stays at t and the single-pulse limit is dpsep_us → 0. Used to round-trip the double-pulse single-histogram fit (the generating model matches asymmetry.core.fitting.count_domain.fit_single_histogram()’s dpsep model).

class asymmetry.core.simulate.PeriodSpec(model, parameters=None, total_events=None, alpha=None, scale=1.0, label='')[source]

One period’s forward/backward signal for a two-period synthetic run.

Each period is an independent measurement: its own model (or the same model with different parameters), event budget and α balance, all imprinted with the standard forward/backward antisymmetry so the period reduces exactly like a real single-period run. total_events and alpha fall back to the run-level budget and the template grouping’s balance when None. scale multiplies the whole signal amplitude (0 makes the period a flat reference — the usual light-off / RF-off green — so G−R recovers the other period); it keeps the model’s own provenance intact rather than wrapping it in an opaque closure.

model
parameters = None
total_events = None
alpha = None
scale = 1.0
label = ''
__init__(model, parameters=None, total_events=None, alpha=None, scale=1.0, label='')
asymmetry.core.simulate.simulate_two_period_run(template, periods, *, total_events, seed=0, background_per_bin=0.0, period_mode=PeriodMode.RED, run_number=None, title=None)[source]

Simulate a two-period (red/green) run from per-period models.

Pulsed-source runs can be recorded in period mode (light-on/off, RF-on/off, ALC steps): one file holds several period histograms. This synthesises the two-period case — periods[0] is red (period 1), periods[1] green (period 2) — through the same Poisson forward model as simulate_run(), one independent draw per period from a single seeded generator (a fixed seed reproduces both periods bit-for-bit).

The returned Run carries the loader’s two-period payload (period_histograms, period_reduced, period_good_frames, period_dead_time_us, period_mode) with run.histograms cloned from the red period, so asymmetry.core.io.periods.select_period(), the green∓red combinations in reduce_run_to_dataset(), and degrade_run() all operate on it exactly as on a loaded period-mode file. The NeXus writer still emits a single period (study decision); a two-period synthetic run lives in-memory and through the project.

class asymmetry.core.simulate.GroupSignalSpec(group_id, amplitude, relative_phase=0.0, n0_weight=1.0, label='')[source]

Per-group amplitude, relative phase and count-rate weight for a TF ring.

The simulation analogue of a grouped time-domain fit’s per-group nuisance block (amplitude, relative_phase, N0 in asymmetry.core.fitting.grouped_time_domain): each detector group sees the shared normalised polarisation scaled by its own amplitude and phase-shifted by its own relative_phase, with n0_weight setting its relative count rate (detector efficiency).

group_id
amplitude
relative_phase = 0.0
n0_weight = 1.0
label = ''
__init__(group_id, amplitude, relative_phase=0.0, n0_weight=1.0, label='')
asymmetry.core.simulate.build_group_signals(model, specs, *, base_parameters=None)[source]

Build (group_signals, group_weights) for a multi-group simulation.

model is a normalised polarisation model (amplitude 1, background 0 — the grouped-fit contract), so its output is the dimensionless polarisation P(t) ≈ [−1, 1] directly (no percent conversion: the per-group amplitude owns the scale, exactly as in build_grouped_count_model()). Each spec forms a_g(t) = amplitude · P(t) and adds relative_phase (radians) to the model’s phase parameter(s); base_parameters supplies the shared model values. The returned weights are the per-group n0_weight values, fed to simulate_run_from_group_signals() which normalises them over the assigned detectors.

Raises ValueError if a non-zero relative_phase is requested for a model with no phase parameter.

asymmetry.core.simulate.simulate_multi_group_run(template, model, specs, *, total_events, seed=0, base_parameters=None, background_per_bin=0.0, run_number=None, title=None)[source]

Simulate a run with a distinct amplitude/phase per detector group.

The multi-group counterpart of simulate_run(): instead of the F/B α split it drives simulate_run_from_group_signals() with per-group signals built by build_group_signals() from specs and the shared normalised model. Use it to synthesise a TF ring whose groups differ in phase, seeded from a grouped time-domain fit’s nuisance parameters.

asymmetry.core.simulate.group_specs_from_grouped_fit(grouped_result)[source]

Extract per-group GroupSignalSpecs from a grouped fit result.

Reads the amplitude/relative_phase/N0 nuisance values from each group’s FitResult in a GroupedTimeDomainFitResult (duck-typed: any object exposing group_results). Groups with no fitted amplitude fall back to a 0.2 default. The shared model values are not captured here — pass them as base_parameters to build_group_signals() / simulate_multi_group_run().

asymmetry.core.simulate.degrade_run(run, factor, *, seed=0, run_number=None)[source]

Resample a run’s histograms to a different statistics level.

For factor < 1 each recorded count survives independently with probability factor (binomial thinning) — thinning a Poisson process is exactly Poisson, so the result is statistically indistinguishable from a run measured for factor times the beam time. For factor > 1 no exact construction from recorded data exists; the WiMDA convention Poisson(counts · factor) is used, which is over-dispersed relative to a genuinely longer measurement (variance λf(1+f) rather than λf).

Returns a new Run (the source run is untouched) with metadata["degraded"] provenance. A fixed seed reproduces the resampling bit-for-bit. grouping["good_frames"] (and the per-period frame counts) are scaled by factor — thinning by f is a measurement f times shorter, and an inherited deadtime correction only stays exact when counts and frames scale together. Combined two-period runs keep their period payload: each period’s histograms are thinned with the same generator and the stored per-period reductions are recomputed, so period selection keeps working on the derived run.

asymmetry.core.simulate.reduce_run_to_dataset(run, *, binning=None, cancel_check=None)[source]

Reduce synthetic counts and record their actual uncorrected observation.

asymmetry.core.simulate.total_events_of(run)[source]

Sum acquired counts, including background, for a simulation event budget.

For signal-only counts subtract the estimated flat background per bin times the total bins, as in matched_statistics().

asymmetry.core.simulate.estimate_background_per_bin(run)[source]

Estimate a run’s flat background from its pre-t0 bins (counts/bin).

The bins before t0 see no implanted-muon decay signal, so their mean count is the time-independent background level (zero for an ideal pulsed source). Returns the median across detectors for robustness, or 0.0 when no detector has a pre-t0 region.

asymmetry.core.simulate.matched_statistics(run)[source]

Plug-in signal budget and pre-t0 flat pedestal estimate for simulation.

The estimated pedestal is removed from the gross count before supplying a fixed signal budget; neither value propagates estimation uncertainty or guarantees a matched physical acquisition process.

asymmetry.core.simulate.simulate_capture_run(template, components, weights, *, total_events, group_id=None, seed=0, background_per_bin=0.0, run_number=None, title=None)[source]

Synthesise a μ⁻ capture-lifetime run.

Per detector in the signal group (or all detectors if group_id is None):

N_d(t) = Σ_i N_{i,d}·exp(−(t−t0)/τ_i) + b (t ≥ t0) N_d(t) = b (t < t0)

with the component populations split by weights (relative, normalised over the components) and the per-bin envelope using the same exact telescoping normalisation as expected_counts():

n0_i = N_{i,d}·(1−exp(−Δt/τ_i))

so the post-t0 window sum ≈ total_events. Detectors in group_id (or all detectors if None) carry the signal; background_per_bin is added in addition to the event budget. Poisson-sampled with seed and assembled (provenance, deadtime-zeroing) via asymmetry.core.simulate._sample_and_build_run. Provenance records capture_mode=True, the components/τ and weights, and the seed.

Parameters:
  • template – Geometry template — bin structure, t0, grouping. Counts are ignored.

  • components – Ordered sequence of CaptureComponent objects (duck-typed: need .label and .tau_us).

  • weights – Relative weight per component label. Normalised over the components present; missing labels default to zero weight. The provenance block records the raw (pre-normalisation) weights as passed.

  • total_events – Expected number of detected capture events in the post-t0 window, summed over all signal detectors.

  • group_id – Only detectors in this group carry the signal. If None, all detectors are signal detectors.

  • seed – RNG seed for bit-for-bit reproducibility.

  • background_per_bin – Flat background counts per bin added to every detector (signal and non-signal alike).

  • run_number, title – Provenance metadata for the returned Run.

Archetype presets

One-click textbook archetypes (Ag Kubo–Toyabe, EuO T-scan, F-μ-F, YBCO) that generate badged synthetic runs through the simulate pipeline.

Archetype gallery: one-click textbook synthetic runs.

Each preset pairs a built-in idealised instrument (asymmetry.core.simulate) with a fit model and a set of physically grounded parameters, and generates a first-class synthetic run — Poisson count histograms drawn through the same reduction chain as beamline data, badged with provenance — rather than a curve with Gaussian noise bolted on. The parameter values are the canonical textbook/literature numbers also used by the documentation screenshots (docs.screenshots.data.archetypes); here they drive the full simulate pipeline so the runs are fittable and recover their generating physics.

Reference for all archetypes: S. J. Blundell, R. De Renzi, T. Lancaster, and F. L. Pratt (eds.), Muon Spectroscopy: An Introduction (Oxford University Press, 2022). Per-preset chapters are named in each SimulatePreset.

This module is Qt-free and must stay importable without the GUI.

class asymmetry.core.simulate_presets.PresetRunSpec(model_name, model, parameters, title, temperature, field, field_state='ZF', total_events=40000000.0)[source]

One synthetic run within a preset (a scan member or a single run).

model_name
model
parameters
title
temperature
field
field_state = 'ZF'
total_events = 40000000.0
__init__(model_name, model, parameters, title, temperature, field, field_state='ZF', total_events=40000000.0)
class asymmetry.core.simulate_presets.SimulatePreset(key, label, chapter, description, template_key, seed, specs=<factory>)[source]

A named textbook archetype that generates one or more synthetic runs.

key
label
chapter
description
template_key
seed
specs
__init__(key, label, chapter, description, template_key, seed, specs=<factory>)
asymmetry.core.simulate_presets.ARCHETYPE_PRESETS = {'ag_lf_decoupling': SimulatePreset(key='ag_lf_decoupling', label='Ag — LF decoupling series', chapter='Ch. 5', description='Longitudinal-field decoupling of the same Ag Kubo–Toyabe: as B_L grows the relaxation is progressively decoupled, the textbook test of static nuclear dipolar fields.', template_key='ideal_pulsed_fb', seed=4100, specs=(PresetRunSpec(model_name='LFKuboToyabe', model=<function longitudinal_field_kubo_toyabe>, parameters={'A0': 24.0, 'Delta': 0.39, 'B_L': 0.0, 'baseline': 0.0}, title='Ag LF 0 G', temperature=20.0, field=0.0, field_state='ZF', total_events=40000000.0), PresetRunSpec(model_name='LFKuboToyabe', model=<function longitudinal_field_kubo_toyabe>, parameters={'A0': 24.0, 'Delta': 0.39, 'B_L': 10.0, 'baseline': 0.0}, title='Ag LF 10 G', temperature=20.0, field=10.0, field_state='LF', total_events=40000000.0), PresetRunSpec(model_name='LFKuboToyabe', model=<function longitudinal_field_kubo_toyabe>, parameters={'A0': 24.0, 'Delta': 0.39, 'B_L': 25.0, 'baseline': 0.0}, title='Ag LF 25 G', temperature=20.0, field=25.0, field_state='LF', total_events=40000000.0), PresetRunSpec(model_name='LFKuboToyabe', model=<function longitudinal_field_kubo_toyabe>, parameters={'A0': 24.0, 'Delta': 0.39, 'B_L': 50.0, 'baseline': 0.0}, title='Ag LF 50 G', temperature=20.0, field=50.0, field_state='LF', total_events=40000000.0))), 'ag_zf_kt': SimulatePreset(key='ag_zf_kt', label='Ag — ZF Gaussian Kubo–Toyabe', chapter='Ch. 5', description='Zero-field silver polycrystal: the canonical static nuclear-dipolar reference, a Gaussian Kubo–Toyabe with Δ = 0.39 µs⁻¹.', template_key='ideal_pulsed_fb', seed=2301, specs=(PresetRunSpec(model_name='StaticGKT_ZF', model=<function static_gkt_zf>, parameters={'A0': 24.0, 'Delta': 0.39, 'baseline': 0.0}, title='Ag ZF 20 K (Kubo–Toyabe)', temperature=20.0, field=0.0, field_state='ZF', total_events=40000000.0),)), 'euo_tscan': SimulatePreset(key='euo_tscan', label='EuO — ferromagnet through Tc', chapter='Ch. 6', description='Zero-field EuO temperature scan across the Curie point Tc = 69 K: spontaneous precession below Tc tracking the order parameter (1 − T/Tc)^β, paramagnetic relaxation above.', template_key='ideal_pulsed_fb', seed=1700, specs=(PresetRunSpec(model_name='Oscillatory', model=<function oscillatory>, parameters={'A0': 22.0, 'frequency': 22.286621524273773, 'phase': 0.0, 'Lambda': 0.1, 'baseline': 0.0}, title='EuO ZF 30 K (ordered)', temperature=30.0, field=0.0, field_state='ZF', total_events=40000000.0), PresetRunSpec(model_name='Oscillatory', model=<function oscillatory>, parameters={'A0': 22.0, 'frequency': 16.71551784090791, 'phase': 0.0, 'Lambda': 0.10017662469979105, 'baseline': 0.0}, title='EuO ZF 50 K (ordered)', temperature=50.0, field=0.0, field_state='ZF', total_events=40000000.0), PresetRunSpec(model_name='Oscillatory', model=<function oscillatory>, parameters={'A0': 22.0, 'frequency': 8.962772884123677, 'phase': 0.0, 'Lambda': 2.6647215537198186, 'baseline': 0.0}, title='EuO ZF 65 K (ordered)', temperature=65.0, field=0.0, field_state='ZF', total_events=40000000.0), PresetRunSpec(model_name='ExponentialRelaxation', model=<function exponential_relaxation>, parameters={'A0': 22.0, 'Lambda': 2.6647215537198186, 'baseline': 0.0}, title='EuO ZF 73 K (paramagnetic)', temperature=73.0, field=0.0, field_state='ZF', total_events=40000000.0), PresetRunSpec(model_name='ExponentialRelaxation', model=<function exponential_relaxation>, parameters={'A0': 22.0, 'Lambda': 0.10001914046956852, 'baseline': 0.0}, title='EuO ZF 90 K (paramagnetic)', temperature=90.0, field=0.0, field_state='ZF', total_events=40000000.0))), 'fmuf_pbf2': SimulatePreset(key='fmuf_pbf2', label='PbF₂ — F-μ-F entanglement', chapter='Ch. 4', description='Zero-field PbF₂: the muon binds two fluorine neighbours into an F-μ-F state whose characteristic dipolar beat pattern (r ≈ 1.17 Å) is the textbook fingerprint of muon-fluorine entanglement.', template_key='ideal_pulsed_fb', seed=8900, specs=(PresetRunSpec(model_name='FmuF_Linear+Constant', model=<asymmetry.core.fitting.composite.CompositeModel object>, parameters={'A_1': 22.0, 'r_muF': 1.17, 'A_bg': 0.2}, title='PbF₂ ZF 5 K (F-μ-F)', temperature=5.0, field=0.0, field_state='ZF', total_events=80000000.0),)), 'ybco_tf': SimulatePreset(key='ybco_tf', label='YBCO — transverse-field precession', chapter='Ch. 8', description='Normal-state YBa₂Cu₃O₇₋δ in a 200 G transverse field: Knight-shifted Larmor precession with a relaxation that broadens on entering the vortex state below Tc = 90 K.', template_key='ideal_pulsed_fb', seed=10100, specs=(PresetRunSpec(model_name='Oscillatory', model=<function oscillatory>, parameters={'A0': 20.0, 'frequency': 2.7235499999999995, 'phase': 0.0, 'Lambda': 0.08, 'baseline': 0.0}, title='YBCO TF 200 G 100 K (Knight shift)', temperature=100.0, field=200.0, field_state='TF', total_events=40000000.0),))}

Archetype presets keyed for the gallery menu.

asymmetry.core.simulate_presets.build_preset_runs(key, *, seed=None, run_number_allocator=None)[source]

Generate the synthetic run(s) of a named archetype preset.

Each run is produced by asymmetry.core.simulate.simulate_run() on the preset’s built-in instrument template, badged synthetic, and carries the preset key and textbook chapter in its metadata["simulation"] provenance. A scan preset (EuO, Ag LF) returns several runs; seeds are the preset’s fixed seed offset by the member index, so the family is reproducible. seed overrides the preset’s fixed base seed when given.

Raises KeyError for an unknown preset key.

Pull-distribution diagnostic

Simulate and refit under an explicit ideal-count experiment, retaining seeds, outcomes, source/synthetic recipes, and descriptive usable-subset pulls.

Conditional ideal-count simulation/refit summaries, independent of Qt.

Pull means and sample widths describe a common usable subset, not estimator bias, interval coverage or the adequacy of the acquired-data model.

class asymmetry.core.pull_diagnostic.ParameterPull(name, truth, pulls)[source]

Descriptive standardised residuals on the common usable subset.

name
truth
pulls
property n[source]
property mean[source]
property mean_uncertainty[source]

Reference SE 1/√N for independent standard-normal pulls only.

property width[source]

Sample SD; two observations suffice for a descriptive value.

property width_uncertainty[source]

Approximate SD reference SE under independent N(0,1) pulls only.

verdict()[source]

Measured quantities without directional error or coverage certification.

__init__(name, truth, pulls)
class asymmetry.core.pull_diagnostic.PullDistribution(request, attempts, stopped, recipes, runtime_json)[source]

Attempts are authoritative; counts and parameter samples are derived.

request
attempts
stopped
recipes
runtime_json
property n_attempted[source]
property n_fit_success[source]
property n_usable[source]
property n_failed[source]

Unsuccessful/unavailable refits; interrupted attempts remain separate.

property failure_reasons[source]
property parameters[source]
verdict()[source]
to_dict()[source]

Strict JSON-compatible provenance using the existing nonfinite codec.

classmethod from_dict(value)[source]

Restore recorded facts only; never execute a model or reconstruct history.

__init__(request, attempts, stopped, recipes, runtime_json)
class asymmetry.core.pull_diagnostic.PullAttempt(seed, fit_success, reason, values=(), errors=(), pulls=(), minos=(), recipe_index=None, message='', refit_provenance_json=None)[source]

One seed’s outcome; all tracked pulls are admitted or rejected together.

seed
fit_success
reason
values = ()
errors = ()
pulls = ()
minos = ()
recipe_index = None
message = ''
refit_provenance_json = None
__init__(seed, fit_success, reason, values=(), errors=(), pulls=(), minos=(), recipe_index=None, message='', refit_provenance_json=None)
class asymmetry.core.pull_diagnostic.RefitOutcome(success, values=<factory>, errors=<factory>, message='', minos=None, refit_provenance_json=None)[source]

Expected numerical outcome; coding errors and cancellation still propagate.

errors contains the symmetric reported errors. Optional MINOS signed offsets are separate, never substituted into pulls.

success
values
errors
message = ''
minos = None
refit_provenance_json = None
__init__(success, values=<factory>, errors=<factory>, message='', minos=None, refit_provenance_json=None)
class asymmetry.core.pull_diagnostic.PullRequest(canonical_json)[source]

Canonical JSON experiment; executable model/refit are supplied separately.

Template counts are excluded. The stored detector shapes, resolved timing, effective pair and binning reconstruct the supported ideal experiment. Custom callable settings are unknown unless explicitly declared by the caller. Loading this record never simulates or fits.

canonical_json
to_dict()[source]
classmethod from_dict(value)[source]
template()[source]

Reconstruct owned zero-count detector shapes, without any acquired buffers.

property requested_seeds[source]
__init__(canonical_json)
asymmetry.core.pull_diagnostic.make_pull_request(template, model, parameters, *, total_events, n_seeds=200, seed_start=0, track=None, alpha=None, background_per_bin=0.0, time_range=None, binning=None, source_recipe=None, refit_configuration=None)[source]

Validate an authored request once, using existing layout/binning authorities.

Non-unit beta, combined periods/acquisitions, fractional clock residuals and clipped/nonfinite model means have no matching generator here. Refusal affects this diagnostic only. Resolved integer detector origins and exclusions are supported; selected channels retain their native detector lengths.

asymmetry.core.pull_diagnostic.pull_model_unavailable_reason(model)[source]

Explain an unsupported count-generating request without restricting fitting.

asymmetry.core.pull_diagnostic.run_pull_distribution(template, model, parameters, refit, *, progress=None, should_continue=None, **settings)[source]

Validate/snapshot a request, then run the conditional experiment.

Call make_pull_request() before worker launch when caller-owned mutable inputs may change. Replay uses run_pull_request() with supplied code; JSON contains no executable functions or promise of cross-version identity.

asymmetry.core.pull_diagnostic.run_pull_request(request, model, refit, *, progress=None, should_continue=None)[source]

Execute a declarative request with the same supplied callable/environment.

Generation is indivisible. Cancellation is checked between generation, reduction and refit, and passed into numerical fitting. An interrupted seed stays in the partial record, without a fabricated nonconvergence.

Detached declarative inputs for conditional ideal-count pull experiments.

asymmetry.core.pull_request.pull_model_unavailable_reason(model)[source]

Explain an unsupported count-generating request without restricting fitting.

class asymmetry.core.pull_request.PullRequest(canonical_json)[source]

Canonical JSON experiment; executable model/refit are supplied separately.

Template counts are excluded. The stored detector shapes, resolved timing, effective pair and binning reconstruct the supported ideal experiment. Custom callable settings are unknown unless explicitly declared by the caller. Loading this record never simulates or fits.

canonical_json
to_dict()[source]
classmethod from_dict(value)[source]
template()[source]

Reconstruct owned zero-count detector shapes, without any acquired buffers.

property requested_seeds[source]
__init__(canonical_json)
asymmetry.core.pull_request.make_pull_request(template, model, parameters, *, total_events, n_seeds=200, seed_start=0, track=None, alpha=None, background_per_bin=0.0, time_range=None, binning=None, source_recipe=None, refit_configuration=None)[source]

Validate an authored request once, using existing layout/binning authorities.

Non-unit beta, combined periods/acquisitions, fractional clock residuals and clipped/nonfinite model means have no matching generator here. Refusal affects this diagnostic only. Resolved integer detector origins and exclusions are supported; selected channels retain their native detector lengths.

asymmetry.core.pull_request.request_binning(request)[source]

Restore the existing immutable binning value from a diagnostic request.

Qt-free adapter and captured single-fit inputs for conditional pull checks.

class asymmetry.core.pull_refit.EngineRefit(model, parameters, *, minos=False, frequency_offsets=None, error_oversampling=1.0)[source]

Own model, constraints and supported options; propagate numerical cancellation.

Frequencies and constraints remain in the laboratory frame. Source offset parameterisation is recorded, but synthetic refits optimise lab parameters. The engine’s symmetric parabolic errors enter pulls; optional MINOS signed offsets stay separate.

__init__(model, parameters, *, minos=False, frequency_offsets=None, error_oversampling=1.0)[source]
configuration()[source]
classmethod from_configuration(model, configuration)[source]

Replay supported declarative engine settings with a supplied model.

class asymmetry.core.pull_refit.PullFitInput(model, parameters, dataset, options_json)[source]

Execution-owner capture; later controls cannot reinterpret a completed fit.

model
parameters
dataset
options_json
classmethod capture(model, parameters, dataset, options)[source]
unavailable_reason()[source]
complete(result)[source]

Bind fitted plug-in values to launch constraints and selected support.

__init__(model, parameters, dataset, options_json)
class asymmetry.core.pull_refit.CapturedPullFit(source, result_json)[source]

Cheap completed-execution binding; numerical preparation runs on the worker.

source
result_json
classmethod capture(source, result)[source]
presentation()[source]
prepare()[source]
__init__(source, result_json)

Physical constants

Physical constants and period-mode identifiers relevant to μSR.

The exact defining values follow the revised SI, effective in 2019. Measured magnetic constants use the CODATA 2018 adjustment, independent of the installed SciPy version. Uncertainties below are standard uncertainties; unit conversions are exact. Explicit approximations retain their stated precision.

Sources

class asymmetry.core.utils.constants.PeriodMode(*values)[source]

Supported combination modes for two-period muon data.

RED = 'red'
GREEN = 'green'
GREEN_MINUS_RED = 'green_minus_red'
GREEN_PLUS_RED = 'green_plus_red'
asymmetry.core.utils.constants.ORDER_KEYS = ('field', 'temperature', 'run')

Allowed ordering keys for run series and field scans — the per-run variable an x-axis is sorted by. Shared by asymmetry.core.representation.series.FitSeries and asymmetry.core.transform.integral.build_field_scan() so the two cannot drift.

asymmetry.core.utils.constants.PLANCK_CONSTANT_J_S = 6.62607015e-34

Planck constant h in J s; revised SI (2019), exact.

asymmetry.core.utils.constants.ELEMENTARY_CHARGE_C = 1.602176634e-19

Elementary charge e in C; revised SI (2019), exact.

asymmetry.core.utils.constants.BOLTZMANN_CONSTANT_J_PER_K = 1.380649e-23

Boltzmann constant k_B in J/K; revised SI (2019), exact.

asymmetry.core.utils.constants.AVOGADRO_CONSTANT_PER_MOL = 6.02214076e+23

Avogadro constant N_A in mol⁻¹; revised SI (2019), exact.

asymmetry.core.utils.constants.REDUCED_PLANCK_CONSTANT_J_S = 1.0545718176461565e-34

Reduced Planck constant ħ = h/(2π) in J s; exact SI relation.

asymmetry.core.utils.constants.MAGNETIC_FLUX_QUANTUM_WB = 2.0678338484619295e-15

Magnetic flux quantum Φ₀ = h/(2e) in Wb; exact SI relation.

asymmetry.core.utils.constants.BOLTZMANN_CONSTANT_MEV_PER_K = 0.08617333262145178

Boltzmann constant k_B in meV/K; exact SI relation, 1 eV = e J/C.

asymmetry.core.utils.constants.MOLAR_GAS_CONSTANT_J_PER_MOL_K = 8.31446261815324

Molar gas constant R = N_A k_B in J/(mol K); exact SI relation.

asymmetry.core.utils.constants.MUON_MAGNETIC_MOMENT_J_PER_T = -4.4904483e-26

Negative-muon magnetic moment in J/T; CODATA 2018, uncertainty 1.0e-33 J/T.

asymmetry.core.utils.constants.MUON_GYROMAGNETIC_RATIO_MHZ_PER_T = 135.5388095

Muon γ_μ/(2π) magnitude in MHz/T; CODATA 2018 2|μ_μ|/h, uncertainty 0.0000030 MHz/T.

asymmetry.core.utils.constants.ELECTRON_GYROMAGNETIC_RATIO_RAD_PER_S_PER_T = 176085963023.0

Electron gyromagnetic-ratio magnitude in rad/(s T); CODATA 2018, uncertainty 53 rad/(s T).

asymmetry.core.utils.constants.PROTON_GYROMAGNETIC_RATIO_MHZ_PER_T = 42.577478

Proton γ_p/(2π) in MHz/T; truncated CODATA 2018 value 42.577478518(18).

asymmetry.core.utils.constants.VACUUM_PERMEABILITY_OVER_4PI_H_PER_M = 1.00000000055e-07

Vacuum μ₀/(4π) in H/m; CODATA 2018, uncertainty 1.5e-17 H/m, not exact.

asymmetry.core.utils.constants.MUON_LIFETIME_US = 2.1969811

Muon lifetime in μs; PDG 2024, uncertainty 0.0000022 μs.

asymmetry.core.utils.constants.PION_LIFETIME_US = 0.026

Charged-pion lifetime in μs; rounded from PDG 2024 0.026033(5) μs. Sets the surface-muon pulse-arrival time scale in the MaxEnt response.

asymmetry.core.utils.constants.FLUORINE_19_GYROMAGNETIC_RATIO_MHZ_PER_T = 40.069243717

Fluorine-19 γ_F/(2π) in MHz/T; Stone (2019) moment 2.628321(4) μ_N converted with CODATA 2018 μ_N/h. Uncertainty 0.000061 MHz/T.

asymmetry.core.utils.constants.MUONIUM_VACUUM_HYPERFINE_MHZ = 4463.302765

Vacuum muonium hyperfine interval in MHz; Liu et al. (1999), uncertainty 0.000053 MHz. Used as a fit starting value.

asymmetry.core.utils.constants.CELSIUS_ZERO_K = 273.15

Celsius zero in K; exact SI relation, BIPM SI Brochure, 9th ed., section 2.3.1. https://www.bipm.org/en/publications/si-brochure

asymmetry.core.utils.constants.GAUSS_TO_TESLA = 0.0001

Tesla per gauss; exact unit definition, 1 G = 10⁻⁴ T.

asymmetry.core.utils.constants.ELECTRON_GYROMAGNETIC_RATIO_RAD_PER_US_PER_G = 17.6085963023

Electron gyromagnetic-ratio magnitude in rad/(μs G); CODATA 2018, exact conversion of the SI value.

Run arithmetic

asymmetry.core.data.combine.combine_runs accepts finite signed scales. The first coefficient equals scales[0]; later coefficients equal sign * scales[i]. Counts combine linearly and independent variances use squared coefficients, retained in Histogram.count_variance. NaN denotes explicitly unknown per-bin noise; only a consumed unknown bin blocks preparation. Zero terms are recorded but excluded from operation domains; nonfinite/all-zero requests and known direct reuse raise CombineError. Corresponding period payloads use the same coefficients; mixed/mismatched payloads require explicit selection. reduce_combined_run prepares each retained acquisition using its own correction facts and resolved clock, then weights and pools on common observed good support. The returned dataset records an immutable counts-first replay snapshot; the raw inspection sum alone does not authorise reconstruction. Shared group background is applied once. See Run arithmetic: co-add and co-subtract for exposure and likelihood eligibility. Ordinary GUI co-add remains unit weighted. Core weighted Runs are transient in-memory results; saved reduced results and recipes do not supply histogram reconstruction. A project/browser definition that cannot reproduce its saved coefficients or selected periods retains its observations or unavailable state and history, including after a later source rebuild.

Calibration

asymmetry.core.data.calibration.WEAK_TF_FIELD_RANGE_GAUSS

Applied-field window (Gauss, on abs(field)) a weak transverse-field calibration run conventionally sits in. The lower bound rejects a nominal zero-field run that merely carries a stray transverse token; the upper bound rejects a high-field measurement run. These are advisory bounds for highlighting a likely calibration run, not a hard classification — the user can always pick any run from the dropdown.

asymmetry.core.data.calibration.classify_tf_calibration_run(metadata)[source]

Classify a run’s metadata as a likely weak-TF calibration run.

Parameters:

metadata – A run’s metadata mapping. The keys consulted are field_direction (the loader’s structured geometry classification: "Transverse" / "Longitudinal" / "Zero field" / ""), field (applied field magnitude in Gauss), and the title / comment free text.

Returns:

TFCalibrationVerdict – is_candidate is True when the run shows explicit transverse-field evidence (structured geometry or a text token) and any recorded field magnitude sits in WEAK_TF_FIELD_RANGE_GAUSS.

Run combination

class asymmetry.core.data.combine.CombineError[source]

Raised when runs cannot be combined at the count level.

asymmetry.core.data.combine.combine_runs(runs, *, sign=1, scales=None, run_number=None, label=None, subtract_method='reference', cancel_check=None)[source]

Combine the raw histograms of runs at the count level.

Parameters:
  • runs – Two or more loaded runs with detector histograms. Every run must share the same detector count and (per detector) bin width; differing per-detector t0 values are aligned before summing (the ISIS norm of a single shared t0 takes the trivial path).

  • sign – +1 co-adds (runs[0] + runs[1] + …); -1 co-subtracts (runs[0] − Σ scaleₖ·runsₖ for k ≥ 1). Co-subtract is the reference-run path: runs is [sample, reference] and scales is [1.0, frame_ratio].

  • scales – Finite signed per-run multipliers (length len(runs)), default one. Zero terms do not participate in compatibility or noise requirements. runs[0] is always taken at its own scale (normally 1.0).

  • run_number – Run number for the combined run. Defaults to runs[0].run_number (the GUI passes a negative synthetic id).

  • label – Optional explicit run_label; otherwise built from the constituents ("a + b" for add, "a − b" for subtract).

  • subtract_method – For sign == -1 only. "reference" (default) is the frame-scaled reference subtraction [sample, reference] with scales = [1.0, frame_ratio] (exactly two runs). "signed" is the symmetric N-run signed co-subtract runs[0] − Σ scaleₖ·runsₖ (k ≥ 1), every term contributing its retained independent variance — for photo-µSR laser-on/off and background-style differences over more than two runs.

  • cancel_check – Optional cooperative cancellation callback, checked between detectors and original acquisition records. Raising aborts without changing sources.

Returns:

Run – A first-class run with summed (or differenced) histograms, mirrored grouping, accumulated good frames, master scalar metadata with spread keys, and a metadata["combination"] provenance block. For a subtraction the independent noise is retained in each histogram’s count_variance.

Raises:

CombineError – Fewer than two runs, empty histograms, or mismatched detector count / bin width.

Ratio validity

class asymmetry.core.data.ratio_validity.RatioValidity(reasons)[source]

One byte per output bin, classified before replacing mathematical zero errors.

Undefined ratios take precedence over zero variance. Full acquisition grids and contributing counts remain independent of Gaussian selection.

Instrument

asymmetry.core.instrument.INSTRUMENT_NAMES

Registry keys of all supported instrument layouts. "GPS" (6-detector PSI-BIN), "GPS-RD" (11-detector ROOT sub-detectors) and "GPS-RD15" (15-detector ROOT export carrying the combined counters and the sub-detectors) are three variants of the one physical GPS instrument; they share the display name “GPS” and are collapsed to a single dropdown entry by instrument_choices_for().

asymmetry.core.instrument.instrument_choices_for(active_name=None)[source]

Return [(display_name, registry_key)] for the instrument dropdown.

Variant families (e.g. the 6-detector PSI-BIN "GPS", the 11-detector ROOT "GPS-RD" and the 15-detector ROOT "GPS-RD15") collapse to a single entry under their shared display name, so the user only ever sees one “GPS”. The variant exposed for a family is the one whose key equals active_name (the currently-loaded layout); otherwise the family default (first registry key) is used.

Global fit studies

class asymmetry.core.representation.global_fit_study.GlobalFitStudy(study_id, name, parameter_name, x_key, x_label, group_variable_key, group_variable_label, created, updated, source_group_ids=<factory>, groups=<factory>, model=None, config=<factory>, result=None, fit_x_min=nan, fit_x_max=nan, input_digest='')[source]

A named, persisted cross-group global parameter fit.

study_id is caller-supplied (the GUI derives a deterministic modelfit-<digest> id, matching the existing decoration-keying scheme used by asymmetry.gui.windows.global_parameter_fit_window) — this module never generates one.

input_digest is a caller-computed hash of the snapshot groups arrays (see compute_group_input_digest()); it lets a GUI detect that a study’s inputs have drifted from the live trend data (“stale”) without this dataclass storing a stale flag itself — staleness is a runtime property recomputed by comparing the stored digest against a freshly computed one, never persisted.

asymmetry.core.representation.global_fit_study.compute_group_input_digest(groups)[source]

Return a stable short hash over groups’ identity and data arrays.

Used by the GUI to detect that a study’s stored snapshot has drifted from the live trend data (“stale”): a study records the digest of the groups it was fit against, and a fresh call against the current trend rows is compared against it.

Groups are sorted by group_id before hashing so that permuting the input list (e.g. a different multi-select order in the trend panel) never changes the digest — only the content of the groups matters. Arrays are rounded to a fixed number of decimal digits before hashing so that harmless floating-point representation differences (e.g. serialize round trip through JSON, or platform-dependent float repr) do not register as a spurious staleness signal; the rounded array’s raw bytes (.tobytes()) are hashed rather than a text repr(), which keeps the digest deterministic across platforms (unlike repr(), whose float formatting is not guaranteed to be byte-identical across numpy builds).

Joint fit records

class asymmetry.core.representation.joint_fit.JointFit(joint_id, label, rep_type, member_batch_ids=<factory>, shared=<factory>, result=None, analysis_history=None)[source]

A named, persisted joint fit over two or more member series.

joint_id is caller-supplied (mirroring GlobalFitStudy, this module never mints one). member_batch_ids is ordered — the order the member series were ticked in, which also defines the seed order used to pick a shared row’s initial value/bounds from “the first contributing series”. shared is a plain list of dicts rather than a dataclass: it is exactly what the window’s shared-parameter table edits, and a fourth column type (min/max/value) would buy nothing a dict does not already give a JSON round trip. result holds only the last run’s summary — shared values, uncertainties, the shared covariance block, combined and per-series χ², a timestamp — never curves; the curves are each member series’ own results_by_run, already persisted there.

Fit series

class asymmetry.core.representation.series.FitSeries(batch_id, rep_type, *, label=None, member_kind='runs', member_run_numbers=None, member_source_run=None, order_key='run', canonical_model=None, analysis_history=None, param_roles=None, nuisance_params=None, results_by_run=None, extra=None, source_group_id=None, group_id=None, excluded_run_numbers=None, last_fitted_members=None, recipe=None, trend_excluded_runs=None, joint_fit_id=None, shared_params=None, projection=None, member_frames=None)[source]

An ordered series of members fit with one canonical model.

Members are keyed by integer in member_run_numbers. For member_kind == "runs" the key is the run number; for member_kind == "groups" it is the synthetic negative group key, and member_source_run maps each key back to its physical source run (used for field/temperature ordering and metadata).

FitSeries.member_run_numbers

Ordered integer member keys: run numbers or synthetic detector-group keys.

FitSeries.member_source_run

Source acquisition for each member key in a detector-group series.

Run surveys

asymmetry.core.workflow.survey.LARMOR_FREQUENCY_TOLERANCE

How far the dominant line may sit from the Larmor frequency of the recorded field and still be called Larmor precession, as a fraction of that frequency. On the corpus the true transverse-field runs land 3–14 % high (the FFT bin is coarse and the recorded field is nominal), while the runs that must be rejected — ordered magnets precessing in their own internal field — are off by factors of 4 to 40. A quarter separates the two with room on both sides.

asymmetry.core.workflow.survey.PRECESSION_SNR_FLOOR

Dominant-FFT SNR a line must clear before the survey will call it precession at all. Measured across the muon-school corpus: genuine weak-transverse-field runs at 20 G and 100 G score 89–418, while the longitudinal decoupling runs ISIS stamps Transverse at 40–120 G score about 3. Ten sits in the empty gap between the two populations.

class asymmetry.core.workflow.survey.ScanGroup(axis, instrument, geometry, geometry_note, temperature, field, runs, values, notes='', samples=(), n_periods=1)[source]

A set of runs on one instrument that vary one quantity, holding another.

axis is the varying quantity ("temperature" or "field"); instrument plus the other quantity (field for a temperature scan, temperature for a field scan) are what the group holds fixed. runs and values are parallel and ordered along the axis.

Geometry is a property of the group, not part of its key. A physical scan is one scan even when the survey can only resolve the geometry of part of it — a magnet’s transverse-field scan resolves above its transition and not below — so geometry is the members’ single agreed geometry, and None with a geometry_note when they disagree.

Work directories

WorkDir.bind(folder, instrument)[source]

The runs this session serves for folder and instrument; raise if it holds others.

The single gate every command passes before it touches the directory, so no command can mix two data folders, or two instruments’ runs, into one cache (see the module docstring). Both paths are resolved, so the same folder named relatively and absolutely is the same folder. The answer is the narrower selection of the two: a session holding every run in its folder takes on the instrument a command names, and a command naming none reads the instrument the session holds. Raises WorkDirMismatchError when the manifest names a different folder or a different instrument.

class asymmetry.core.workflow.workdir.WorkDirMismatchError(*, root, bound, requested)[source]

A work directory was asked to serve runs that are not the ones it holds.

Carries the directory and both selections so a caller can phrase the message in its own vocabulary; str is already a complete sentence naming them.