Data transforms

The transform layer is the sequence of operations applied to raw per-detector histograms before any model fit sees them: deadtime correction (deadtime()), background subtraction (background()), grouping into forward and backward detector sums (align_forward_backward()), asymmetry calculation with the chosen \(\alpha\) calibration constant (compute_asymmetry(), estimate_alpha()), and count binning before the asymmetry ratio is formed (BinningSpec). The order is fixed: deadtime → grouping → background → count binning → asymmetry. The user-facing documentation of these steps and of Asymmetry’s conventions (alpha applied to the backward group; Mantid-style uncertainty handling at zero denominator) is in Data processing.

Validated grouped counts

align_forward_backward() aligns the selected detectors and records their shifts and terminal crop in an AlignmentCrop. corrected_grouped_counts() returns a ForwardBackwardCounts containing both groups, their independent variances and shared components, an inclusive BinWindow, and the time grid. Count arrays are owned, read-only snapshots. Background provenance records constant levels; exported standard errors derive from the shared components.

Validated grouped counts and their aligned acquisition-bin coordinates.

class asymmetry.core.transform.fb_counts.BinWindow(first, last, label='good-bin window')[source]

Inclusive, zero-based window in aligned grouped-bin coordinates.

first
last
label = 'good-bin window'
validate_length(n_bins, *, label='good-bin window')[source]
property slice[source]
__init__(first, last, label='good-bin window')
asymmetry.core.transform.fb_counts.good_window(grouping, n_bins)[source]

Read a declared window; absent endpoints select the full aligned record.

asymmetry.core.transform.fb_counts.validated_count_arrays(*arrays)[source]

Validate a public count-array boundary without truncation or broadcasting.

asymmetry.core.transform.fb_counts.count_timing(bin_width_us, common_t0_bin, t0_time_us)[source]

Validate a uniform acquisition grid, returning its width and exact t0 in μs.

class asymmetry.core.transform.fb_counts.SharedComponent(name, variance, sensitivity, count_covariance)[source]

One shared parameter’s variance, sensitivity and raw-count covariance.

For corrected counts c = r + g(θ̂ − θ), sensitivity is g and count_covariance is cov(r, θ̂). Components in a group must describe mutually independent parameters; all arrays use its acquisition bins.

name
variance
sensitivity
count_covariance
__init__(name, variance, sensitivity, count_covariance)
class asymmetry.core.transform.fb_counts.GroupCounts(counts, variance=None, shared=(), noise=None)[source]

Grouped counts with independent variance and shared parameter components.

variance=None denotes the Poisson count model. Arrays are copied and read-only, so changing an input buffer cannot invalidate the checked shape.

counts
variance = None
shared = ()
noise = None
classmethod from_value(value)[source]

Accept an existing validated group or raw Poisson count arrays.

property independent_variance[source]

Independent count variance before any shared correction components.

__init__(counts, variance=None, shared=(), noise=None)
asymmetry.core.transform.fb_counts.linear_combination_variance(group, edges, weights=None)[source]

Variance of each weighted bin sum, including estimation-window overlap.

For coefficients a, each shared parameter adds (Σag)² var(θ̂) + 2(Σag)(Σa cov(r, θ̂)) to the independent Poisson term Σa²v. Edges select half-open acquisition-bin intervals; weights cover the whole group.

class asymmetry.core.transform.fb_counts.AlignmentCrop(common_t0_bin, detector_offsets, group_lengths, length, first_bin=0, timing_residuals_us=(), timing_sources=(), timing_strategy='', acquired_detectors=())[source]

Observed-bin mapping; offsets and anchor use the cropped local coordinate.

common_t0_bin
detector_offsets
group_lengths
length
first_bin = 0
timing_residuals_us = ()
timing_sources = ()
timing_strategy = ''
acquired_detectors = ()
property timing_spread_us[source]

Full residual range in μs; an integer approximation, not uncertainty.

to_dict()[source]

Export the resolved mapping and derived fractional spread in μs.

window(grouping, *, offset_bins=0)[source]

Translate explicit bounds to this grid, then intersect leading support.

offset_bins maps the request’s aligned coordinate to the uncropped grid. Absent endpoints select observed support without translation.

__init__(common_t0_bin, detector_offsets, group_lengths, length, first_bin=0, timing_residuals_us=(), timing_sources=(), timing_strategy='', acquired_detectors=())
asymmetry.core.transform.fb_counts.crop_to_good_support(alignment, window)[source]

Remove unused context while retaining nonnegative local t0 coordinates.

Raw k maps to local r by the detector offset. Removing L leading bins subtracts L from both that offset and t0, preserving elapsed time in µs.

class asymmetry.core.transform.fb_counts.ForwardBackwardCounts(forward, backward, t0_time_us, bin_width_us, window, alignment, corrections=CorrectionOutcomes(deadtime=CorrectionOutcome(name='deadtime', requested='off', status=<CorrectionStatus.OFF: 'off'>, reason=None, effective=None, uncertainty=None), background=CorrectionOutcome(name='background', requested='none', status=<CorrectionStatus.OFF: 'off'>, reason=None, effective=None, uncertainty=None)), calibration_window=None, effective_recipe=None)[source]

Aligned forward/backward counts with one validated window and time grid.

alignment owns the common t0 bin; t0_time_us preserves any sub-bin residual. Background provenance stores its constant levels; standard errors are exported from the shared count components.

forward
backward
t0_time_us
bin_width_us
window
alignment
corrections = CorrectionOutcomes(deadtime=CorrectionOutcome(name='deadtime', requested='off', status=<CorrectionStatus.OFF: 'off'>, reason=None, effective=None, uncertainty=None), background=CorrectionOutcome(name='background', requested='none', status=<CorrectionStatus.OFF: 'off'>, reason=None, effective=None, uncertainty=None))
calibration_window = None
effective_recipe = None
property common_t0_bin[source]
property background_level[source]
__init__(forward, backward, t0_time_us, bin_width_us, window, alignment, corrections=CorrectionOutcomes(deadtime=CorrectionOutcome(name='deadtime', requested='off', status=<CorrectionStatus.OFF: 'off'>, reason=None, effective=None, uncertainty=None), background=CorrectionOutcome(name='background', requested='none', status=<CorrectionStatus.OFF: 'off'>, reason=None, effective=None, uncertainty=None)), calibration_window=None, effective_recipe=None)
asymmetry.core.transform.fb_counts.native_time_window(time, good_window, bounds)[source]

Select inclusive native observations, using good support for omitted bounds.

asymmetry.core.transform.fb_counts.native_count_time(length, bin_width_us, common_t0_bin, t0_time_us)[source]

Stamp native bin centres using the local anchor plus exact-t0 residual.

from asymmetry.core.transform.rebin import binning_spec

counts = corrected_grouped_counts(
    histograms=run.histograms, grouping=run.grouping,
    forward_idx=[0], backward_idx=[1],
    use_deadtime=False, deadtime_mode="off", use_background=False,
)
time, asymmetry, error = binned_fb_asymmetry(
    counts, binning=binning_spec(run.grouping), alpha=1.0,
)

time is in μs; asymmetry and error are fractions. The good-bin window is selected before binning, and counts are summed before forming the ratio. See Histogram binning for rejection messages.

Authored correction requests use deadtime_mode with "off", "from_file", "manual", or "estimate"; the documented "file" input spelling is also accepted. deadtime_method records estimator or table provenance and does not select the request. Authored coefficients require an explicit request mode. File-table lookup retains acquired coefficient origin separately from an authored calibration. Authored tables use dead_time_us; fixed background pairs use background_fixed_values. Unsupported authored aliases raise a contextual error. Released project spellings are interpreted by project persistence before reduction, without changing correction mathematics.

Asymmetry calculation

Compute the μSR asymmetry from grouped histograms.

The corrected asymmetry is defined as

A(t) = [N_F(t) − α N_B(t)] / [β N_F(t) + α N_B(t)]

where N_F and N_B are the forward and backward group counts, α is the count-rate balance (detector efficiencies × solid angles) and β is the intrinsic-asymmetry balance β = A_{0,B}/A_{0,F} (musrfit asymmetry fit type 2; β multiplies the forward counts in our α-on-backward convention, which is algebraically identical to musrfit’s α-on-forward form with α_musrfit = 1/α). β = 1 recovers the standard formula A = (F − αB)/(F + αB).

