Fourier analysis

The Fourier subsystem exposes asymmetry.core.fourier.fft for direct FFT-based spectra of any time-domain dataset or bare (t, A, σ) triple, with the WiMDA-compatible filter / apodisation model documented in Fourier analysis, and asymmetry.core.fourier.window for the windowing primitives the FFT path uses. asymmetry.core.fourier.apodisation holds the matched-filter suggester and the early-signal guard that warns when an apodisation has deleted the beginning of the record. asymmetry.core.fourier.maxent re-exports the grouped-count maximum-entropy engine that lives in asymmetry.core.maxent. The GUI Fourier panel does not call this API directly — it computes grouped-count FFTs from the current grouping payload — but the two share the same windowing primitives.

FFT

FFT helpers for μSR asymmetry and grouped detector signals.

asymmetry.core.fourier.fft.canonical_fourier_display_mode(display)[source]

Return the canonical Fourier display-mode key for display.

asymmetry.core.fourier.fft.fourier_mode_uses_phase_correction(display)[source]

Return whether display consumes the phase-corrected spectrum.

asymmetry.core.fourier.fft.fourier_mode_uses_phase_fit(display)[source]

Return whether display estimates the physical phase automatically.

asymmetry.core.fourier.fft.finite_bin_mean_weights(signal, error=None)[source]

Return normalized finite-bin weights, using 1/error where available.

class asymmetry.core.fourier.fft.PreparedFFTSignal(unwindowed_signal, window_weights, sample_errors, mean_weights, time_start_us, dt, fractional_baseline=None, fractional_applied=False)[source]

One prepared input and the exact linear window/mean/noise operators.

unwindowed_signal
window_weights
sample_errors
mean_weights
time_start_us
dt
fractional_baseline = None
fractional_applied = False
property signal[source]

Return the measured signal with its actual window applied.

property window_sum[source]

Return the unpadded coherent gain used for percent calibration.

property percent_scale[source]

Return 100·2/Σw, targeting an isolated fractional cosine line in percent.

__init__(unwindowed_signal, window_weights, sample_errors, mean_weights, time_start_us, dt, fractional_baseline=None, fractional_applied=False)
asymmetry.core.fourier.fft.prepare_fft_time_signal(dataset, *, window='none', t_min=None, t_max=None, subtract_average_signal=None, filter_start_us=0.0, filter_time_constant_us=1.5, fractional=False, detrend=None)[source]

Return the preprocessed real time-domain signal and its calibration.

Applies (in order) the time crop, optional fractional footing, the baseline removal (subtract_average_signal or detrend), and the apodisation filter/window — the exact preprocessing fft_complex_asymmetry() feeds to the FFT, so an all-poles (Burg) estimate can share the same input.

window accepts the WiMDA filters ("none", "gaussian", "lorentzian" — weight-1 at t = 0) and the symmetric tapers ("hann", "cosine" — zero at the record’s ends). A taper deletes early-time signal and is for late-time / narrow-line work only; when it detects that a taper has erased a front-loaded signal this function raises ApodisationEarlySignalWarning, which names the numbers and the two alternatives (no window with a crop, or the exponential filter at filter_time_constant_us ≈ 1/λ). The warning is advisory: nothing about the returned value changes.

To preprocess a bare (t, A, σ) triple with no dataset in hand, use prepare_fft_arrays(), which shares this function’s entire implementation.

With fractional, signal and errors are divided by a finite-window 1/σ-weighted level (an arithmetic mean without usable error weights). A finite positive level defines fractional footing; otherwise raw footing is retained. An oscillation’s nonzero window mean can bias this estimate; neither lifetime correction nor this level calibrates absolute polarisation.

Baseline removal

subtract_average_signal removes a constant — WiMDA’s error-weighted average. A signal that relaxes across the record does not ride on a constant, and the residual trend dumps power into the low-frequency bins, where it can swamp a genuine line. detrend removes a trend instead:

  • None (the default) — no detrend; subtract_average_signal behaves exactly as it always has.

  • an int n (0 ≤ n ≤ 3) — an error-weighted least-squares polynomial of order n is fitted to the cropped, post-fractional signal and subtracted. Keep the order low: a high-order polynomial fits the oscillation itself, so orders above 3 are rejected rather than silently deleting the line.

  • a callable f(time) -> baseline — subtracted as given, for removing a slow model fitted elsewhere. It receives the cropped time axis and must return an array of the same shape.

detrend is applied instead of the average subtraction, not after it (a fitted polynomial already subsumes the mean). subtract_average_signal therefore defaults to None, meaning “the historical True, unless detrend takes over”; passing detrend= together with an explicit subtract_average_signal=True raises ValueError rather than guessing an order for the two.

raises ValueError:

If the cropped time grid has fewer than two samples, is not finite and increasing, or deviates from uniform sampling by more than 1e-6 intervals.

asymmetry.core.fourier.fft.prepare_fft_arrays(time, asymmetry, error=None, *, window='none', t_min=None, t_max=None, subtract_average_signal=None, filter_start_us=0.0, filter_time_constant_us=1.5, fractional=False, detrend=None)[source]

Preprocess a bare (t, A, σ) triple — no MuonDataset required.

The array-taking front door onto the same preprocessing as prepare_fft_time_signal(): both crop through one seam and then run one shared internal core, so prepare_fft_arrays(ds.time, ds.asymmetry, ds.error, …) returns exactly what prepare_fft_time_signal(ds, …) returns.

Parameters:
  • time (array_like) – Time axis in microseconds, one dimension.

  • asymmetry (array_like) – Signal values to transform. The FFT is scale-linear, so whatever scale goes in comes out: a percent-scale curve (the MuonDataset convention) yields a percent-scaled spectrum, a fraction-scale curve a fraction-scaled one. Nothing here rescales the input — see “Asymmetry units across the API”.

  • error (array_like, optional) – 1σ uncertainty on asymmetry, on the same scale. Used only for the error-weighted average subtraction and the fractional baseline; omit it (None) and those fall back to their unweighted forms.

  • window, t_min, t_max, subtract_average_signal, filter_start_us, filter_time_constant_us, fractional, detrend – Exactly as documented on prepare_fft_time_signal() (including its “Baseline removal” section for detrend). t_min/t_max crop the arrays with the same inclusive bounds time_range() applies.

Raises:

ValueError – When the arrays are not one-dimensional, have unequal lengths, are empty, or contain non-finite values. Both array and dataset entry points require at least two finite, increasing, uniformly sampled times after cropping, within 1e-6 sampling intervals of the uniform grid.

