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'
- __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.
One shared parameter’s variance, sensitivity and raw-count covariance.
For corrected counts c = r + g(θ̂ − θ),
sensitivityis g andcount_covarianceis cov(r, θ̂). Components in a group must describe mutually independent parameters; all arrays use its acquisition bins.
- class asymmetry.core.transform.fb_counts.GroupCounts(counts, variance=None, shared=(), noise=None)[source]
Grouped counts with independent variance and shared parameter components.
variance=Nonedenotes the Poisson count model. Arrays are copied and read-only, so changing an input buffer cannot invalidate the checked shape.- counts
- variance = None
- 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.
- window(grouping, *, offset_bins=0)[source]
Translate explicit bounds to this grid, then intersect leading support.
offset_binsmaps 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.
alignmentowns the common t0 bin;t0_time_uspreserves 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
- __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
MuonDatasetsurface:ds.asymmetry/ds.errorare 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, useds.asymmetry_fraction/ds.asymmetry_percentrather 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: aMuonDataset, a fit model’sA0,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
alphamultiplying the backward group (andbetathe 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
alphafrom grouped counts.This follows the same approach used by Mantid’s
AlphaCalcalgorithm:\[\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_erroris absent for the quick diamagnetic and General estimates.ratioreports 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_valueis the minimised objective for the optimising methods andNonefor theratiomethod.- 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.
diamagneticminimises weighted asymmetry power on internally packed, positive bins.generalequates early/late lifetime-corrected densities at beta = 1 and requirestime_usin microseconds relative to t0. Both returnalpha_error=None.ratiouses 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_valueis 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_checkis 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
MuonDatasetsurface:ds.asymmetry/ds.errorare 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, useds.asymmetry_fraction/ds.asymmetry_percentrather 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: aMuonDataset, a fit model’sA0,fit_arrays().
- asymmetry.core.transform.asymmetry.estimate_alpha(forward, backward, *, first_good_bin=None, last_good_bin=None)[source]
Estimate the detector-balance parameter
alphafrom grouped counts.This follows the same approach used by Mantid’s
AlphaCalcalgorithm:\[\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.
- 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_framesfrom a grouping, falling back to default.good_framesis 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. Passdefault=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_detectorsgrouping 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. RaisesValueErroron 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. RaisesValueErrorwith 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_refis 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_namesmap from the run’s grouping payload (keyed byintor 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
- __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
- __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.
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_usis the flat background rate in counts/µs;amplitude_per_usis the muon-decay rate extrapolated to t0.consistent_with_zeroflags a background below two standard errors.count_covarianceis cov(raw count, fitted rate) in counts²/µs onwindow.expected_countssupplies 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 MusrRootLaboratoryheader for ROOT files);metadata["instrument"]is the fallback, since the facility can be read off an instrument name where the label is missing, andmetadata["psi_format"]is decisive on its own. A grouping payload’sinstrument— 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_modewins; 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·referencewith variancev + 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_modeselects the mode (seeresolve_background_mode()for the back-compatible default);background_fixed_valuessupplies fixed values andbackground_ranges/background_rangebin 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
rangedefaults are shortened to the accelerator-period convention inspired by musrfit. The defaultNonemeans derive it frommetadata/groupingviaresolve_facility(). Pass""to opt out explicitly (no facility, no trimming); any non-empty string overrides.metadata – Run metadata, used only to resolve
facilitywhen 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_runmode (resolution from thebackground_runpayload 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.background_window(value)[source]
Validate two inclusive acquisition-bin endpoints at the input boundary.
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
- __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.
- class asymmetry.core.transform.deadtime.DeadtimeCorrection(tau_us, good_frames)[source]
Finite signed detector coefficients with an explicit acquisition normalisation.
- tau_us
- good_frames
- __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.
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.groupingmust describe the requested observation: selected pair, period, calibration, timing, good bins, corrections, and base binning.mergecombines 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_checkwhich 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_recordbefore 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 = ()
- __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.
valuesmay be asymmetry on either scale — fraction or percent (seeasymmetry.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
valueswith 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.factormust 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
- 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_rangeoptionally 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 mergesbinning.mergerecorded 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
kis 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 –
validityclassifies each final ratio before display fallbacks.timein µs relative to t0;asymmetryanderroras a fraction — not percent, since this delegates tocompute_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.
valuesmay be asymmetry on either scale — fraction or percent (seeasymmetry.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
valueswith 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/dxof a scan (WiMDAdA/dB).Each output point sits at the midpoint of an adjacent pair, with
dA/dx = (A₂ - A₁) / (x₂ - x₁). Independent input errors give the marginalhypot(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 explicitmax_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.unitsrecords 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
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
xascending.excludedlists(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/errorare the integral asymmetry as a fraction (fromcompute_asymmetry()on summed counts) — the scale the field-scan / ALC parameter models expect (e.g.GaussianLCRseedsfnear 0.1), and the one theunitsfield records. This differs from a loadedMuonDataset, whoseasymmetryis on the percent scale; multiply by 100 (or callasymmetry.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/errorare the integral asymmetry as a fraction carried straight from the owningFieldScan— see itsunitsfield.
- 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
MuonDatasetorRun. 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 sameORDER_KEYSFitSeriesuses).filter – Optional predicate
run -> boolused 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 resolvedRun(giving itsrun_numberandmetadata) before reduction; runs for which it returns a falsy value are dropped and listed inexcludedwith 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. DefaultNonekeeps every run — identical to the historical behaviour. (To split a multi-period file into its periods first, useasymmetry.core.io.periods.select_period()upstream — period extraction lives inio, which depends on this transform, not the reverse.)
- Returns:
FieldScan – Whose
value/errorare as a fraction (withunitsset toASYMMETRY_FRACTION) — not percent, since every point comes fromintegrate_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.
integralsums native counts before forming the ratio.differentialaverages usable native ratio observations and reports omissions in typed results. Both propagate the independent count variances and shared components withlinear_combination_variance(). Its weights are 1 for an integral and the asymmetry derivatives divided by the number of averaged bins for a differential mean.timeis an optional aligned axis in μs, required with inclusive boundst_minort_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 raisesValueError.
- 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. Passds.asymmetryand the result is percent; passds.asymmetry_fractionand it is a fraction, matchingintegrate_asymmetry()andintegrate_run().
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 finalbinned_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/metadatabehave exactly as incorrected_grouped_counts(): leavefacilityatNoneand passmetadata=run.metadatato have the accelerator-period trimming of a pre-t0 background window engage by itself.- Returns:
GroupedAsymmetryReduction – Whose
asymmetryanderrorare in percent (fraction × 100) —unitsisASYMMETRY_PERCENT. This is the one step on the reduction path that applies the ×100, so its output drops straight into aMuonDatasetand the percent-scale fit models, unlike the fraction returned bybinned_fb_asymmetry()andcompute_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 withwith_values()and a period’s baselines withwith_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.
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/imagare 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 roughlyfilter_tapsbins;effective_independent_fraction(Σh²ₖ of the DC-normalised kernel) is the approximate fraction of output points that carry independent information.real_imag_covarianceretains 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,magnitudeandmagnitude_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: demodulateds.asymmetryand the components are percent; demodulateds.asymmetry_fractionand they are a fraction. Seeasymmetry.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/errormay 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.
valuesmay be on either asymmetry scale and the returnedRRFCurvekeeps it — so pass the curve on the same scale as the data it overlays (percent for a plottedMuonDataset).
- 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 ν₀.
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
KnightShiftUnitthere is noAUTOmember 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
frmscale. 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
float64array on thetoscale. 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
valueson the fractional scale (percent input by default).The counterpart of
to_percent(), and the free-function equivalent ofasymmetry.core.data.dataset.MuonDataset.asymmetry_fraction.
- asymmetry.core.transform.units.to_percent(values, *, frm=AsymmetryUnit.FRACTION)[source]
Return
valueson 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