Scale: count-to-ratio outputs are dimensionless fractions, never percent. Signed corrected counts and general beta need not give values in [-1, 1]. See asymmetry.core.transform.units and “Asymmetry units across the API” in the documentation for the whole picture.

asymmetry.core.transform.asymmetry.compute_asymmetry(forward, backward, alpha=1.0, beta=1.0)[source]

Calculate fractional asymmetry and its first-order Poisson error.

Alpha/beta are fixed. Zero-denominator and degenerate raw-count bins use a fallback error of one fraction, which still has finite Gaussian weight.

Scale

This primitive returns the dimensionless fraction (and a fractional error), matching the textbook definition above. Note this differs from the loaded MuonDataset surface: ds.asymmetry / ds.error are on the percent scale (the loaders multiply this fraction by 100, the WiMDA-style convention the time-domain fit models also use). When you need an explicit scale from a dataset, use ds.asymmetry_fraction / ds.asymmetry_percent rather than assuming one — seeding a fit with fraction-scale amplitudes against percent-scale data converges to the wrong minimum.

Parameters:
  • forward, backward – Counts in the forward and backward detector groups (same length).

  • alpha – Count-rate balance parameter (α).

  • beta – Intrinsic-asymmetry balance parameter (β = A_{0,B}/A_{0,F}); the default 1.0 is the standard formula.

returns:

tuple of numpy.ndarray – As a fraction, with the error on the same scale — not percent. Arrays of the same length as the inputs. Scale by 100 (or asymmetry.core.transform.units.to_percent()) before handing these to anything percent-scale: a MuonDataset, a fit model’s A0, fit_arrays().

asymmetry.core.transform.asymmetry.compute_asymmetry_with_count_errors(forward, backward, forward_error, backward_error, alpha=1.0, beta=1.0)[source]

Calculate asymmetry from counts with supplied count uncertainties.

First-order propagation uses retained count uncertainties, including for signed background-corrected counts, conditional on fixed alpha/beta. A zero denominator returns value zero/error one; a defined ratio with zero count-variance contribution retains error one. These fallbacks have finite weight if passed as bare arrays. Known histogram datasets carry a separate mathematical classification so Gaussian fits omit these fallbacks. No calibration covariance is added. The asymmetry convention remains Asymmetry’s convention, with alpha multiplying the backward group (and beta the forward group in the denominator).

Parameters:
  • forward, backward, forward_error, backward_error – Counts and their 1σ count uncertainties (count domain — no asymmetry scale involved on the way in).

  • alpha, beta – As in compute_asymmetry().

Returns:

tuple of numpy.ndarray – As a fraction, exactly as compute_asymmetry() — not percent.

asymmetry.core.transform.asymmetry.ratio_with_count_errors(forward, backward, forward_error, backward_error, alpha=1.0, beta=1.0)[source]

Form a histogram ratio and classify it before numerical display fallbacks.

asymmetry.core.transform.asymmetry.slice_to_good_window(asymmetry, error, window, *, common_t0, bin_width, t0_time_us=None)[source]

Slice reduced arrays to a validated inclusive aligned-bin window.

Bin k is stamped at its centre relative to exact t0, (k + 0.5)·w − t0. The bin-centre default preserves the integer-bin axis exactly.

asymmetry.core.transform.asymmetry.estimate_alpha(forward, backward, *, first_good_bin=None, last_good_bin=None)[source]

Estimate the detector-balance parameter alpha from grouped counts.

This follows the same approach used by Mantid’s AlphaCalc algorithm:

\[\alpha = \frac{\sum_i F_i}{\sum_i B_i}\]

where \(F_i\) and \(B_i\) are forward and backward grouped counts integrated over the selected good-bin window.

Parameters:
  • forward, backward – Forward and backward grouped count arrays.

  • first_good_bin, last_good_bin – Optional inclusive bin range for integration. If omitted, the full length of the arrays is used.

Returns:

float – Finite positive estimated alpha value.

Raises:

asymmetry.core.transform.corrections.CorrectionUnavailableError – No bins are available, either integral is nonpositive, or their ratio is not finite and positive. A failed estimate has no default coefficient.

class asymmetry.core.transform.asymmetry.AlphaEstimate(alpha, alpha_error, method, n_bins_used, objective_value, ok, message='')[source]

Result of an alpha estimation.

alpha_error is absent for the quick diamagnetic and General estimates. ratio reports a first-order standard error of the detector-group sums, including represented shared counting terms. Estimate plus/minus this error is not an exact confidence interval; polarisation and model bias are excluded. objective_value is the minimised objective for the optimising methods and None for the ratio method.

alpha
alpha_error
method
n_bins_used
objective_value
ok
message = ''
__init__(alpha, alpha_error, method, n_bins_used, objective_value, ok, message='')
asymmetry.core.transform.asymmetry.estimate_alpha_detailed(forward, backward, *, method='diamagnetic', time_us=None, first_good_bin=None, last_good_bin=None, cancel_check=None)[source]

Estimate alpha using a quick balance or the integral ratio.

diamagnetic minimises weighted asymmetry power on internally packed, positive bins. general equates early/late lifetime-corrected densities at beta = 1 and requires time_us in microseconds relative to t0. Both return alpha_error=None. ratio uses the raw window sums and reports first-order uncertainty, including supplied shared background terms.

General rejects rounding-level window contrast. Its existing diagnostic re-frees alpha across eight sub-windows to check the lifetime assumption: a deviation exceeding both 0.15% and 2.5 standard errors sets ok=False. This diagnostic uses a Poisson count approximation and does not certify identifiability, corrected-data uncertainty, or noisy weak-contrast recovery. objective_value is the flatness chi-square, or weighted asymmetry power for Diamagnetic; it is absent for the ratio. See the alpha calibration reference for assumptions and diagnostic limits.

cancel_check is an optional raising check, polled at preparation boundaries, before each Diamagnetic objective and General diagnostic sub-window, and before return. Its exception propagates unchanged; no partial estimate is returned. Individual NumPy calls run to completion.

asymmetry.core.transform.asymmetry.compute_asymmetry(forward, backward, alpha=1.0, beta=1.0)[source]

Calculate fractional asymmetry and its first-order Poisson error.

Alpha/beta are fixed. Zero-denominator and degenerate raw-count bins use a fallback error of one fraction, which still has finite Gaussian weight.

Scale

This primitive returns the dimensionless fraction (and a fractional error), matching the textbook definition above. Note this differs from the loaded MuonDataset surface: ds.asymmetry / ds.error are on the percent scale (the loaders multiply this fraction by 100, the WiMDA-style convention the time-domain fit models also use). When you need an explicit scale from a dataset, use ds.asymmetry_fraction / ds.asymmetry_percent rather than assuming one — seeding a fit with fraction-scale amplitudes against percent-scale data converges to the wrong minimum.

Parameters:
  • forward, backward – Counts in the forward and backward detector groups (same length).

  • alpha – Count-rate balance parameter (α).

  • beta – Intrinsic-asymmetry balance parameter (β = A_{0,B}/A_{0,F}); the default 1.0 is the standard formula.

returns:

tuple of numpy.ndarray – As a fraction, with the error on the same scale — not percent. Arrays of the same length as the inputs. Scale by 100 (or asymmetry.core.transform.units.to_percent()) before handing these to anything percent-scale: a MuonDataset, a fit model’s A0, fit_arrays().

asymmetry.core.transform.asymmetry.estimate_alpha(forward, backward, *, first_good_bin=None, last_good_bin=None)[source]

Estimate the detector-balance parameter alpha from grouped counts.

This follows the same approach used by Mantid’s AlphaCalc algorithm:

\[\alpha = \frac{\sum_i F_i}{\sum_i B_i}\]

where \(F_i\) and \(B_i\) are forward and backward grouped counts integrated over the selected good-bin window.

Parameters:
  • forward, backward – Forward and backward grouped count arrays.

  • first_good_bin, last_good_bin – Optional inclusive bin range for integration. If omitted, the full length of the arrays is used.