asymmetry.core.fourier.fft.fft_complex_asymmetry(dataset, window='none', padding_factor=1, t_min=None, t_max=None, phase_degrees=0.0, t0_offset_us=0.0, subtract_average_signal=None, filter_start_us=0.0, filter_time_constant_us=1.5, fractional=False, amplitude_calibration=False, diagnostics=None, detrend=None)[source]

Compute the phase-rotated complex FFT of the asymmetry signal.

Parameters:
  • dataset – The time-domain data.

  • window – Apodization window name ("none", "gaussian", "hann", "cosine", "lorentzian"). "gaussian"/"lorentzian" are the WiMDA filters — weight-1 at t = 0, decaying with filter_time_constant_us — while "hann"/"cosine" are symmetric tapers, zero at the record’s ends. A taper is for late-time / narrow-line work and DELETES early-time signal: a heavily damped oscillation (lifetime ≪ record length) can vanish entirely under Hann while being many-sigma with "none" and a crop, or with the exponential filter at filter_time_constant_us ≈ 1/λ (the matched apodisation for a Lorentzian line). This path warns when it detects that case — see ApodisationEarlySignalWarning.

  • padding_factor – Zero-pad the signal to padding_factor × N.

  • t_min, t_max – Restrict the time range before transforming.

  • phase_degrees – Manual phase correction in degrees. A positive value applies the usual phase-correction rotation exp(-i * phi) to the complex spectrum.

  • t0_offset_us – Additional WiMDA-style time-zero offset in microseconds. This applies a frequency-dependent phase term exp(-i * 2π f t0) after the FFT.

  • subtract_average_signal – When true, subtract the WiMDA-style pre-FFT average signal before any window is applied. Defaults to None, which means True unless detrend takes the baseline removal over.

  • filter_start_us – WiMDA-style filter start time in microseconds for "gaussian" and "lorentzian" FFT filtering.

  • filter_time_constant_us – WiMDA-style filter time constant in microseconds for "gaussian" and "lorentzian" FFT filtering.

  • fractional – When true, put the signal on a fractional-asymmetry footing by dividing it (and its error) by the error-weighted baseline before averaging and the FFT (see prepare_fft_time_signal()).

  • amplitude_calibration – When true, multiply the complex spectrum by the coherent-gain / percent factor 100 · 2 / Σw (Σw the apodisation coherent gain over the unpadded samples). This targets 100·A for a resolved isolated undamped fractional cosine away from DC/Nyquist, with negligible opposite-frequency leakage and a known level. Off-grid peaks, damping, finite-window level estimates, and padding can change sampled maxima.

  • diagnostics – Optional mutable dict; when supplied it is populated with the window_sum, fractional_baseline, fractional_applied and amplitude_calibrated used, so callers can stamp provenance/guard notes without a second pass.

  • detrend – Baseline removal for a signal that relaxes across the record: None, an integer polynomial order (0–3, fitted error-weighted), or a callable f(time) -> baseline. Applied instead of subtract_average_signal — see “Baseline removal” in prepare_fft_time_signal().

Returns:

frequencies, spectrum – Frequency axis (MHz) and the complex, optionally phase-rotated spectrum.

Raises:

ValueError – If the cropped time grid has fewer than two samples, is not finite and increasing, or deviates from uniform sampling by more than 1e-6 intervals.

asymmetry.core.fourier.fft.fft_complex_prepared(prepared, *, padding_factor=1, phase_degrees=0.0, t0_offset_us=0.0, amplitude_calibration=False, diagnostics=None)[source]

Transform an already-preprocessed signal into a calibrated complex spectrum.

The one implementation behind fft_complex_asymmetry() and fft_complex_arrays(): everything downstream of PreparedFFTSignal — padding, the coherent-gain calibration, the phase rotation, and the diagnostics stamp — lives here once.

asymmetry.core.fourier.fft.fft_complex_arrays(time, asymmetry, error=None, *, window='none', padding_factor=1, t_min=None, t_max=None, phase_degrees=0.0, t0_offset_us=0.0, subtract_average_signal=None, filter_start_us=0.0, filter_time_constant_us=1.5, fractional=False, amplitude_calibration=False, diagnostics=None, detrend=None)[source]

Complex FFT of a bare (t, A, σ) triple — no MuonDataset required.

The array-taking front door onto the same transform as fft_complex_asymmetry(): both preprocess through one shared core and then run one shared spectral core, so fft_complex_arrays(ds.time, ds.asymmetry, ds.error, …) returns exactly the frequencies and spectrum fft_complex_asymmetry(ds, …) returns — equal bit for bit, with no tolerance. Use it for any curve that is not a dataset’s default reduction (a custom detector pairing, a detrended or background-corrected export, a hand-built model curve) instead of synthesising a MuonDataset to carry it.

Parameters:
  • time, asymmetry, error – As documented on prepare_fft_arrays(). The FFT is scale-linear: percent in, percent-scaled spectrum out.

  • window, padding_factor, t_min, t_max, phase_degrees, t0_offset_us, subtract_average_signal, filter_start_us, filter_time_constant_us, fractional, amplitude_calibration, diagnostics, detrend – Exactly as documented on fft_complex_asymmetry(), keyword-only here because error is optional.

Raises:

ValueError – As prepare_fft_arrays(). The retained time grid must also satisfy the sampling contract of prepare_fft_time_signal().

asymmetry.core.fourier.fft.fft_asymmetry(dataset, window='none', padding_factor=1, t_min=None, t_max=None, phase_degrees=0.0, t0_offset_us=0.0, subtract_average_signal=None, filter_start_us=0.0, filter_time_constant_us=1.5, fractional=False, amplitude_calibration=False, detrend=None)[source]

Compute the FFT of the asymmetry signal.