Returns:

float – Finite positive estimated alpha value.

Raises:

asymmetry.core.transform.corrections.CorrectionUnavailableError – No bins are available, either integral is nonpositive, or their ratio is not finite and positive. A failed estimate has no default coefficient.

Grouping

Detector grouping utilities.

Groups individual detector histograms into forward / backward (or custom) groups by summing their counts.

exception asymmetry.core.transform.grouping.InvalidGroupingError(message, grouping)[source]

An unavailable request retained verbatim so project/UI boundaries can edit it.

__init__(message, grouping)[source]
class asymmetry.core.transform.grouping.ChannelMembership(ids)[source]

Unique acquired-channel ordinals; physical detector identity is separate.

ids
classmethod from_entries(entries)[source]

Decode structured membership without coercion or accidental weights.

indices(n_histograms=None)[source]

Resolve declared ordinals against the acquired channels, without trimming.

__init__(ids)
asymmetry.core.transform.grouping.require_compatible_bin_width(width, current)[source]

One float64 ULP admits representation rounding on native acquisition edges.

asymmetry.core.transform.grouping.resolve_alignment(histograms, *group_indices, detector_t0_bins=None, common_t0_bin=None, sample_length=None, first_bin=None)[source]

Resolve selected grids, integer shifts, common observations and residuals.

Raw k maps to local r = k + c - n_i - L. Both the integer and exact origins move by L*w, so removing unobserved padding preserves timestamps.

asymmetry.core.transform.grouping.sum_aligned_counts(histograms, group_indices, alignment, *, variance=False)[source]

Sum acquired slices only, with identical mapping for counts and variance.

asymmetry.core.transform.grouping.apply_grouping_aligned(histograms, group_indices, *, common_t0_bin=None, detector_t0_bins=None, variance=False)[source]

Sum selected observations on their common integer-aligned support.

asymmetry.core.transform.grouping.common_t0_for_groups(histograms, *group_indices, detector_t0_bins=None)[source]

Maximum selected effective anchor in uncropped aligned coordinates.

asymmetry.core.transform.grouping.group_reference_t0(histograms, grouping)[source]

Reference over effective authored groups for a shared spectral grid.

asymmetry.core.transform.grouping.align_forward_backward(histograms, forward_indices, backward_indices, detector_t0_bins=None, *, common_t0_bin=None, sample_length=None, first_bin=None)[source]

Align both groups onto their common observed support without padding.

asymmetry.core.transform.grouping.group_counts_aligned(histograms, group_indices, *, common_t0_bin=None, detector_t0_bins=None, alignment=None)[source]

Sum counts and supplied variances with one observed-bin mapping.

asymmetry.core.transform.grouping.align_forward_backward_counts(histograms, forward_indices, backward_indices, detector_t0_bins=None, *, common_t0_bin=None, sample_length=None, first_bin=None)[source]

Resolve the pair once and use identical observed support for its noise.

asymmetry.core.transform.grouping.good_frames(grouping, default=1.0)[source]

Positive good_frames from a grouping, falling back to default.

good_frames is the universal dead-time normaliser (rate = counts / (dt · good_frames)); a missing, unparseable or non-positive value collapses to default so it can never zero the correction. Pass default=0.0 (and treat a falsy result as “unknown”, e.g. good_frames(g, 0.0) or None) when the caller wants to fall back to a snapshot instead.

asymmetry.core.transform.grouping.good_event_count(histograms, grouping)[source]

Raw F/B observations inside the current aligned window and selected period.

Good Events and the export header share this uncorrected observation sum. An unavailable request returns None while acquired counts remain available.

asymmetry.core.transform.grouping.excluded_detector_indices(grouping)[source]

0-based indices of detectors excluded by the grouping.

The excluded_detectors grouping key holds 1-based detector ids (WiMDA’s detector-exclusion convention). Exclusion is applied at grouping time — excluded detectors are dropped from every group sum — so the raw histograms stay intact and no reload is needed (study divergence D10; WiMDA zeroes the counts in its file-read path instead).

asymmetry.core.transform.grouping.filter_excluded_indices(indices, grouping)[source]

Drop excluded detectors (0-based) from a group index list.

asymmetry.core.transform.grouping.parse_detector_list(text)[source]

Parse a WiMDA-style detector list, e.g. "1,5,10-15".

Separators may be commas or whitespace; ranges use - and may run in either direction ("15-10" equals "10-15"). Returns sorted unique 1-based detector ids. Raises ValueError on unparseable fragments so typos surface instead of silently excluding nothing.

asymmetry.core.transform.grouping.parse_group_detectors(text, n_detectors)[source]

Parse one group’s typed detector list for a run of n_detectors.

parse_detector_list(), plus the two rules a group adds: it needs at least one detector, and every id must exist on the run. Raises ValueError with a message fit to show the user.

asymmetry.core.transform.grouping.format_detector_list(ids)[source]

Format detector ids compactly with ranges, e.g. "1,5,10-15".

asymmetry.core.transform.grouping.resolve_group_indices(groups, group_id, *, n_histograms=None)[source]

Resolve unique authored 1-based channel IDs (integer or JSON group keys).

asymmetry.core.transform.grouping.group_detectors_outside_run(groups, group_id, n_histograms)[source]

Name absent authored channels for diagnostics; no reduction trims them.

asymmetry.core.transform.grouping.effective_group_indices(grouping, group_id, *, n_histograms=None)[source]

Validate authored membership, then subtract explicit acquired-channel exclusions.

Missing preset channels remain a mismatch even when excluded. A required group with no effective members cannot be reduced. Raw counts are untouched.

asymmetry.core.transform.grouping.independent_pair_indices(grouping, *, n_histograms, resolved_indices=None)[source]

Resolve one independent F/B pair, after exclusions, without changing it.

Resolved-index entry points supply their effective selections explicitly. Identity is the declared acquired ordinal, never count or array equality. Auxiliary groups and other projections do not participate in this contract.

asymmetry.core.transform.grouping.effective_grouping(run, grouping_ref=None)[source]

Merge a run’s grouping with an optional override (override wins).

grouping_ref is the recipe-level grouping override (forward/backward group ids, alpha, good-bin window, …). Returning a fresh dict keeps the run’s stored grouping immutable.

asymmetry.core.transform.grouping.group_names(run)[source]

Return {group_id: display name} for a run’s grouping.

Reads the optional group_names map from the run’s grouping payload (keyed by int or stringified id), falling back to "Group <id>" for any group without an explicit name. Returns {} when the run has no group definitions.

class asymmetry.core.transform.grouping.GroupedForwardBackward(counts, alpha, forward_gid, backward_gid, beta=1.0)[source]

Forward/backward grouped counts plus the metadata to reduce them.

counts
alpha
forward_gid
backward_gid
beta = 1.0
property forward[source]
property backward[source]
property common_t0[source]
__init__(counts, alpha, forward_gid, backward_gid, beta=1.0)
class asymmetry.core.transform.grouping.ForwardBackwardLayout(t0_time_us, bin_width_us, window, alignment, alpha, beta, forward_gid, backward_gid)[source]

Resolved F/B timing, windows, and balances without evaluating count sums.

t0_time_us
bin_width_us
window
alignment
alpha
beta
forward_gid
backward_gid
property common_t0_bin[source]

Local integer anchor owned by the alignment.

__init__(t0_time_us, bin_width_us, window, alignment, alpha, beta, forward_gid, backward_gid)
asymmetry.core.transform.grouping.grouping_balances(grouping, *, pair=None)[source]

Resolve the actual pair’s balances, retaining the authored base fallback.

asymmetry.core.transform.grouping.selected_projection_labels(grouping, *, pair=None)[source]

Identify projection authorities by the actual pair, using a matching axis preference.

asymmetry.core.transform.grouping.shared_automatic_alpha(grouping, metadata)[source]

Use one authored automatic balance for arithmetic, preserving explicit projections.

asymmetry.core.transform.grouping.resolve_forward_backward_layout(histograms, grouping, *, resolved_indices=None)[source]

Resolve a selected pair onto common observations and one typed window.

Acquired k maps to local r = k + c - t0_i - L. A carried window policy resolves for this actual pair/period, rather than reusing another pair’s scalar bounds. Legacy scalars retain their recorded coordinate meaning.

asymmetry.core.transform.grouping.group_forward_backward(histograms, grouping, *, resolved_indices=None, metadata=None)[source]

Resolve the selected pair’s layout, then sum its observed counts.

asymmetry.core.transform.grouping.align_forward_backward(histograms, forward_indices, backward_indices, detector_t0_bins=None, *, common_t0_bin=None, sample_length=None, first_bin=None)[source]

Align both groups onto their common observed support without padding.

Background

Background subtraction for grouped raw histograms.

Four modes are supported, selected by the background_mode grouping key (with back-compatible derivation from the older keys when absent):

  • "fixed" — subtract user-supplied per-group constants.

  • "range" — the mean over an explicit observed interval, or an automatic pre-t0 default when that support exists.

  • "tail_fit" — a pulsed-source background mode: a bin-integrated muon exponential plus a flat rate fitted to the late-time spectrum; the flat rate is subtracted. Asymmetry fits by Poisson maximum likelihood on native bins and reports the rate with an uncertainty.

  • "reference_run" — WiMDA’s File BG: subtract a designated reference run’s grouped counts scaled by the good-frame ratio (sample holder / silver / laser-off references), with error propagation (divergence D7).

class asymmetry.core.transform.background.BackgroundCorrectionResult(forward, backward, outcome)[source]

Result of grouped background subtraction.

forward
backward
outcome
__init__(forward, backward, outcome)
class asymmetry.core.transform.background.TailFitResult(rate_per_us, rate_error_per_us, amplitude_per_us, window, n_bins, ok, consistent_with_zero, message='', count_covariance=None, expected_counts=None, invalid_input=False)[source]

Late-time exponential + flat fit to one grouped count spectrum.

rate_per_us is the flat background rate in counts/µs; amplitude_per_us is the muon-decay rate extrapolated to t0. consistent_with_zero flags a background below two standard errors. count_covariance is cov(raw count, fitted rate) in counts²/µs on window. expected_counts supplies the fitted Poisson variance basis.

rate_per_us
rate_error_per_us
amplitude_per_us
window
n_bins
ok
consistent_with_zero
message = ''
count_covariance = None
expected_counts = None
invalid_input = False
__init__(rate_per_us, rate_error_per_us, amplitude_per_us, window, n_bins, ok, consistent_with_zero, message='', count_covariance=None, expected_counts=None, invalid_input=False)
asymmetry.core.transform.background.resolve_facility(*, metadata=None, grouping=None)[source]

Resolve the facility label from run metadata, or "" when unknown.

The single place this resolution lives. The loaders record the facility in metadata["facility"] ("PSI" for the PSI reader, the MusrRoot Laboratory header for ROOT files); metadata["instrument"] is the fallback, since the facility can be read off an instrument name where the label is missing, and metadata["psi_format"] is decisive on its own. A grouping payload’s instrument — the canonical registry identity the loaders stamp there — is the last resort.

This label guides period adjustment of automatic pre-t0 defaults only; explicit intervals remain exactly as authored.

asymmetry.core.transform.background.supports_background_correction(*, metadata=None, source_file='')[source]

Range estimation is available when an observed interval is supplied.

Identity and filenames guide automatic defaults, not method access. Observation support is checked by grouped_background_ranges().

asymmetry.core.transform.background.available_background_modes(*, metadata=None, source_file='')[source]

Methods offered independently of facility or filename conventions.

asymmetry.core.transform.background.resolve_background_mode(grouping)[source]

Resolve the active background mode from a grouping payload.

An explicit background_mode wins; otherwise the pre-existing keys decide (fixed values → fixed; anything else → range, which is the historical behaviour of the single enable flag).

asymmetry.core.transform.background.fit_tail_background(counts, *, bin_width_us, t0_bin, first_good_bin=None, last_good_bin=None, fit_start_bin=None)[source]

Fit exponential + flat background to the late-time spectrum.

The model is the muon exponential averaged across each bin plus a flat rate:

µ_i = [p₁ · e^{−t_i/τ_µ} · sinh(w/2τ_µ)/(w/2τ_µ) + p₂] · w

with w the bin width and t_i the bin centre relative to t0. Estimation is by nonnegative Poisson maximum likelihood, profiling the total expected count and solving the remaining monotone mixture score on [0, 1]. The rate uncertainty comes from the expected information for raw counts. With GroupCounts, propagate supplied variance through the estimator’s linearised influence, including its covariance with the input bins.

The default window is the late half of inclusive selected good support, on native bins. An omitted first good defaults to t0, clipped to observed support; an explicit fit start overrides the midpoint.

asymmetry.core.transform.background.subtract_scaled_counts(counts, reference_counts, scale)[source]

Subtract a scaled reference spectrum with error propagation.

Returns counts − scale·reference with variance v + scale²·v_ref. Array inputs use the Poisson approximation; GroupCounts retain supplied independent variance. Arrays must have equal one-dimensional shape.

asymmetry.core.transform.background.apply_grouped_background_correction(forward, backward, *, grouping, t0_bin, acquisition_start_bin=0, bin_width_us, facility=None, metadata=None, first_good_bin=None, last_good_bin=None, reference_forward=None, reference_backward=None, reference_scale=None)[source]

Subtract background from grouped counts by the active mode.

Parameters:
  • forward, backward – Grouped forward/backward count arrays, or GroupCounts carrying supplied independent variance. Background estimation requires independent inputs.

  • grouping – Grouping payload. background_mode selects the mode (see resolve_background_mode() for the back-compatible default); background_fixed_values supplies fixed values and background_ranges/background_range bin ranges (inclusive, matching musrfit).

  • t0_bin – Common time-zero bin (musrfit fallback range; tail-fit time axis).

  • bin_width_us – Histogram bin width in microseconds.

  • facility – Facility label. Only automatic PSI/TRIUMF range defaults are shortened to the accelerator-period convention inspired by musrfit. The default None means derive it from metadata/grouping via resolve_facility(). Pass "" to opt out explicitly (no facility, no trimming); any non-empty string overrides.

  • metadata – Run metadata, used only to resolve facility when it is not given.

  • first_good_bin, last_good_bin – Inclusive selected good support bounding the native tail-fit window.

  • reference_forward, reference_backward, reference_scale – Grouped counts of the resolved background reference run and the good-frame ratio, required by the reference_run mode (resolution from the background_run payload happens at the caller, which has loader access).

asymmetry.core.transform.background.tail_background_window(length, t0_bin, last_good_bin, *, first_good_bin=None, fit_start_bin=None)[source]

Inclusive late half of selected support; absent first good defaults to t0.

An odd window retains its middle bin. Explicit fit starts override the half.

asymmetry.core.transform.background.grouped_background_ranges(grouping, *, t0_bin, acquisition_start_bin, length, bin_width_us, facility)[source]

Map authored acquisition bounds exactly; adjust only automatic defaults.

asymmetry.core.transform.background.fixed_background_values(grouping)[source]
asymmetry.core.transform.background.background_window(value)[source]

Validate two inclusive acquisition-bin endpoints at the input boundary.

asymmetry.core.transform.background.background_range_is_explicit(grouping)[source]

Key presence preserves authorship, including values equal to defaults.

asymmetry.core.transform.background.resolve_background_ranges(grouping, t0_bin)[source]

Resolve both inclusive background windows on the declared acquisition grid.

Deadtime

Deadtime correction utilities for raw detector histograms.

class asymmetry.core.transform.deadtime.DeadtimeDomain(observations)[source]

Original detector ordinals and disjoint inclusive raw-bin intervals.

observations
property detector_indices[source]

Required ordinals, without compacting a coefficient table.

to_dict()[source]

Record raw coordinates beside the effective correction.

__init__(observations)
exception asymmetry.core.transform.deadtime.DeadtimeCorrectionError(reason, *, detector=None, bin_index=None, occupancy=None)[source]

A correction outside its raw-count or inverse-model domain.

__init__(reason, *, detector=None, bin_index=None, occupancy=None)[source]
class asymmetry.core.transform.deadtime.DeadtimeCorrection(tau_us, good_frames)[source]