Parameters:
  • dataset – The time-domain data.

  • window – Apodization window name ("none", "gaussian", "hann", "cosine", "lorentzian"). "gaussian"/"lorentzian" are the WiMDA filters — weight-1 at t = 0, decaying with filter_time_constant_us — while "hann"/"cosine" are symmetric tapers, zero at the record’s ends. A taper is for late-time / narrow-line work and DELETES early-time signal: a heavily damped oscillation (lifetime ≪ record length) can vanish entirely under Hann while being many-sigma with "none" and a crop, or with the exponential filter at filter_time_constant_us ≈ 1/λ (the matched apodisation for a Lorentzian line). This path warns when it detects that case — see ApodisationEarlySignalWarning.

  • padding_factor – Zero-pad the signal to padding_factor × N.

  • t_min, t_max – Restrict the time range before transforming.

  • phase_degrees – Manual phase correction in degrees applied to the complex spectrum before the real and magnitude outputs are derived.

  • t0_offset_us – Additional WiMDA-style time-zero offset in microseconds. This adds the frequency-dependent phase term before the real and magnitude outputs are derived.

  • subtract_average_signal – When true, subtract the WiMDA-style pre-FFT average signal before any window is applied. Defaults to None, which means True unless detrend takes the baseline removal over.

  • filter_start_us – WiMDA-style filter start time in microseconds for "gaussian" and "lorentzian" FFT filtering.

  • filter_time_constant_us – WiMDA-style filter time constant in microseconds for "gaussian" and "lorentzian" FFT filtering.

  • detrend – Baseline removal for a signal that relaxes across the record: None, an integer polynomial order (0–3, fitted error-weighted), or a callable f(time) -> baseline. Applied instead of subtract_average_signal — see “Baseline removal” in prepare_fft_time_signal().

Returns:

frequencies, real_part, magnitude – Frequency axis (MHz) and the real and magnitude spectra.

Raises:

ValueError – If the cropped time grid has fewer than two samples, is not finite and increasing, or deviates from uniform sampling by more than 1e-6 intervals.

asymmetry.core.fourier.fft.fft_arrays(time, asymmetry, error=None, *, window='none', padding_factor=1, t_min=None, t_max=None, phase_degrees=0.0, t0_offset_us=0.0, subtract_average_signal=None, filter_start_us=0.0, filter_time_constant_us=1.5, fractional=False, amplitude_calibration=False, detrend=None)[source]

FFT a bare (t, A, σ) triple — no MuonDataset required.

The array-taking front door matching fft_asymmetry() kwarg for kwarg, running the same complex transform as fft_complex_arrays() and deriving the same two channels fft_asymmetry() derives from fft_complex_asymmetry(). fft_arrays(ds.time, ds.asymmetry, ds.error, …) returns exactly what fft_asymmetry(ds, …) returns — the same frequencies, real part and magnitude, bit for bit.

Parameters:
  • time, asymmetry, error – As documented on prepare_fft_arrays(). The FFT is scale-linear: percent in, percent-scaled spectrum out.

  • window, padding_factor, t_min, t_max, phase_degrees, t0_offset_us, subtract_average_signal, filter_start_us, filter_time_constant_us, fractional, amplitude_calibration, detrend – Exactly as documented on fft_asymmetry(), keyword-only here because error is optional.

Returns:

frequencies, real_part, magnitude – Frequency axis (MHz) and the real and magnitude spectra.

Raises:

ValueError – As prepare_fft_arrays(). The retained time grid must also satisfy the sampling contract of prepare_fft_time_signal().

asymmetry.core.fourier.fft.estimate_fft_phase(freqs, spectrum, *, method='peak', min_frequency=0.0, max_frequency=None)[source]

Estimate the phase, in degrees, that best projects a spectrum onto the real axis.

Parameters:
  • freqs – Frequency axis in MHz.

  • spectrum – Complex FFT spectrum.

  • method – "peak" uses the dominant non-zero frequency bin. "average" uses a power-weighted circular mean across the selected spectrum.

  • min_frequency – Ignore bins below this frequency threshold when estimating the phase.

  • max_frequency – Ignore bins above this frequency threshold when estimating the phase.

asymmetry.core.fourier.fft.fourier_display_values(spectrum, *, display='Real')[source]

Return a display channel, after any required physical phase correction.

asymmetry.core.fourier.fft.exclude_frequency_ranges(freqs, values, exclusion_ranges)[source]

Zero spectral values inside one or more symmetric exclusion ranges.

Parameters:
  • freqs – Frequency axis in MHz.

  • values – Real-valued Fourier display channel to be filtered.

  • exclusion_ranges – Iterable of (center_mhz, half_width_mhz) pairs.

asymmetry.core.fourier.fft.average_fourier_display_values(display_channels, *, estimate_error=False)[source]

Average real-valued Fourier display channels across groups.

When estimate_error is true, the returned error follows the same WiMDA-style grouped-average estimate used for averaged FFT spectra, computed from the per-bin second moment and mean across the selected groups.

Automatic phase estimation

The GroupSpectrumConfig recipe identifier phaseOptReal selects the GUI’s Auto Phase display. Direct estimators use the typed acquisition and result objects below.

Fit a sampled real common-phase signal with nonnegative spectral amplitudes.

The complex response retains both real-signal sidebands and the known mean operator. Complex fitting is motivated by Isaac et al., https://doi.org/10.1016/j.jmr.2025.107991; amplitude elimination follows the variable projection principle of Golub and Pereyra, https://doi.org/10.1088/0266-5611/19/2/201. The uncertainty is conditional on the local active dictionary and excludes model error, changing active sets, and timing/background systematics.

class asymmetry.core.fourier.phase_fit.PhaseAcquisition(time_start_us, sample_interval_us, window_weights, sample_errors, mean_weights, fft_scale=1.0, *, unwindowed_signal)[source]

Known sampling and preprocessing, with prepared samples before windowing.

mean_weights is None only for samples without a constant offset: the response model has no zero-frequency term.

time_start_us
sample_interval_us
window_weights
sample_errors
mean_weights
fft_scale = 1.0
unwindowed_signal
__init__(time_start_us, sample_interval_us, window_weights, sample_errors, mean_weights, fft_scale=1.0, *, unwindowed_signal)
class asymmetry.core.fourier.phase_fit.PhaseFitConfig(minimum_frequency_mhz=None, maximum_frequency_mhz=None, tolerance_degrees=5.0)[source]

Frequency band and maximum tolerated phase sensitivity.

minimum_frequency_mhz = None
maximum_frequency_mhz = None
tolerance_degrees = 5.0
__init__(minimum_frequency_mhz=None, maximum_frequency_mhz=None, tolerance_degrees=5.0)
class asymmetry.core.fourier.phase_fit.PhaseEstimate(phase_radians, standard_error_radians, band_mhz, maximum_change_radians, signal_to_noise, residual_ratio, grid_size, grid_density, observation_band_mhz)[source]

Accepted physical cosine phase at absolute time zero.

phase_radians
standard_error_radians
band_mhz
maximum_change_radians
signal_to_noise
residual_ratio
grid_size
grid_density
observation_band_mhz
to_dict()[source]
__init__(phase_radians, standard_error_radians, band_mhz, maximum_change_radians, signal_to_noise, residual_ratio, grid_size, grid_density, observation_band_mhz)
class asymmetry.core.fourier.phase_fit.PhaseRejection(reason, message, band_mhz=None, observation_band_mhz=None)[source]