Finite signed detector coefficients with an explicit acquisition normalisation.

tau_us
good_frames
classmethod from_grouping(grouping, n_histograms)[source]
__init__(tau_us, good_frames)
asymmetry.core.transform.deadtime.deadtime_occupancy(counts, tau_us, bin_width_us, good_frames, *, detector=None, raw_bin_indices=None)[source]

Return N·τ/(Δt·F) for valid raw counts and an invertible signed correction.

asymmetry.core.transform.deadtime.apply_deadtime_correction(counts, tau_us, bin_width_us, *, num_good_frames, detector=None, raw_bin_indices=None)[source]

Invert the non-paralysable model on every raw bin, rejecting N·τ/(Δt·F) ≥ 1.

N_corr = N / (1 - N * tau / (dt * n_frames))

asymmetry.core.transform.deadtime.estimate_deadtime_from_histograms(histograms, *, t_good_offset=0, last_good_bin=None, num_good_frames, max_bins=400, detector_t0_bins=None)[source]

Estimate a uniform deadtime value from early-time detector counts.

Average the independently fitted rational-model coefficients across detectors. The returned value is a single detector deadtime in microseconds that can be broadcast across grouped histograms.

asymmetry.core.transform.deadtime.calibrate_deadtime_from_histograms(histograms, *, t_good_offset=0, last_good_bin=None, num_good_frames, max_bins=400, detector_t0_bins=None)[source]

Return per-detector coefficients in µs from the rational decay model.

class asymmetry.core.transform.deadtime.DeadtimeCalibration(tau_us, errors_us, method, source_run)[source]

Total per-detector coefficients and uncertainties in µs, ready for promotion.

tau_us
errors_us
method
source_run
classmethod from_increment(base, increment_us, *, n_histograms, detector_indices, error_us, source_run)[source]

Compose the fitted residual with the exact table applied to its data.

__init__(tau_us, errors_us, method, source_run)
asymmetry.core.transform.deadtime.fit_deadtime_calibration(histograms, *, num_good_frames, t_good_offset=0, last_good_bin=None, max_bins=400, detector_t0_bins=None, source_run=None, method='calibrate', cancel_callback=None)[source]

Fit independent signed coefficients using RUMDA (RAL-94-080), §4’s mean.

M = N/(1 + N d/(Δt F)); d and Δt are in µs, F is dimensionless. This nonlinear weighted fit uses raw-count Poisson standard deviations; the published transformed regression supplies a signed starting point.

asymmetry.core.transform.deadtime.parse_deadtime_calibration_text(text, *, n_histograms=None)[source]

Parse a WiMDA-style deadtime calibration text file.

The accepted format is the simple line-oriented form written by WiMDA:

  • optional first line with the histogram count

  • subsequent lines of <index> <tau_us>

  • optional trailing metadata lines such as Run 1234

asymmetry.core.transform.deadtime.promote_deadtime_to_grouping(grouping, calibration)[source]

Write one validated total table atomically, enabling its manual correction.

asymmetry.core.transform.deadtime.normalise_deadtime_mode(value)[source]

Name each accepted request consistently while retaining unknown input for errors.

asymmetry.core.transform.deadtime.deadtime_request_mode(grouping, *, default='from_file')[source]

Parse current authored requests without using coefficient origin as a mode.

asymmetry.core.transform.deadtime.file_deadtime_table(grouping)[source]

Read acquisition coefficients without borrowing an authored calibration.

asymmetry.core.transform.deadtime.resolve_deadtime(grouping, n_histograms, use, mode=None, *, domain=None)[source]

Resolve one request without mutating its table or coefficient provenance.

asymmetry.core.transform.deadtime.deadtime_operation_inputs(inputs, use, mode=None, *, domains=None)[source]

Withhold File correction from every participant if any lacks coefficients.

Only computation copies change; acquisition tables and authored settings remain intact. Fatal resolution outcomes keep their existing error paths.

asymmetry.core.transform.deadtime.prepare_histograms_with_deadtime(histograms, grouping, use_deadtime, *, mode=None, allow_incomplete=False)[source]

Return prepared histograms and the exact requested/effective correction.

Rebinning

Replay a selected histogram observation

The toolbar and scripts share prepare_histogram_asymmetry(). The caller supplies the selected run and resolves any live reference acquisition before calling. The operation reads the run’s grouping, preserves its base binning, and merges complete output bins before forming the percent asymmetry. It returns correction outcomes for each requested observation as well as the arrays. G+R is one pooled prepared-count observation with group background once; G−R differences separately reduced sets on common native support. Both use one explicitly selected α/β. Final ratio usability follows the requested statistic.

integrate_run honours Red, Green, pooled G+R, and G−R with retained counting responses for both existing native-bin estimators. Extracted sets and mapped originals use the same count preparation; held inspection clocks do not override acquired timing.

This synchronous operation consumes complete selected good-bin support. It does not recover the provenance or selected membership of an existing processed curve. Interactive callers retain worker, cancellation, and cache ownership; process workers that only fit the resulting arrays can use fit_record() afterwards.

Known reduction producers attach a transient HistogramObservation to a dataset. prepare_wizard_dataset composes complete-group merges with its recorded selections; time_range retains crop membership. Capture owns read-only copies of sample, held-period, and reference counts and supplied variances, deduplicating repeated uses of the same array within that capture. Settings and timing are copied too. Later writes through the caller’s arrays or their aliases do not alter the captured values or identity; the caller’s arrays remain usable. A fresh explicit capture uses the edited values and identifies that observation. Unknown custom or historical curves have no such context and use independent means. Explicit merge_curve_bins drops histogram replay context. fit_record strips the context and period arrays before candidate process fan-out. No recipe is inferred from an attached Run or a median time step. Simulation reductions record the actual uncorrected settings and selected period policies, including an implicit acquired-window policy when used.

Replay a selected run’s histogram reduction with resolved reference inputs.

asymmetry.core.transform.preparation.prepare_histogram_asymmetry(run, *, merge, facility, reference, cancel_check=None, binning=None)[source]

Reduce the explicitly selected histogram observation, in percent and µs.

run.grouping must describe the requested observation: selected pair, period, calibration, timing, good bins, corrections, and base binning. merge combines complete groups of those base output bins counts-first. It is additional to base binning, not a replacement for it. Source arrays and grouping are read without modification.

The caller resolves live reference identity, acquisition timing and scaling before calling; each period still adapts reference exposure through the established reference owner. No files, GUI state or CLI defaults are read. This replays the run’s complete selected good-bin support; it does not infer the provenance or cropped membership of an existing curve. Curve-only and rotated observations require their own curve-domain operation.

This operation is synchronous. Interactive callers retain their worker and cache ownership and may pass a cooperative cancel_check which raises when cancelled. A check is made before any numerical preparation.

class asymmetry.core.transform.preparation.HistogramObservation(source, facility, reference, binning, identity, cached_periods=(), cached_validities=(), cached_recipes=(), cached_computation_revisions=())[source]

A resolved reduction snapshot and selections of its actual output bins.

The snapshot owns read-only counts and variances, sharing each copied array within the capture, and copies settings and histogram timing. It is transient and removed by fit_record before process fan-out. Unknown historical curves have no observation and retain independent-curve semantics.

source
facility
reference
binning
identity
cached_periods = ()

Context belonging to loader-cached period curves, independent of current grouping.

cached_validities = ()
cached_recipes = ()
cached_computation_revisions = ()
select(mask)[source]

Retain a contiguous centre-selected crop before any subsequent merge.

merge(size, factor)[source]

Combine complete groups after the current recorded selections.

__init__(source, facility, reference, binning, identity, cached_periods=(), cached_validities=(), cached_recipes=(), cached_computation_revisions=())
asymmetry.core.transform.preparation.observation_histograms(run)[source]

All buffers owned by a histogram replay, including ignored acquisitions.

asymmetry.core.transform.preparation.count_metadata_identity(metadata)[source]

Condition labels do not change prepared histogram observations.

Facility/source/timing/correction facts remain in the count identity. Wizard model/coordinate identity separately includes the displayed conditions.