An unsuitable measurement has no phase value.

reason
message
band_mhz = None
observation_band_mhz = None
to_dict()[source]
__init__(reason, message, band_mhz=None, observation_band_mhz=None)
exception asymmetry.core.fourier.phase_fit.PhaseFitCancelled[source]

The caller cancelled a phase fit cooperatively.

exception asymmetry.core.fourier.phase_fit.PhaseFitRejectedError(report, message=None)[source]

Expose a typed rejection at front-end boundaries requiring an exception.

__init__(report, message=None)[source]
asymmetry.core.fourier.phase_fit.fit_fft_phase(acquisition, config=PhaseFitConfig(minimum_frequency_mhz=None, maximum_frequency_mhz=None, tolerance_degrees=5.0), *, cancel_callback=None)[source]

Estimate phase from the acquisition’s native rFFT and explicit response fits.

Suitability screens use conservative engineering thresholds, not calibrated confidence levels: conditional total-positive-amplitude SNR >= 8, residual/noise <= 5, edge amplitude <= 5%, and phase sensitivity and conditional error within the requested tolerance. SNR divides total fitted positive amplitude by its correlated-noise standard error from the joint active-amplitude/phase Jacobian; it does not divide by accumulated noise energy in otherwise empty observation guards. This local uncertainty excludes active-set selection and is not a detection confidence. The support band uses at most 257 base lattice centers; three support-band widths of leakage guard on either side bound the native fitting grid to 598 bins. Refinement is capped at 1025 centers and density 24.

Apodisation

Data-driven matched-apodisation suggestion, and the early-signal guard.

Two things live here. suggest_matched_apodisation() computes the matched filter for a spectrum’s dominant line. early_signal_apodisation_loss() is the opposite check — it measures how much early-time signal power an apodisation already in force has removed, and backs ApodisationEarlySignalWarning, which the FFT prepare path raises when a symmetric taper (hann/cosine, zero at the record’s ends) has deleted a heavily damped oscillation — including when that oscillation rides on a slowly relaxing tail whose own power would otherwise mask the loss. That failure mode is concrete: a signal whose lifetime is a small fraction of the record can read as flat noise under Hann while being many-sigma with no window and a crop, or under the exponential (“lorentzian”) filter with filter_time_constant_us ≈ 1/λ.

Advisory only — nothing in the core (or the GUI) ever applies a suggested filter automatically. A matched filter maximises a line’s peak S/N at the cost of roughly doubling its apparent width, so applying one is a decision the user must make knowingly; this module only computes what the matched values would be from the unapodised spectrum.

Widths are measured on the POWER spectrum |F|^2, not the magnitude: the one-sided transform of a damped cosine carries a dispersion part alongside the absorption line, and at half-maximum the magnitude of a Lorentzian is a factor sqrt(3) wider than the absorption shape (the first implementation measured magnitude and recovered relaxation rates ~1.7x too large). On the power spectrum both shapes have closed-form half-widths.

The window parameterisation matches apply_fft_filter() (start_time_us=0); with the power-spectrum FWHM Gamma in MHz and time constants in µs:

  • Lorentzian weight exp(-t/tau). The one-sided transform of exp(-lambda t) cos(w0 t) has power 1/4 / (lambda^2 + dw^2) exactly — a true Lorentzian of FWHM Gamma = lambda / pi (MHz) — so tau = 1 / (pi Gamma).

  • Gaussian weight exp(-(t/tau)^2). For a Gaussian envelope exp(-sigma^2 t^2 / 2) the one-sided power line is (pi/2) exp(-u^2) + 2 Dawson(u / sqrt 2)^2 (in u = dw / sigma units); its half-maximum falls at u* = 1.42294 (numerical root — the Dawson dispersion tail broadens it well past the pure-Gaussian sqrt(ln 2)), so sigma = pi Gamma / u* and the matched tau = sqrt(2) / sigma = sqrt(2) u* / (pi Gamma).

Detection is two-stage. The fast path (asymmetry.core.fourier.apodisation._prominence_line) tests the raw, unsmoothed peak against the window’s median power — cheap, and correct whenever the line already towers over the noise. A line that is genuinely present but sits below that raw threshold (e.g. an un-windowed, lifetime-corrected record whose late-time noise is amplified by the e^{t/tau} correction) needs the power concentrated before it is visible: the fallback (asymmetry.core.fourier.apodisation._matched_scan_fallback) convolves the windowed power spectrum with a family of normalised kernels (Lorentzian or Gaussian, matching the requested filter kind) spanning roughly 10 geometrically-spaced widths, and keeps the width whose robust SNR — median/MAD floor, with the peak region excluded so a real line cannot inflate its own floor — is highest.

The scanned kernel widths are anchored to the spectrum’s INTRINSIC resolution (1 / T_window MHz, the unpadded transform’s bin spacing), not to the padded grid’s bin width: on a zero-padded spectrum adjacent grid bins are correlated over one resolution element, so a kernel a few grid bins wide smooths nothing, and the unsmoothed power-spectrum noise is exponentially distributed — its maximum over thousands of bins hugely exceeds a median + 8 x MAD floor, which would yield false detections on pure noise. With every kernel at least ~4 independent resolution elements wide the smoothed noise is near-Gaussian and the SNR threshold has real headroom. Callers should pass intrinsic_resolution_mhz; when they cannot, the resolution is estimated from the half-maximum lag of the windowed power spectrum’s autocorrelation (the correlation length of the noise).

Smoothing broadens whatever it detects, so the kernel’s own width is then removed from the measured FWHM before any physical quantity is derived from it: linearly for a Lorentzian kernel (widths add), in quadrature for a Gaussian one (variances add). The same resolution-limited guard (_MIN_FWHM_BINS) is applied to that deconvolved width, not the observed one, so a smoothed noise ripple cannot masquerade as a physical line.

exception asymmetry.core.fourier.apodisation.ApodisationEarlySignalWarning[source]

The apodisation in force has deleted the early-time signal.

Raised by the shared FFT prepare core (so both the dataset and the array front doors carry it) when a front-loaded signal meets a symmetric taper window — including the standard case where the damped oscillation rides on a slowly relaxing tail that hides it from a whole-signal power statistic (see early_signal_apodisation_loss()). Advisory only: no returned value changes.

class asymmetry.core.fourier.apodisation.EarlySignalApodisationLoss(early_window_fraction, early_power_fraction, early_retained_fraction, measured_on, verdict, excess_power, significance_floor)[source]