asymmetry.core.transform.preparation.histogram_observation(run, *, facility=None, reference=None, binning=None, cancel_check=None)[source]

Capture an explicitly resolved histogram operation at its producing boundary.

Call only where the supplied settings actually produced the observation; attaching a Run to a custom curve does not authorise this replay.

asymmetry.core.transform.preparation.wizard_observation_identity(dataset, *, policy='counts_first_observation_omit_undefined_zero_variance_v1_acquired_correct_align_v1')[source]

Identify the actual curve, replay context, and selected membership for reuse.

asymmetry.core.transform.preparation.wizard_observation_matches(dataset, signature)[source]

Whether a numerical result describes this exact prepared-observation source.

asymmetry.core.transform.preparation.prepare_wizard_dataset(dataset, factor, *, cancel_check=None)[source]

Merge the actual selected observation once, before making worker records.

asymmetry.core.transform.preparation.wizard_rebuild_dataset(dataset, factor, signature)[source]

Reconstruct recorded preparation without authorising reuse of historical scores.

Counts-first histogram binning and independent curve-bin merging.

BinningSpec fixes the raw edges for fixed, exponentially variable, or constant-error binning. Corrected counts and their shared-background noise are combined on those edges before forming a forward/backward asymmetry ratio. The raw acquisition record is unchanged. Curve-only inputs use merge_curve_bins, whose errors assume independent points.

asymmetry.core.transform.rebin.merge_curve_bins(time, values, errors, factor)[source]

Merge independent curve bins by a linear mean, without using raw counts.

Parameters:
  • time, values, errors – Equal-length arrays of the original data. values may be asymmetry on either scale — fraction or percent (see asymmetry.core.transform.units).

  • factor – Number of bins to merge into one.

Returns:

(time_rebinned, values_rebinned, errors_rebinned) – On the same scale as the input. The merge is a linear mean of values with errors added in quadrature, so this transform is unit-preserving: it never converts between fraction and percent.

asymmetry.core.transform.rebin.rebin_counts(time, counts, factor)[source]

Return count-preserving bunched traces (sum counts, mean times).

Unlike merge_curve_bins(), which is value-domain (mean of values, errors in quadrature ÷ factor), this merges neighbouring bins by summing the counts while moving the time coordinate to the centre of the wider effective bin — the right combiner for grouped count-like signals (fit-input traces, grouped Fourier inputs). The two are deliberately distinct: a value-domain mean would corrupt Poisson statistics on counts.

factor must be an integer >= 1. A factor of one returns float64 copies; an incomplete trailing group is dropped.

class asymmetry.core.transform.rebin.BinningSpec(mode='fixed', factor=1, bin0_us=0.08, bin10_us=0.25, merge=1, selections=(), time_range=None)[source]

Validated raw-bin edges and the number of recorded bins to merge.

mode = 'fixed'
factor = 1
bin0_us = 0.08
bin10_us = 0.25
merge = 1
selections = ()

Successive (first, stop, merge) selections of recorded output bins.

time_range = None

Centre-selected support after base binning, before later selections.

edges(n_bins, bin_width_us, t_start_us)[source]

Raw edges from the first native centre t_start_us.

Nonuniform targets use the actual left edge and nearest whole native width (half-up, at least one). Retain their final partial bin; fixed packing and an additional merge drop only incomplete groups.

__init__(mode='fixed', factor=1, bin0_us=0.08, bin10_us=0.25, merge=1, selections=(), time_range=None)
class asymmetry.core.transform.rebin.NativeDiagnosticBinning(source_binning)[source]

Fixed native bins covering exactly the source operation’s retained edges.

source_binning
__init__(source_binning)[source]
edges(n_bins, bin_width_us, t_start_us)[source]

Resolve all selections before expanding the retained contiguous support.

asymmetry.core.transform.rebin.binning_spec(grouping)[source]

Parse file/project/user grouping binning, rejecting present invalid values.

asymmetry.core.transform.rebin.fb_binning_edges(counts, binning, *, time_range=None)[source]

Resolve consumed local acquisition edges and the first bin’s timestamp.

class asymmetry.core.transform.rebin.BinnedRatio(time, asymmetry, error, validity, noise, edges)[source]

Fractional curve and its retained acquisition response.

time

Alias for field number 0

asymmetry

Alias for field number 1

error

Alias for field number 2

validity

Alias for field number 3

noise

Alias for field number 4

edges

Alias for field number 5

asymmetry.core.transform.rebin.binned_ratio_observation(counts, *, binning, alpha, beta=1.0, time_range=None)[source]

Reduce grouped counts to a binned asymmetry curve (all binning modes).

time_range optionally selects complete output bins by their centres; it never moves the bin edges. The validated spec selects raw edges inside the good-bin window, then merges binning.merge recorded output bins. Counts and their retained variance model are summed before the ratio is formed. Fixed binning drops a partial raw group; variable modes keep their last partial bin. An incomplete group of output bins is dropped when merge is greater than one.

Raw bin k is stamped at its centre measured from the run’s exact t0, (k + 0.5)·w − t0_time_us. The validated counts carry the exact t0 and inclusive aligned-bin window.

Returns:

BinnedRatio – validity classifies each final ratio before display fallbacks. time in µs relative to t0; asymmetry and error as a fraction — not percent, since this delegates to compute_asymmetry_with_count_errors(). Callers that need the percent scale apply the ×100 themselves; reduce_grouped_asymmetry() is the reduction that does, and its output is percent.

asymmetry.core.transform.rebin.binned_fb_observation(counts, *, binning, alpha, beta=1.0, time_range=None)[source]

Return the fractional ratio grid, errors and mathematical validity.

asymmetry.core.transform.rebin.binned_fb_asymmetry(counts, *, binning, alpha, beta=1.0, time_range=None)[source]

Return the full binned time, fractional ratio and display-error arrays.

Known dataset producers use binned_fb_observation() to retain the mathematical classification for Gaussian fits alongside these full grids.

asymmetry.core.transform.rebin.merge_curve_bins(time, values, errors, factor)[source]

Merge independent curve bins by a linear mean, without using raw counts.

Parameters:
  • time, values, errors – Equal-length arrays of the original data. values may be asymmetry on either scale — fraction or percent (see asymmetry.core.transform.units).

  • factor – Number of bins to merge into one.

Returns:

(time_rebinned, values_rebinned, errors_rebinned) – On the same scale as the input. The merge is a linear mean of values with errors added in quadrature, so this transform is unit-preserving: it never converts between fraction and percent.

Integrated observation status

reduce_period_integral() carries a ScalarObservation alongside value, mathematical error, and correction outcomes. Its reason uses RatioReason; report is an ObservationReport of the requested scalar or native mean support. reduce_integral_run retains the same status. Curve-only means have corrections=None (an empty correction map for the period coordinator).

The tuple convenience APIs integrate_asymmetry, integrate_curve, and integrate_run return mathematical errors: undefined count ratios give (nan, nan), and defined zero-variance ratios retain their value with zero error. A mean with no usable observations raises ValueError. Use the typed coordinator for omission reports; never assign Gaussian weight to a defined value solely because it can be displayed.

FieldScan.observations retains per-point status. correlated_pairs records pairs of point indices with known unsupported nonzero cross-point counting covariance, without serialising large sparse response operators. FieldScan.select preserves these facts through crops/reordering. The scan fit adapters apply one usable-observation policy before seeding and weighting; legacy inputs retain their recorded independent-source assumption. See Integral scan mode (avoided-level-crossing field scans) for the mathematics and Asymmetry in the μSR software landscape for reference-program qualifications.

Workflow integral scans ordered by run number retain source-run coordinates in their effective recipe and JSON payload. Point recipes retain their selected acquired periods independently of those displayed coordinates.

Condition-scan derivatives

asymmetry.core.transform.integral.differentiate_scan(scan, *, max_gap=None)[source]

Forward-difference derivative dA/dx of a scan (WiMDA dA/dB).