How much early-time signal power the applied apodisation removed.

early_window_fraction

Leading share of the record measured (_EARLY_WINDOW_FRACTION).

early_power_fraction

Share of the error-weighted power living there, on the deciding pass.

early_retained_fraction

Share of that power the window keeps (1.0 = untouched, 0.0 = deleted).

measured_on

Which pass the reported numbers come from — "signal" for the signal’s own power, "oscillatory" for the power left after the slow baseline is removed (see early_signal_apodisation_loss()).

verdict

"triggered", "clear", or "insufficient_statistics" — the last meaning the record’s excess power did not clear the significance gate, so the guard declined to decide rather than deciding on noise. Distinct from "clear", which is a confident “this apodisation is fine”.

excess_power

Total noise-excess power the verdict rests on (the larger of the whole record’s and the early window’s), in units of |s/σ|².

significance_floor

The significance gate that excess was compared against, _EXCESS_SIGNIFICANCE_SIGMA · √(2n).

property triggered[source]

True when both trigger conditions were met on the reported pass.

property assessable[source]

False when there was too little excess power to judge either way.

__init__(early_window_fraction, early_power_fraction, early_retained_fraction, measured_on, verdict, excess_power, significance_floor)
asymmetry.core.fourier.apodisation.early_signal_apodisation_loss(time_us, signal, weights, error=None)[source]

Measure the early-time signal power an apodisation removed.

signal is the pre-window signal (after any cropping, fractional footing and baseline removal) and weights the apodisation weights about to multiply it — the two the FFT prepare core has in hand. Power is |signal/σ|² when usable errors are supplied and |signal|² otherwise, so the well-measured bins dominate exactly as they do in a fit.

Two numbers are computed over the leading _EARLY_WINDOW_FRACTION of the record: how much of the power lives there (early_power_fraction) and how much of that the window keeps (early_retained_fraction). Both conditions must hold to trigger — a heavily damped oscillation under a symmetric taper, which the taper’s zero at t = 0 can erase entirely.

The test runs twice, and triggers if either pass fires:

"signal"

The signal’s own power, as measured.

"oscillatory"

The power left after an error-weighted moving mean (asymmetry.core.fourier.apodisation._slow_baseline, kernel _EARLY_WINDOW_FRACTION of the record) is subtracted — a high-pass that removes the slow component and leaves the oscillation.

The second pass exists because a real ordered-state μSR curve is not a bare damped cosine: it carries a slowly relaxing tail (the powder 1/3 tail) whose amplitude can exceed the oscillation’s. A constant or low-order baseline removal cannot take out that tail’s residual curvature, so its power spreads across the whole record and dilutes the concentration statistic — the signal pass then reads well under the trigger even when the window has deleted essentially all of the oscillatory content. Subtracting the slow baseline first asks the question the guard means to ask: where does the oscillatory power live, and how much of it survives?

Either pass may return "insufficient_statistics" when its excess power does not clear the significance gate — there was not enough signal above the noise to judge, and a ratio computed from a sum consistent with zero would be meaningless. That is reported distinctly from a confident "clear".

The kernel is wide enough to pass any oscillation with more than a handful of cycles across the record. A very slow oscillation — fewer than about 1 / _EARLY_WINDOW_FRACTION (~7) cycles — is partly absorbed into the baseline, which costs sensitivity on that pass only; the signal pass still sees it, and a false negative is the safe direction for an advisory warning.

Returns None when the measurement is not meaningful: too few samples, mismatched shapes, no finite power on either pass, or an apodisation that plainly cannot have done damage.

class asymmetry.core.fourier.apodisation.ApodisationSuggestion(window, time_constant_us, line_frequency_mhz, line_fwhm_mhz)[source]

A matched-filter suggestion derived from one spectral line.

window

"lorentzian" or "gaussian" — the window kind that was matched.

time_constant_us

Matched filter time constant in µs (apply_fft_filter convention).

line_frequency_mhz

Frequency (MHz) of the line the suggestion was matched to.

line_fwhm_mhz

Measured POWER-spectrum FWHM (MHz) of that line, unapodised.

__init__(window, time_constant_us, line_frequency_mhz, line_fwhm_mhz)
asymmetry.core.fourier.apodisation.suggest_matched_apodisation(freqs, magnitude, *, window='lorentzian', min_frequency_mhz=None, max_frequency_mhz=None, intrinsic_resolution_mhz=None)[source]

Suggest the matched apodisation for the dominant line of a spectrum.

freqs/magnitude are the UNAPODISED magnitude spectrum (MHz axis); an already-filtered spectrum would match the filter, not the sample. The optional frequency window restricts the line search (callers narrow it around the field-expected region, as phase estimation does). intrinsic_resolution_mhz is the unpadded transform’s bin spacing (1 / (t_max - t_min)); callers that zero-pad should pass it so the matched-scan fallback’s kernels are anchored to real resolution elements rather than the padded grid (module docstring). When omitted, it is estimated from the spectrum itself (asymmetry.core.fourier.apodisation._estimate_intrinsic_resolution); when even that is not possible the fallback scan is skipped. Detection is two-stage (module docstring): a cheap raw-prominence fast path, then a matched-filter scan for lines buried below it. Returns None — meaning “leave apodisation off” — when neither stage finds a line, when the dominant line is resolution-limited, or when its width cannot be measured inside the window.

Caution

This reasons from the spectrum only and cannot see a dead time-domain envelope. If the spectrum handed to it was itself computed under a symmetric taper that already deleted the early-time signal, the line it is asked to match may simply not be there, and it will report “no clear line” on data that is many-sigma without the taper. It also never suggests a taper: the two kinds it returns ("lorentzian"/"gaussian") are the weight-1-at-t = 0 apply_fft_filter() filters, which are safe for early-time work. The active check for the dead-envelope case is ApodisationEarlySignalWarning, raised by the FFT prepare path; a signal-aware suggester is deliberately not built.

Maximum entropy

Compatibility wrapper for grouped MaxEnt spectral reconstruction.

There is no asymmetry-domain MaxEnt, and there cannot be one. MaxEnt fits a forward model of the raw detector counts, weighting every bin by its own Poisson error and carrying per-group phases, amplitudes and backgrounds; an asymmetry curve has already combined detectors, divided out the normalisations and destroyed exactly those statistics. The frequency-domain estimator for an asymmetry curve is asymmetry.core.fourier.fft.fft_arrays() (or a frequency-domain fit). Callers holding counts but no Run want maxent_from_counts(), re-exported here.

asymmetry.core.fourier.maxent.maxent(dataset, n_freq=512, f_max=None)[source]

Return a MaxEnt spectrum as (frequencies, values).

This preserves the historical Fourier-module import path while delegating to asymmetry.core.maxent. MaxEnt is a grouped raw-count algorithm; callers passing a MuonDataset must provide one with dataset.run.

There is no asymmetry-domain MaxEnt (see the module docstring): an asymmetry curve has destroyed the per-group Poisson statistics the algorithm fits. Use asymmetry.core.fourier.fft.fft_arrays() for a curve, or maxent_from_counts() for counts without a run.

asymmetry.core.fourier.maxent.maxent_from_counts(counts, config=None, *, bin_width_us, t0_bin=0.0, group_names=None, field_gauss=None, alpha=None, run_number=0, cycles=None, state=None, early_stop=True, progress_callback=None, cancel_callback=None)[source]

Reconstruct a MaxEnt spectrum from per-group raw counts — no Run.

There is no asymmetry-domain MaxEnt, and there cannot be one. MaxEnt reconstructs P(B) by fitting a forward model of the counts, weighting every bin by its own Poisson error and carrying per-group phases, amplitudes and backgrounds. An asymmetry curve has already combined detectors, divided out the normalisations and destroyed exactly the per-group statistics the algorithm needs, so there is nothing to hand it. If what you have is an asymmetry curve — a custom pairing, a derived or exported trace — use asymmetry.core.fourier.fft.fft_arrays() (or a frequency-domain fit) instead; that is the array-based frequency estimator for the asymmetry domain.

This entry point exists for the case where you do have counts but no Run to carry them: a re-grouped detector sum, a simulation, counts reconstructed from an export. It shares its whole implementation with maxent() — both build a MaxEntInput through one core and run the same run_cycles() — so the same counts give the same result.

Parameters:
  • counts – Per-group raw detector counts: a mapping {group_id: counts} or a sequence of arrays (numbered 1…n in order). Every group must have the same number of bins, on the same time axis. These are counts, not an asymmetry: values must be finite and non-negative, and the Poisson σ = √N (floored at one count) is derived from them — there is deliberately no way to override it, because a supplied σ that is not the counting error breaks the algorithm’s premise.

  • config – The usual MaxEntConfig (or dict). Everything the algorithm needs that is not count-domain calibration lives here: spectrum points, frequency window, time window and exclusions, cycles and inner iterations, prior level, mode, pulse shape, binning, backend.

  • bin_width_us – Time-bin width in microseconds. Required — the counts alone carry no time axis.

  • t0_bin – Index of t = 0 within the supplied arrays; the time axis is (bin - t0_bin) · bin_width_us. Fractional values are allowed. Default 0.0 (the first bin is t = 0).

  • group_names – Optional {group_id: name} labels for the reconstruction output.

  • field_gauss – Applied field in gauss, used only for the field-centred automatic frequency window (config.auto_window) and the binning auto-steer — exactly what run.metadata["field"] supplies on the Run path. None behaves as a run with no recorded field: the window falls back to the data-aware or explicit bounds.

  • alpha – Forward/backward α, used only in mode="zf_lf" to tie the pair’s amplitudes and backgrounds. Without run metadata to designate them, the order of counts decides: the first group is forward (pinned to 0°), the second backward (180°).

  • run_number – Label carried into MaxEntResult and the reconstruction output.

  • cycles, state, early_stop, progress_callback, cancel_callback – Exactly as documented on maxent().

Returns:

MaxEntResult – As maxent().

Raises:

ValueError – When counts is empty, ragged, non-finite, negative or not one-dimensional, or when bin_width_us is not positive.

Windowing

Apodization / window functions for Fourier analysis.

asymmetry.core.fourier.window.apply_window(signal, name)[source]

Apply a named window function to signal.

Supported names: "gaussian", "hann", "cosine", "lorentzian".

Warning

"hann" and "cosine" are symmetric tapers: they are zero at the first sample and rise as (t/T)², so they DELETE early-time signal. They are for late-time / narrow-line work, where the record is long compared with the signal’s lifetime. A heavily damped oscillation (lifetime ≪ record length) can vanish entirely under a Hann window while being many-sigma without it. For that case use no window with a time crop, or the exponential filter (apply_fft_filter() with mode="lorentzian" and time_constant_us ≈ 1/λ), which is weight-1 at t = 0 and is the matched apodisation for a Lorentzian line. The FFT prepare path warns about this automatically — ApodisationEarlySignalWarning.

asymmetry.core.fourier.window.apply_fft_filter(signal, time_us, *, mode='none', start_time_us=0.0, time_constant_us=1.5)[source]

Apply WiMDA-style FFT apodisation to a time-domain signal.

Unlike the symmetric tapers of apply_window(), these filters are weight-1 at t = 0 (with start_time_us = 0) and decay from there, so they preserve early-time signal. mode="lorentzian" with time_constant_us = 1/λ is the matched apodisation for a Lorentzian-broadened line relaxing at λ: it maximises the line’s peak signal-to-noise, at the cost of roughly doubling its apparent width.

Parameters:
  • signal – Time-domain signal values.

  • time_us – Matching time axis in microseconds.

  • mode – One of "none", "lorentzian", or "gaussian".

  • start_time_us – Filter start time. A value above zero creates WiMDA’s softened step at the chosen start time.

  • time_constant_us – Filter time constant tau in microseconds.

Pulse request contract

GroupSpectrumConfig(pulse_compensation=False) leaves pulse settings unused. Active compensation requires an explicit finite positive pulse_half_width_us (parabolic support half-width). pulse_n_pulses=0 is the explicit identity; 1 consumes width only, and 2 also consumes a finite nonnegative pulse_separation_us. No width is inferred from arbitrary run metadata. Invalid consumed inputs raise PulseRequestError, a ValueError subclass. MaxEnt uses pulse_mode="ignore", "single", or "double" with the same response. Applied result metadata retain the consumed settings and convention.

ISIS pulse-shape response for the MaxEnt forward model.

At a pulsed muon source the muons arrive spread over a finite pulse (≈ tens of ns), so a precession signal oscillating fast compared with the pulse width is averaged across the spread of arrival times and its amplitude is suppressed. Above ~5 MHz this distorts the recovered spectrum unless the forward model accounts for it (Blundell, De Renzi, Lancaster & Pratt, Muon Spectroscopy, OUP 2022, §14.2).

The muon arrival-time distribution is the proton-pulse shape convolved with the pion-decay exponential. Its Fourier transform multiplies each frequency’s contribution to the modelled time signal. For a normalised symmetric parabola of half-width w the cosine transform is