Each output point sits at the midpoint of an adjacent pair, with dA/dx = (A₂ - A₁) / (x₂ - x₁). Independent input errors give the marginal hypot(e₁, e₂) / |Δx|. For a known dependent input pair its covariance is unsupported here: retain the value and report error NaN, not zero variance. Undefined source ratios remain undefined. Derived points have no new ratio classification; the original scan retains its scalar observation reports. Pairs with non-positive spacing, or spacing greater than explicit max_gap, are skipped without interpolation or an automatic gap threshold. Adjacent differences share observations. These scans support display/export; fit the original scan rather than assigning independent derivative weights.

Returns:

FieldScan – With derivative=True. Dividing by Δx leaves the asymmetry scale untouched, so values stay on the input fraction or percent scale per x-unit. units records that numerator scale and is carried unchanged.

Derivatives retain FieldScan.units as their asymmetry scale per selected axis unit. They carry no new scalar-ratio classification. Independent source pairs supply marginal errors; known dependent adjacent pairs have NaN error, serialized as null. The original scan retains source classifications and positional correlated_pairs. Derivative identity survives select and workflow payload restoration. The shared fit-input boundary rejects derivative scans: fit original observations, since adjacent differences share inputs.

Corrections

exception asymmetry.core.transform.corrections.CorrectionUnavailableError[source]

A requested correction has no usable result for final analysis.

Integral scans

class asymmetry.core.transform.integral.IntegralReduction(value, error, corrections, observation, effective_recipe=None)[source]

Scalar value/error and known count corrections, absent for a curve-only mean.

class asymmetry.core.transform.integral.FieldScan(x, value, error, run_numbers, order_key, method, derivative=False, x_label='', y_label='Integral asymmetry', excluded=<factory>, units=AsymmetryUnit.FRACTION, correction_outcomes=<factory>, observations=(), correlated_pairs=(), source_assumption='Unknown acquisition identity is assumed distinct.', effective_recipe=None, computation_revision=None)[source]

An ordered series of integral-asymmetry values vs a run variable.

The arrays are parallel and sorted by x ascending. excluded lists (run_number, reason) for runs that could not contribute (for example a missing field log — Mantid skips such runs rather than failing the scan).

Scale note: value/error are the integral asymmetry as a fraction (from compute_asymmetry() on summed counts) — the scale the field-scan / ALC parameter models expect (e.g. GaussianLCR seeds f near 0.1), and the one the units field records. This differs from a loaded MuonDataset, whose asymmetry is on the percent scale; multiply by 100 (or call asymmetry.core.transform.units.to_percent()) if you need to compare the two directly.

class asymmetry.core.transform.integral.FieldScanPoint(run_number, x, value, error, label='', corrections=<factory>, observation=None, noise=None, effective_recipe=None)[source]

One run’s contribution to a field scan.

value/error are the integral asymmetry as a fraction carried straight from the owning FieldScan — see its units field.

asymmetry.core.transform.integral.build_field_scan(runs, *, t_min=None, t_max=None, method='integral', alpha=None, order_key='field', grouping_ref=None, reference=None, progress_callback=None, cancel_check=None, filter=None)[source]

Assemble a field scan from a series of loaded runs.

Parameters:
  • runs – Iterable of loaded objects — each a MuonDataset or Run. For multi-period runs, select the period upstream and pass the per-period datasets in.

  • t_min, t_max, method, alpha, grouping_ref, reference – Passed through to integrate_run() (applied to every run in the scan — the grouping/alpha is normally common across a scan).

  • order_key – "field", "temperature", or "run" — the x-axis variable the points are ordered by (the same ORDER_KEYS FitSeries uses).

  • filter – Optional predicate run -> bool used to keep a subset of the runs in a single scan, so distinct measurement periods or run types taken at the same field are not mixed into one curve. It is called with each resolved Run (giving its run_number and metadata) before reduction; runs for which it returns a falsy value are dropped and listed in excluded with the reason "excluded by filter". Use it to keep one period (run.metadata.get("period_label") == "red"), one run type, or to drop interleaved calibration runs (run.run_number not in cal). A predicate that raises excludes that one run (reason "filter raised: …") rather than aborting the scan. Default None keeps every run — identical to the historical behaviour. (To split a multi-period file into its periods first, use asymmetry.core.io.periods.select_period() upstream — period extraction lives in io, which depends on this transform, not the reverse.)

Returns:

FieldScan – Whose value/error are as a fraction (with units set to ASYMMETRY_FRACTION) — not percent, since every point comes from integrate_run(). Sorted parallel arrays plus the list of excluded runs.

asymmetry.core.transform.integral.integrate_asymmetry(forward, backward, *, alpha=1.0, beta=1.0, time=None, t_min=None, t_max=None, method='integral')[source]

Reduce grouped counts to one fractional asymmetry and marginal error.

integral sums native counts before forming the ratio. differential averages usable native ratio observations and reports omissions in typed results. Both propagate the independent count variances and shared components with linear_combination_variance(). Its weights are 1 for an integral and the asymmetry derivatives divided by the number of averaged bins for a differential mean.

time is an optional aligned axis in μs, required with inclusive bounds t_min or t_max. Without bounds the full record is selected. α and β must be positive. An undefined scalar returns (nan, nan); a defined zero-variance ratio retains its value with error zero. Neither has Gaussian fit weight. A mean with no usable observations raises ValueError.

asymmetry.core.transform.integral.integrate_curve(time, asymmetry, error, *, t_min=None, t_max=None)[source]

Mean of an already-formed asymmetry curve over [t_min, t_max].

Explicit zero errors are omitted; no surviving observations raises ValueError. Useful when only the reduced curve is available (for example a combined green∓red spectrum) rather than the forward/backward counts. The error is the error on the mean, sqrt(Σ eᵢ²) / N.

Parameters:
  • time – Time axis in µs.

  • asymmetry, error – The reduced curve, on either asymmetry scale — fraction or percent. This is the one function in the module that does not fix the scale.

  • t_min, t_max – Inclusive averaging window in µs.

Returns:

tuple of float – On the same scale as the input asymmetry — a mean is unit-preserving. Pass ds.asymmetry and the result is percent; pass ds.asymmetry_fraction and it is a fraction, matching integrate_asymmetry() and integrate_run().

asymmetry.core.transform.integral.integrate_run(data, *, t_min=None, t_max=None, method='integral', alpha=None, grouping_ref=None, reference=None)[source]

Return fractional integral asymmetry and error, warning for accepted skips.

asymmetry.core.transform.integral.reduce_period_integral(data, *, t_min=None, t_max=None, method='integral', alpha=None, grouping_ref=None, reference=None, cancel_check=None, counting_capture=None)[source]

Coordinate background before integrating held-period sums or differences.

Vector projections

asymmetry.core.transform.projections.reduce_selected_projections(run, *, facility=None, reference=None, period_index=None, binning=None, cancel_check=None)[source]

Reduce the selected period statistic as one counting-observation cohort.

References must already be resolved by the file/UI boundary. Count variance is conditional on calibration, correction values and frame settings.

Count reduction

asymmetry.core.transform.reduce.corrected_grouped_counts(*, histograms, grouping, forward_idx, backward_idx, use_deadtime, deadtime_mode, use_background, facility=None, metadata=None, reference_resolver=None, cancel_check=None, allow_incomplete=False, context='', output_window=None, output_binning=None, output_time_range=None)[source]

Return corrected counts with the canonical requested/effective outcomes.

asymmetry.core.transform.reduce.reduce_grouped_asymmetry(*, histograms, grouping, binning, forward_idx, backward_idx, alpha, use_deadtime, deadtime_mode, use_background, facility=None, metadata=None, reference_resolver=None, cancel_check=None, allow_incomplete=False, context='', beta=1.0, output_time_range=None)[source]

Reduce grouped histograms to a forward/backward asymmetry curve.

The correction stages (deadtime → grouping → background) are shared with the alpha estimate via corrected_grouped_counts(); this function adds only the final binned_fb_asymmetry() step. The returned arrays are final — the good window is applied, the binning (fixed bunching included) is applied, and no further slicing or bunching is left for the caller.

facility/metadata behave exactly as in corrected_grouped_counts(): leave facility at None and pass metadata=run.metadata to have the accelerator-period trimming of a pre-t0 background window engage by itself.

Returns:

GroupedAsymmetryReduction – Whose asymmetry and error are in percent (fraction × 100) — units is ASYMMETRY_PERCENT. This is the one step on the reduction path that applies the ×100, so its output drops straight into a MuonDataset and the percent-scale fit models, unlike the fraction returned by binned_fb_asymmetry() and compute_asymmetry() underneath it. See “Asymmetry units across the API” in the documentation.

asymmetry.core.transform.reduce.reduce_period_asymmetry(histograms, grouping, period_mode, *, binning, forward_idx, backward_idx, alpha, use_deadtime, deadtime_mode, use_background, beta=1.0, output_time_range=None, facility=None, metadata=None, reference_resolver=None, cancel_check=None, allow_incomplete=False, context='', timing_search=None)[source]

Form pooled G+R once or difference independently reduced sets on common support.

Rotating-frame provenance

class asymmetry.core.transform.rotating_frame.RotatingFrame(frequency_mhz, b1_axis, rf_phase_deg, sense, gain, baselines, provenance=<factory>)[source]

One run’s rotating frame: setup fields, gain, per-period baselines, provenance.

Build a new one with typed_frequency(); change scalar fields with with_values() and a period’s baselines with with_baseline(), which record where the new values came from.

classmethod RotatingFrame.typed_frequency(frequency_mhz, periods)[source]

The frame a user starts by typing ν_RF; every other field a default.

RotatingFrame.with_values(provenance, **values)[source]

These scalar fields set to values, recorded as coming from provenance.

RotatingFrame.with_baseline(period, provenance, x, y)[source]

Period period’s baselines set to (x, y), recorded as from provenance.

Rotating reference frames

class asymmetry.core.transform.rrf.RRFCurve(time, real, real_error, imag, imag_error, real_imag_covariance, valid, frequency_mhz, phase_deg, method, bandwidth_mhz, filter_taps, effective_independent_fraction)[source]

A demodulated rotating-frame curve with per-point errors.

real/imag are the in-phase and quadrature components with per-point standard deviations conditional on independent scalar input errors, propagated through the FIR demodulation and filter (the WiMDA comparison mode retains its linear-error convention). Neighbouring bins are correlated over roughly filter_taps bins; effective_independent_fraction (Σh²ₖ of the DC-normalised kernel) is the approximate fraction of output points that carry independent information. real_imag_covariance retains their signed same-bin covariance from shared input errors, in squared input-scale units. Unknown input temporal correlations cannot be recovered from marginal errors alone.

Scale: every value here — real, imag, their errors, magnitude and magnitude_error — is on the same asymmetry scale as the input curve. Demodulation is linear (a ×2 carrier product and a DC-normalised filter), so it neither introduces nor removes the ×100: demodulate ds.asymmetry and the components are percent; demodulate ds.asymmetry_fraction and they are a fraction. See asymmetry.core.transform.units.

asymmetry.core.transform.rrf.rrf_demodulate(time, asymmetry, error, *, frequency_mhz, phase_deg=0.0, bandwidth_mhz=None, method='fir', wimda_box_width_us=None)[source]

Demodulate an asymmetry curve into the rotating frame at ν₀.

Parameters:
  • time, asymmetry, error (array-like) – The curve in µs with per-bin standard deviations. asymmetry/error may be on either asymmetry scale — fraction or percent — and the output carries that same scale through unchanged. Non-finite bins are excluded from the filter without poisoning their neighbourhood. Bins within one filter support of a non-finite hole keep a bounded bias (up to ~missing-bins/taps × twice the local amplitude): the kernel renormalisation restores the baseband mean but the hole impairs the image cancellation locally.

  • frequency_mhz (float) – Frame frequency ν₀ (positive). Gauss-entered values are converted by the caller through asymmetry.core.fourier.units — this module speaks MHz only.

  • phase_deg (float) – Frame phase φ in degrees; the carrier is e^{−i(2πν₀t + φ)}.

  • bandwidth_mhz (float, optional) – Single-sided FIR cutoff; defaults to default_bandwidth_mhz(). Ignored by the WiMDA mode.

  • method (str) – "fir" (complex demodulation, the display method) or "wimda" (2·cos + box average, comparison only; see the module docstring).

  • wimda_box_width_us (float, optional) – WiMDA-mode box width in µs; defaults to one image period 1/(2ν₀), WiMDA’s own default when ν₀ sits at the applied field.

Returns:

RRFCurve – Complex curve on the input’s asymmetry scale, with conditional per-point FIR error propagation for independent scalar observations and a validity mask covering filter edges and non-finite holes. See the class notes on inter-bin correlation and scale.

asymmetry.core.transform.rrf.rrf_demodulate_values(time, values, *, frequency_mhz, phase_deg=0.0, bandwidth_mhz=None, method='fir', wimda_box_width_us=None)[source]

Demodulate an error-free curve (e.g. a stored fit-curve overlay).

The model curve drawn over RRF-displayed data must pass through the same pipeline as the data so their values and resolved bandwidth stay in step.

values may be on either asymmetry scale and the returned RRFCurve keeps it — so pass the curve on the same scale as the data it overlays (percent for a plotted MuonDataset).

asymmetry.core.transform.rrf.default_bandwidth_mhz(frequency_mhz, sample_rate_mhz=None)[source]

Default single-sided FIR cutoff between the envelope and the image.

The image sits at ν + ν₀ ≈ 2ν₀ for ν₀ tuned near the line, so ν₀/2 leaves generous room for the envelope and any deliberate detuning beat. On a sampled signal the image folds: for 2ν₀ beyond Nyquist it aliases to |2ν₀ − k·fs| and can land back inside the baseband — common for high-TF data binned close to Nyquist. Given the sample rate, the default therefore stays below 70% of the folded image frequency as well. When the image folds onto DC (2ν₀ ≈ k·fs) no filter can separate it from the envelope; the default falls back to ν₀/2 and the curve will show the contamination — rebin differently or move ν₀.

RRFCurve.magnitude[source]

The phase-free envelope \(|z|\); noise-biased where \(|z| \lesssim \sigma\).

RRFCurve.magnitude_error[source]

First-order error on \(|z|\); unreliable where \(|z| \lesssim \sigma\) (magnitude bias).

Units

asymmetry.core.transform.units.ASYMMETRY_FRACTION

The dimensionless fraction. Module-level alias for asymmetry.core.transform.units.AsymmetryUnit.FRACTION, so a keyword argument or a docstring can name the scale without importing the enum.

asymmetry.core.transform.units.ASYMMETRY_PERCENT

Percent, fraction × 100. Module-level alias for asymmetry.core.transform.units.AsymmetryUnit.PERCENT.

class asymmetry.core.transform.units.AsymmetryUnit(*values)[source]

The scale an asymmetry value is expressed on.

A two-member enum, deliberately: unlike KnightShiftUnit there is no AUTO member and no ppm, because an asymmetry’s scale is a property of the producing function, not a display preference to be guessed — the point is that every producer can state which of the two it means.

asymmetry.core.transform.units.convert_asymmetry(values, frm, to)[source]

Convert asymmetry (or asymmetry-error) values between the two scales.

Parameters:
  • values (array_like) – Asymmetry or asymmetry-error values on the frm scale. Errors convert by the same factor as the values they belong to.

  • frm, to (AsymmetryUnit) – Source and target scale. Both must be stated — there is no inference, because guessing the input scale from its magnitude is exactly the failure mode this module exists to remove.

Returns:

NDArray – A new float64 array on the to scale. A same-unit conversion still returns a copy, so the result is never an alias of the input.

asymmetry.core.transform.units.to_fraction(values, *, frm=AsymmetryUnit.PERCENT)[source]

Return values on the fractional scale (percent input by default).

The counterpart of to_percent(), and the free-function equivalent of asymmetry.core.data.dataset.MuonDataset.asymmetry_fraction.

asymmetry.core.transform.units.to_percent(values, *, frm=AsymmetryUnit.FRACTION)[source]

Return values on the percent scale (fraction input by default).

The one-liner for feeding a fraction-scale primitive’s output to a percent-scale consumer:

asym, err = compute_asymmetry(forward, backward, alpha)
engine.fit_arrays(time, to_percent(asym), to_percent(err), model, params)
AsymmetryUnit.FRACTION
AsymmetryUnit.PERCENT