G(ω) = 3 [ sin(x)/x³ − cos(x)/x² ], x = ω·w, G(0) = 1,

and the pion lifetime τ_π adds a single-pole low-pass 1/(1 + i ω τ_π). Writing the combined response as P(ω) = P_cos(ω) − i·P_sin(ω) the forward kernel for one frequency becomes

P_cos(ω)·cos(2πνt + φ) + P_sin(ω)·sin(2πνt + φ),

i.e. a per-frequency amplitude R = √(P_cos² + P_sin²) and phase shift δ = atan2(P_sin, P_cos) applied to the bare cosine kernel — the form the engine consumes. A second proton pulse separated by s adds a cosine interference term weighted by tanh(s/2τ_µ) for unequal muon survival at a common observation time.

The source origin is the proton-pulse centre (single) or midpoint (double), relative to the already resolved observation clock. The causal pion delay is in the response, with no shift to acquired t0 or good bounds. The parabolic support is [-w, w]; its FWHM is sqrt(2) w, not 2w.

This module is the pure pulse mathematics; the engine folds (R, δ) into its real cosine/sine forward and adjoint maps. Frequencies are in MHz and times in µs, so ω = 2πν is in rad/µs and ωt is dimensionless.

asymmetry.core.maxent.pulse.PULSE_MODES = ('ignore', 'single', 'double')

Pulse-mode tokens accepted by pulse_response().

exception asymmetry.core.maxent.pulse.PulseRequestError[source]

An authored pulse request lacks a supported physical input.

asymmetry.core.maxent.pulse.pulse_input_float(value)[source]

Retain unavailable authored scalars for a compute-time request diagnosis.

asymmetry.core.maxent.pulse.pulse_provenance(*, half_width_us, separation_us, n_pulses)[source]

Describe consumed response inputs on the resolved observation clock.

asymmetry.core.maxent.pulse.pulse_response(frequencies_mhz, *, half_width_us, separation_us=0.0, n_pulses=1)[source]

Return (P_cos, P_sin) over frequencies_mhz for the pulse response.

n_pulses == 0 means no pulse shaping: P_cos = 1, P_sin = 0. n_pulses == 1 is the single proton pulse; n_pulses == 2 adds the double-pulse interference at separation_us.

At DC (ν = 0) the response is exactly (1, 0). The single-pulse case is the separation_us → 0 limit of the double-pulse formula.

asymmetry.core.maxent.pulse.pulse_amplitude_phase(frequencies_mhz, *, half_width_us, separation_us=0.0, n_pulses=1)[source]

Return the per-frequency (amplitude R, phase shift δ) for the kernel.

R = √(P_cos² + P_sin²) and δ = atan2(P_sin, P_cos) so that the pulse-shaped kernel is R(ν)·cos(2πνt + φ − δ(ν)). Returns (None, None) when there is no pulse shaping, which the engine treats as the identity (R = 1, δ = 0) on its fast path.

Quantity and sampled support

compute_average_group_spectrum resolves canonical display semantics before conditioning: amplitudes and existing standard errors receive g=1/R; Power and its standard errors receive g**2. Phase angles receive no gain. The amplitude limit pulse_max_gain defaults to 25, so Power can receive up to 625. This preserves mean-of-displayed-quantity group averaging.

The first positive frequency with R < 1/pulse_max_gain and all following bins are omitted from the returned dataset, including its companion fourier_imag channel. Baseline estimation and unit-area normalisation use retained support. The cutoff is a grid-dependent numerical safeguard. fourier_pulse_response metadata record quantity, exponent, amplitude limit, model, consumed parameters, units, source, origin, sign, and cutoff policy; fourier_compensation_cutoff_mhz records the sampled cutoff when reached.

Direct apply_spectrum_conditioning calls accept quantity="amplitude" (default), "power", or "angle"; unknown quantity tokens raise ValueError at this public input boundary. Limits below unity or NaN retain the unity amplitude limit, which applied metadata report. Ignore leaves that limit unused (recorded as None). This lower-level result preserves array shape, marking pulse-removed values/errors as NaN and exposing the amplitude gain (zero for removed support). The public spectrum operation selects the retained bins before returning a dataset. Errors remain conditional on the supplied response and existing estimator; no response uncertainty is added.

Internal diagnostic observations

These Qt-free helpers preserve uniform curves or prepare fixed native count bins over a captured nonuniform observation’s retained native support. They do not change the fitted observation or the direct FFT sampling requirements.

Uniform spectral views of captured counts, separate from fitted observations.

class asymmetry.core.fourier.diagnostic.DiagnosticObservation(time, asymmetry, error, ratio_validity, attribution)[source]

Owned diagnostic arrays in µs/percent, without acquisition replay buffers.

time
asymmetry
error
ratio_validity
attribution
window_attribution(stop, window)[source]

Record the actual transformed window and its fixed sampling interval.

__init__(time, asymmetry, error, ratio_validity, attribution)
asymmetry.core.fourier.diagnostic.prepare_diagnostic_observation(dataset, *, cancel_check=None)[source]

Preserve a uniform curve, or reduce its captured counts on native support.

A Run or recipe alone grants no replay. Selections resolve at the canonical count-binning owner, before the retained native edges become fixed bins. This synchronous operation belongs on the existing numerical worker.

class asymmetry.core.fourier.diagnostic.DiagnosticFitRecord(time, asymmetry, error, metadata=<factory>, run=None, histogram_observation=None, ratio_validity=None, counting_noise=None, effective_recipe=None, computation_revision=None, *, diagnostic_observation)[source]

A process fit record with its separately owned spectral observation.

Constructed only on numerical workers before candidate fan-out. Cropping or merging uses MuonDataset’s constructors and drops this execution context.

diagnostic_observation
__init__(time, asymmetry, error, metadata=<factory>, run=None, histogram_observation=None, ratio_validity=None, counting_noise=None, effective_recipe=None, computation_revision=None, *, diagnostic_observation)
asymmetry.core.fourier.diagnostic.diagnostic_fit_record(dataset, *, diagnostic=None)[source]

Strip acquisitions after preparing the bounded shared spectral payload.

class asymmetry.core.fourier.diagnostic.SpectralPreview(observation, frequency, magnitude, attribution)[source]

Captured Hann preview of the same declared diagnostic observation.

observation
frequency
magnitude
attribution
__init__(observation, frequency, magnitude, attribution)
asymmetry.core.fourier.diagnostic.prepare_spectral_preview(dataset, *, cancel_check=None)[source]

Prepare and transform once on the existing scientific-input worker.

asymmetry.core.fourier.diagnostic.check_diagnostic_cancelled(callback)[source]

Use the existing fit cancellation exception between diagnostic passes.

Units

asymmetry.core.fourier.units.gauss_to_mhz(gauss, *, gyromagnetic_ratio_mhz_per_t=135.5388095)[source]

Convert a field (Gauss) to a frequency (MHz).

Engine

class asymmetry.core.maxent.engine.MaxEntConfig(n_spectrum_points=None, default_level=0.01, f_min_mhz=None, f_max_mhz=None, auto_window=True, window_half_width_gauss=300.0, outer_cycles=10, inner_iterations=12, chi2_target_over_n=1.0, fit_phases=True, auto_phase_seed=True, fit_amplitudes=True, fit_backgrounds=True, fit_constant_background=True, use_deadtime_correction=True, selected_group_ids=None, group_phase_degrees=<factory>, t_min_us=None, t_max_us=None, time_binning_factor=1, auto_steer=True, pulse_mode='ignore', pulse_half_width_us=0.05, pulse_separation_us=0.324, exclude_t_min_us=None, exclude_t_max_us=None, mode='general', specbg_enabled=False, specbg_gaussian_width_mhz=0.1, specbg_lorentzian_width_mhz=0.1, specbg_lorentzian_fraction=0.5, show_reconstruction=False, backend='numpy')[source]

Concrete configuration for one grouped MaxEnt reconstruction.

class asymmetry.core.maxent.engine.MaxEntInput(run_number, groups, n_spectrum_points, f_min_mhz, f_max_mhz, default_level, metadata=<factory>, pulse_amp=None, pulse_phase=None, mode='general', zf_lf_alpha=None)[source]

Prepared raw-count input for joint MaxEnt reconstruction.

class asymmetry.core.maxent.engine.MaxEntResult(frequencies_mhz, spectrum, state, diagnostics, metadata, stop_reason='max_cycles', converged=False, diverged=False, maxent_input=None, computation_revision=None)[source]

Completed or partially-completed MaxEnt reconstruction.

asymmetry.core.maxent.engine.maxent_from_counts(counts, config=None, *, bin_width_us, t0_bin=0.0, group_names=None, field_gauss=None, alpha=None, run_number=0, cycles=None, state=None, early_stop=True, progress_callback=None, cancel_callback=None)[source]

Reconstruct a MaxEnt spectrum from per-group raw counts — no Run.

There is no asymmetry-domain MaxEnt, and there cannot be one. MaxEnt reconstructs P(B) by fitting a forward model of the counts, weighting every bin by its own Poisson error and carrying per-group phases, amplitudes and backgrounds. An asymmetry curve has already combined detectors, divided out the normalisations and destroyed exactly the per-group statistics the algorithm needs, so there is nothing to hand it. If what you have is an asymmetry curve — a custom pairing, a derived or exported trace — use asymmetry.core.fourier.fft.fft_arrays() (or a frequency-domain fit) instead; that is the array-based frequency estimator for the asymmetry domain.

This entry point exists for the case where you do have counts but no Run to carry them: a re-grouped detector sum, a simulation, counts reconstructed from an export. It shares its whole implementation with maxent() — both build a MaxEntInput through one core and run the same run_cycles() — so the same counts give the same result.

Parameters:
  • counts – Per-group raw detector counts: a mapping {group_id: counts} or a sequence of arrays (numbered 1…n in order). Every group must have the same number of bins, on the same time axis. These are counts, not an asymmetry: values must be finite and non-negative, and the Poisson σ = √N (floored at one count) is derived from them — there is deliberately no way to override it, because a supplied σ that is not the counting error breaks the algorithm’s premise.

  • config – The usual MaxEntConfig (or dict). Everything the algorithm needs that is not count-domain calibration lives here: spectrum points, frequency window, time window and exclusions, cycles and inner iterations, prior level, mode, pulse shape, binning, backend.

  • bin_width_us – Time-bin width in microseconds. Required — the counts alone carry no time axis.

  • t0_bin – Index of t = 0 within the supplied arrays; the time axis is (bin - t0_bin) · bin_width_us. Fractional values are allowed. Default 0.0 (the first bin is t = 0).

  • group_names – Optional {group_id: name} labels for the reconstruction output.

  • field_gauss – Applied field in gauss, used only for the field-centred automatic frequency window (config.auto_window) and the binning auto-steer — exactly what run.metadata["field"] supplies on the Run path. None behaves as a run with no recorded field: the window falls back to the data-aware or explicit bounds.

  • alpha – Forward/backward α, used only in mode="zf_lf" to tie the pair’s amplitudes and backgrounds. Without run metadata to designate them, the order of counts decides: the first group is forward (pinned to 0°), the second backward (180°).

  • run_number – Label carried into MaxEntResult and the reconstruction output.

  • cycles, state, early_stop, progress_callback, cancel_callback – Exactly as documented on maxent().

Returns:

MaxEntResult – As maxent().

Raises:

ValueError – When counts is empty, ragged, non-finite, negative or not one-dimensional, or when bin_width_us is not positive.

asymmetry.core.maxent.engine.run_cycles(maxent_input, config=None, *, state=None, cycles=None, early_stop=True, progress_callback=None, cancel_callback=None)[source]

Run up to cycles outer MaxEnt cycles, returning the updated result.

With early_stop (the default) cycles is a maximum: the loop halts at the χ² plateau instead of iterating into the post-optimum divergence that a forced high cycle count (e.g. the GUI’s 50-cycle Converge) otherwise drives. Pass early_stop=False to run the exact count regardless.

asymmetry.core.maxent.engine.maxent(run, config=None, *, cycles=None, state=None, early_stop=True, progress_callback=None, cancel_callback=None)[source]

Compute a grouped MaxEnt spectrum for run.

cycles is an upper bound: the run stops early at the χ² plateau unless early_stop is False.

There is no asymmetry-domain MaxEnt, and there cannot be one. This algorithm fits a forward model of the raw counts, weighting every bin by its own Poisson error and carrying per-group phases, amplitudes and backgrounds; an asymmetry curve has already combined detectors, divided out the normalisations and destroyed exactly those statistics. If what you have is an asymmetry curve, use asymmetry.core.fourier.fft.fft_arrays() (or a frequency-domain fit) instead. If you have counts but no Run to carry them, use maxent_from_counts(), which shares this function’s implementation.

class asymmetry.core.maxent.engine.MaxEntCancelledError[source]

Raised when a MaxEnt calculation is cancelled by the caller.