Skip to main content

nereids_physics/
ikeda_carpenter.rs

1//! Ikeda–Carpenter analytical moderator resolution model.
2//!
3//! A third instrument-resolution model alongside the analytical Gaussian
4//! ([`crate::resolution::ResolutionParams`]) and the Monte-Carlo tabulated
5//! kernel ([`crate::resolution::TabulatedResolution`]). It exists to settle a
6//! methodological dispute about the VENUS instrument resolution: one camp
7//! trusts the MC-simulated tabulated kernel (UDR/FTS file); the instrument
8//! scientist distrusts the unproven MC and prefers an analytical
9//! Ikeda–Carpenter moderator model. NEREIDS implements IC as a first-class
10//! model so all three can be cross-validated against synthetic loop-closure
11//! and real VENUS data.
12//!
13//! # Physics — the Ikeda–Carpenter pulse
14//!
15//! Reference: S. Ikeda & J. M. Carpenter, *Nucl. Instrum. Methods* **A239**
16//! (1985) 536–544. The neutron emission-time distribution from a pulsed
17//! spallation moderator is
18//!
19//! ```text
20//!   I(τ) = (1−R)·g₃(τ;α)  +  R·[g₃(·;α) ⊛ β e^{−β·}](τ),    τ ≥ 0
21//! ```
22//!
23//! where the prompt (slowing-down) term is a Gamma/Erlang density of shape 3:
24//!
25//! ```text
26//!   g₃(τ;α) = α³ τ² e^{−ατ} / 2          (mode 2/α, mean 3/α, ∫ = 1)
27//! ```
28//!
29//! and the delayed (storage) term is `g₃` convolved with an exponential of
30//! rate β. The convolution has the closed form
31//!
32//! ```text
33//!   g₃(·;α) ⊛ β e^{−β·} (τ) = β (α/γ)³ [ e^{−βτ} − e^{−ατ}(1 + γτ + ½γ²τ²) ],  γ = α−β
34//! ```
35//!
36//! SAMMY-RPI χ²+double-exp moderator form). Both terms are individually
37//! unit-area, so `I` is unit-area for any α,β>0 and 0≤R≤1, with first moment
38//! `⟨τ⟩ = 3/α + R/β`. The asymmetry — sharp rise, long tail toward larger τ
39//! (later TOF, lower apparent energy) — is the physical origin of the
40//! asymmetric MC kernel.
41//!
42//! ## Parameters and their energy dependence
43//!
44//! - `α(E)` [1/µs]: fast moderation/leakage rate; sets the prompt width.
45//!   Leading epithermal scaling `α ∝ √E` (Mantid `α = 1/(α₀+α₁λ)`, λ ∝ 1/√E).
46//! - `β(E)` [1/µs]: slow storage rate; sets the delayed tail. Constant by
47//!   default; optionally energy-dependent through an [`EnergyLaw`].
48//! - `R(E)`, 0 ≤ R ≤ 1: storage mixing fraction; `R ≈ exp(−E_meV/κ)` → **R→0 in
49//!   the 1–200 eV resonance regime**, so IC there is dominated by the
50//!   one-parameter prompt Gamma(3, α(E)) term.
51//!
52//! Parameters are **fixed** when the instrument scientist provides them, or
53//! **fit** from a known calibration foil otherwise (general case).
54//!
55//! ## Time → energy kernel and centering
56//!
57//! For a flight path `L`, a resonance at `E_r` has nominal TOF
58//! `t_r = TOF_FACTOR·L/√E_r`. A neutron with emission delay τ arrives at TOF
59//! `t_r+τ`, apparent energy `E' = (TOF_FACTOR·L/(t_r+τ))²` — that is the kernel's
60//! *definition* (its positive-τ tail is delayed emission). Sampling `I(τ)` on
61//! a τ-grid and mapping to TOF-offsets yields exactly the `(offset, weight)`
62//! kernel representation that [`crate::resolution::TabulatedResolution`]
63//! consumes — so IC rides the *same* verified broadening machinery, whose
64//! *application* is the convolution gather: the broadened value at measured TOF
65//! `t` reads theory at `t−τ` (a neutron measured at `t` with delay τ really flew
66//! `t−τ`; see `resolution::broaden` and SAMMY `udr/mudr4.f90` `Ud_Convolute`).
67//! At apply time
68//! `interpolated_kernel` blends the two bracketing reference kernels as a
69//! width-normalized shape blend (offsets scaled to the geometrically
70//! interpolated width, shapes merged on the union grid) — unequal point counts
71//! from IC's per-kernel tail trimming no longer trigger a nearest-reference
72//! fallback, so the between-reference width follows the physical power law
73//! smoothly. IC also synthesizes a dense reference
74//! grid (default 64 energies), so the between-reference error is negligible. The
75//! kernel keeps its offsets on the **emission clock** (0 = pulse start), which
76//! is where the Ikeda–Carpenter function itself places them; a loaded UDR file
77//! is anchored on its peak instead and `interpolated_kernel` re-centers
78//! neither. Because the IC pulse is right-skewed, its *mean* lags its mode by
79//! ~1/α(E) in TOF, so the centroid — and even the minimum — of a broadened
80//! resonance shifts toward **lower apparent energy** by an α(E)-dependent amount
81//! (order 1e-2 eV, ~1e-3 relative, for α≈1.5 in the eV regime; larger toward
82//! lower energy). So it *does* move the broadened dip off the nominal energy,
83//! by a small amount.
84//!
85//! For the prompt-only law `α(E) = a0·√E + a1` with `R≈0`, the lag `~1/α(E)` is
86//! **exactly** the `1/√E` basis of a flight-path (`L_scale`) error *iff* `a1 = 0`:
87//! then the centroid offset scales as `c/√E`, and an `L → L(1+δ)` change shifts
88//! every TOF by `δ·K·L/√E`, also `∝ 1/√E`, so the two are degenerate. With `a1 ≠ 0`
89//! the lag `1/(a0√E + a1)` only *approximately* follows that basis (and the
90//! storage term `R/β`, negligible in the eV regime, adds a further small
91//! departure). To leading order, then, the lag is **confounded with the energy
92//! scale**, and is handled by the SHARED `(t0, L_scale)` energy scale, not by any
93//! per-family knob:
94//! - **Run-time fitting** fits the `t0`/`L_scale` energy-scale, which absorbs the
95//!   constant-`L` part of the lag exactly (same basis); only the *shape*
96//!   (skew/tail) of the asymmetry is not absorbable by position.
97//! - **Resolution calibration** (the `nereids-fitting` calibrator) **pins** the
98//!   energy scale by default — a pure shape/width fit. It can optionally fit a
99//!   SHARED `(t0, L_scale)` under a metrology prior (`with_position_prior`) for
100//!   joint energy-scale / identifiability work. A *free, per-family* position knob
101//!   is deliberately NOT used: because the lag is the same basis as `L_scale`, a
102//!   free position lets a wrong (symmetric) family imitate the asymmetric shift
103//!   and erodes the model-selection χ² (the discriminator is then only the
104//!   position-independent skew/tail). See `nereids-fitting`'s
105//!   `free_l_scale_absorbs_asymmetric_lag_and_erodes_discrimination`.
106//!
107//! `ic_centering_shifts_broadened_symmetric_dip_with_alpha` quantifies the bare
108//! mode→centroid shift; the calibrator's `fit_t0_recovers_injected_energy_scale_shift`
109//! checks the energy-scale fit recovers an injected offset. Re-centering the kernel
110//! on its centroid (a future convention change spanning the UDR path too) would
111//! remove the shift at the source.
112//!
113//! ## Optional instrument convolutions
114//!
115//! The full instrument function folds the moderator with a proton-burst
116//! (Gaussian σ) and a chopper/channel (triangle, FWHM) term. Both are optional
117//! here (`None` ⇒ omitted). Detector-time bin probabilities take the triangle
118//! only and refuse a burst. They also take a detector tail, which records a
119//! fraction of the counts late by an exponential delay; the kernel table
120//! refuses one.
121//!
122//! **Provenance of the triangle (`channel_fwhm_us`).** SAMMY broadens for the
123//! accelerator burst either as a Gaussian of FWHM `DELTAG` (SAMMY Manual R8
124//! Sec. III.C.1.a, eq. III C1 a.12) or as a square pulse of width `BURST`
125//! (Sec. III.C.2.a). At SNS the proton pulse delivered to the target is shaped
126//! by the accumulator ring (Proton Storage Ring, PSR) into an approximately
127//! triangular ~700 ns base — FWHM ≈ 350 ns — which is what the VENUS tabulated
128//! FTS kernel header records as "folded triang FWHM 350 ns PSR". NEREIDS folds
129//! that PSR triangle via `channel_fwhm_us` (symmetric triangle, half-base =
130//! FWHM, `triangle_kernel`). Note: a tabulated file whose header says the
131//! triangle is already "folded" in must NOT be double-counted against an IC
132//! model that also applies it (the `nereids-fitting` calibrator therefore
133//! applies its `psr_fwhm_ns` fold to the IC family only, never to
134//! tabulated/UDR kernels).
135
136use std::ops::RangeInclusive;
137use std::sync::Arc;
138
139use crate::resolution::{ResolutionParseError, TOF_FACTOR, TabulatedResolution};
140
141/// de Broglie wavelength factor: λ (Å) = `LAMBDA_ANGSTROM_FACTOR` / √(E in eV).
142///
143/// `λ = h/√(2·m_n·E)`; with CODATA 2018 `h`, `m_n` and the 2019-SI eV this is
144/// `0.285993 Å·√eV`. Used only by [`EnergyLaw::InverseLambda`]; its precise
145/// value folds into the fitted `α₀,α₁`, so high precision is not load-bearing.
146const LAMBDA_ANGSTROM_FACTOR: f64 = 0.285_993;
147
148/// Rates below this (1/µs) are clamped to keep the pulse well-defined.
149const MIN_RATE: f64 = 1e-9;
150
151/// The detector tail's mean delays `τ_D`, in µs, that the pulse accepts.
152pub const DETECTOR_TAIL_DECAY_US: RangeInclusive<f64> = 1e-9..=1e9;
153
154/// Relative-to-peak weight below which kernel tails are trimmed.
155const TRIM_REL: f64 = 1e-7;
156
157/// Default number of log-spaced reference energies in a synthesized table.
158pub const DEFAULT_N_ENERGIES: usize = 64;
159
160/// Default number of τ-samples spanning the prompt core of each kernel.
161pub const DEFAULT_N_TAU: usize = 600;
162
163/// Minimum accepted `n_tau` (τ-samples across the prompt core). Doubles as
164/// the module's prompt-core **resolution floor**: when [`MAX_TAU_SAMPLES`]
165/// widens the τ-step (see [`tau_geometry`]), the step may never exceed
166/// `fast_reach / (MIN_N_TAU − 1)` — the coarsest prompt sampling
167/// [`IkedaCarpenter::new`] has ever accepted as valid via its `n_tau ≥ 8`
168/// check.
169const MIN_N_TAU: usize = 8;
170
171/// Minimum samples per side SPANNING a sampled channel triangle
172/// (`dtau ≤ FWHM / 3`, half-base = FWHM). At the exactly-admitted boundary
173/// `dtau = FWHM/3` the per-side samples sit at `{FWHM/3, 2FWHM/3, FWHM}` —
174/// triangle weights `{2/3, 1/3, 0}` — so each side carries ≥ 2 strictly
175/// interior (nonzero) samples while the endpoint lands ON the triangle
176/// zero; the sampled fold is distinctly non-delta (discrete variance
177/// 4·FWHM²/27 ≈ 89 % of the analytic FWHM²/6). Coarser steps degenerate
178/// the discrete triangle toward the exact delta `[0, 1, 0]`, silently
179/// erasing a requested fold — [`tau_geometry`] rejects that instead
180/// (strictly: `capped_step > FWHM/3`).
181const TRI_MIN_SAMPLES_PER_SIDE: f64 = 3.0;
182
183const GAUSS_REACH_SIGMAS: f64 = 8.0;
184
185/// Prompt-tail reach in e-folds: the τ-grid spans `FAST_REACH_E_FOLDS / α`
186/// so the prompt Gamma(3) tail `τ²e^{−ατ}` is < ~1e-8 of peak at the edge.
187const FAST_REACH_E_FOLDS: f64 = 18.0;
188
189/// Slow/storage-tail reach in e-folds (`SLOW_REACH_E_FOLDS / β` when storage
190/// is active). Sits AT the trim horizon: `e^{−16} ≈ 1.1e-7 ≈` [`TRIM_REL`]
191/// (`ln(1/TRIM_REL) ≈ 16.1`), so the reach cannot be truncated shorter
192/// without discarding tail weight the [`TRIM_REL`] trim would keep — no
193/// hidden approximation lives in this constant.
194const SLOW_REACH_E_FOLDS: f64 = 16.0;
195
196/// Storage fractions below this are treated as "no storage tail" when sizing
197/// the τ-grid. DELIBERATELY two decades below [`TRIM_REL`], not derived from
198/// it: whether a slow tail actually survives the [`TRIM_REL`] trim depends on
199/// the α/β contrast (the trim threshold is relative to the prompt-dominated
200/// peak, and the slow term's peak weight scales with both R and β/α), so no
201/// single constant derived from [`TRIM_REL`] is exact for every admitted
202/// (α, β) — treating a larger R as absent would be a hidden approximation.
203/// The margin's only consequence is conservatism: for R ∈ (1e-9, ~1e-7) the
204/// τ-grid is sized — and the [`MAX_TAU_SAMPLES`] cap gate applied — for a
205/// slow tail whose weight the trim then discards anyway, spending samples
206/// (or rejecting a configuration) for physics that cannot appear in the
207/// kernel. It can never drop tail weight the trim would have kept.
208const R_NEGLIGIBLE: f64 = 1e-9;
209
210/// Cap on the τ-sample count spanning the PULSE BODY (`[0, τ_max]`) of one
211/// synthesized kernel. The τ-step is anchored to the prompt core and refined
212/// to resolve active folds (see [`tau_geometry`]), so a long storage tail
213/// (β ≪ α with R > 0) grows the sample COUNT rather than the step; this cap
214/// bounds that growth (CPU/memory) by widening the step to
215/// `tau_max / (MAX_TAU_SAMPLES − 1)` — but never past the resolution floor
216/// (prompt core: `fast_reach / (MIN_N_TAU − 1)`; triangle: FWHM /
217/// [`TRI_MIN_SAMPLES_PER_SIDE`]; burst: σ). A parameter/grid combination
218/// whose floor cannot be met within the cap is REJECTED loudly by
219/// [`IkedaCarpenter::new`] instead of silently under-sampled. The actual
220/// guarantee is on the pulse body only: the symmetric burst/channel fold
221/// margin (± `GAUSS_REACH_SIGMAS·σ + FWHM` at the resolved step) adds its
222/// samples ON TOP of the cap, so the final grid can exceed
223/// `MAX_TAU_SAMPLES` by the margin sample count.
224const MAX_TAU_SAMPLES: usize = 8192;
225
226#[inline]
227fn h_over_cube_taylor(u: f64) -> f64 {
228    exponential_tail_series(u, 3)
229}
230
231#[inline]
232fn exponential_tail_series(u: f64, shift: u32) -> f64 {
233    let mut sum = 0.0;
234    let mut power = 0.5;
235    for n in 0..64_u32 {
236        let next = sum + power / f64::from(n + shift);
237        if next == sum {
238            break;
239        }
240        sum = next;
241        power *= -u / f64::from(n + 1);
242    }
243    sum
244}
245
246/// Ikeda–Carpenter moderator emission density `I(τ)`.
247///
248/// `τ` in µs, rates `α,β` in 1/µs, mixing `r ∈ [0,1]`. Returns 0 for `τ < 0`.
249/// Unit-area over `τ ∈ [0,∞)`; first moment `3/α + r/β`. **NaN-free** for all
250/// `α,β > 0` (including `α ≈ β` and `β ≫ α`): the slow/storage term is evaluated
251/// from the bounded bracket `e^{−βτ} − e^{−ατ}(1+u+½u²)` (both exponentials ≤ 1
252/// for `τ,α,β > 0`, so no `e^{|u|}` overflow), falling back to a Taylor limit
253/// near `u = α−β·τ → 0` where that bracket cancels.
254#[must_use]
255pub fn ic_pulse(alpha: f64, beta: f64, r: f64, tau: f64) -> f64 {
256    // Same domain contract as ic_cdf: non-finite parameters return NaN so
257    // garbage in stays visible instead of flooring into a plausible pulse.
258    if !alpha.is_finite() || !beta.is_finite() || !r.is_finite() {
259        return f64::NAN;
260    }
261    if !tau.is_finite() || tau < 0.0 {
262        return 0.0;
263    }
264    let alpha = alpha.max(MIN_RATE);
265    let beta = beta.max(MIN_RATE);
266    let at = alpha * tau;
267    // prompt Gamma(3,α): α³τ²/2 · e^{−ατ} = (α/2)(ατ)² e^{−ατ}
268    let fast = 0.5 * alpha * at * at * (-at).exp();
269    if r <= 0.0 {
270        return fast;
271    }
272    (1.0 - r) * fast + r * storage_density(alpha, beta, tau)
273}
274
275fn storage_density(alpha: f64, beta: f64, tau: f64) -> f64 {
276    // slow/storage term = β(α/γ)³[e^{−βτ} − e^{−ατ}(1+u+½u²)], u = γτ = (α−β)τ.
277    let u = (alpha - beta) * tau;
278    let coeff = beta * alpha.powi(3) * tau.powi(3);
279    if u.abs() < 0.05 {
280        // α ≈ β: bracket/u³ → e^{−βτ}·h(u)/u³ (Taylor); avoids 0/0 cancellation.
281        coeff * (-beta * tau).exp() * h_over_cube_taylor(u)
282    } else {
283        // Bounded form: both exponentials are ≤ 1, so β ≫ α (u ≪ 0) cannot
284        // overflow (the old `e^{−βτ}·h(u)` factored an `e^{|u|}` → 0·∞ = NaN).
285        let bracket = (-beta * tau).exp() - (-alpha * tau).exp() * (1.0 + u + 0.5 * u * u);
286        coeff * bracket / (u * u * u)
287    }
288}
289
290fn ic_pulse_slope(alpha: f64, beta: f64, r: f64, tau: f64) -> f64 {
291    if !tau.is_finite() || tau < 0.0 {
292        return 0.0;
293    }
294    let alpha = alpha.max(MIN_RATE);
295    let beta = beta.max(MIN_RATE);
296    let at = alpha * tau;
297    let prompt = 0.5 * alpha * at * at * (-at).exp();
298    let prompt_slope = 0.5 * alpha * alpha * at * (2.0 - at) * (-at).exp();
299    if r <= 0.0 {
300        return prompt_slope;
301    }
302    (1.0 - r) * prompt_slope + r * beta * (prompt - storage_density(alpha, beta, tau))
303}
304
305/// Cumulative probability of the Ikeda–Carpenter moderator pulse.
306///
307/// Returns `P(U <= tau)` for moderator delay `U`. `tau` is in µs and rates
308/// are in 1/µs. The prompt term is the Gamma(3, α) cumulative distribution;
309/// the storage term is the cumulative distribution of Gamma(3, α) plus an
310/// independent exponential delay with rate β.
311///
312/// The expression is evaluated without subtracting nearly equal exponentials
313/// when `α ≈ β`. This is the bin-integral companion to [`ic_pulse`].
314///
315/// Domain contract: non-finite `alpha`, `beta`, or `r` returns NaN so garbage
316/// in stays visible; finite non-positive rates are floored to `MIN_RATE`
317/// (1e-9 µs⁻¹) and `r <= 0` disables the storage term, matching
318/// [`ic_pulse`]. A NaN `tau`
319/// returns 0 — `tau` is the integration coordinate, not a parameter, and a
320/// non-arriving coordinate contributes no mass.
321#[must_use]
322pub fn ic_cdf(alpha: f64, beta: f64, r: f64, tau: f64) -> f64 {
323    if !alpha.is_finite() || !beta.is_finite() || !r.is_finite() {
324        return f64::NAN;
325    }
326    if tau.is_nan() || tau <= 0.0 {
327        return 0.0;
328    }
329    if tau == f64::INFINITY {
330        return 1.0;
331    }
332
333    let alpha = alpha.max(MIN_RATE);
334    let beta = beta.max(MIN_RATE);
335    let at = alpha * tau;
336    let fast = gamma3_cdf(at);
337    if r <= 0.0 {
338        return fast;
339    }
340
341    // Far in the tails the general expressions overflow — `at³` or `u³`
342    // reach f64::INFINITY and produce inf·0 / inf/inf = NaN — while the
343    // limits are exact to full f64 precision, so return them directly.
344    // For at ≥ 1e100 the prompt CDF is 1 and the storage correction is
345    // exp(−βτ) with relative error ≤ 3βτ/at; for βτ ≥ 1e100 the storage
346    // delay is instantaneous and the correction is 0.
347    const CDF_TAIL_LIMIT: f64 = 1.0e100;
348    if at >= CDF_TAIL_LIMIT {
349        return (1.0 - r * (-beta * tau).exp()).clamp(0.0, 1.0);
350    }
351    if beta * tau >= CDF_TAIL_LIMIT {
352        return fast;
353    }
354
355    // The storage CDF is the prompt CDF minus the positive survival
356    // correction below. Written this way, the α=β limit is Gamma(4, α).
357    let u = (alpha - beta) * tau;
358    let correction = if u.abs() < 0.05 {
359        at.powi(3) * (-beta * tau).exp() * h_over_cube_taylor(u)
360    } else {
361        // Bounded form: neither exponential can overflow even when β >> α.
362        let bracket = (-beta * tau).exp() - (-alpha * tau).exp() * (1.0 + u + 0.5 * u * u);
363        at.powi(3) * bracket / u.powi(3)
364    };
365    (fast - r * correction).clamp(0.0, 1.0)
366}
367
368fn ic_cdf_slopes(alpha: f64, beta: f64, r: f64, tau: f64) -> [f64; 3] {
369    if !alpha.is_finite() || !beta.is_finite() || !r.is_finite() {
370        return [f64::NAN; 3];
371    }
372    if tau.is_nan() || tau <= 0.0 || tau == f64::INFINITY {
373        return [0.0; 3];
374    }
375    let at = alpha * tau;
376    let fast = 0.5 * tau * at * at * (-at).exp();
377    const CDF_TAIL_LIMIT: f64 = 1.0e100;
378    if at >= CDF_TAIL_LIMIT {
379        let storage = (-beta * tau).exp();
380        return [0.0, r * tau * storage, -storage];
381    }
382    if beta * tau >= CDF_TAIL_LIMIT {
383        return [fast, 0.0, 0.0];
384    }
385    let u = (alpha - beta) * tau;
386    let (correction, slope) = if u.abs() < 0.05 {
387        let storage = (-beta * tau).exp();
388        (
389            at.powi(3) * storage * h_over_cube_taylor(u),
390            -tau * storage * exponential_tail_series(u, 4),
391        )
392    } else {
393        let prompt = (-alpha * tau).exp();
394        let bracket = (-beta * tau).exp() - prompt * (1.0 + u + 0.5 * u * u);
395        (
396            at.powi(3) * bracket / u.powi(3),
397            tau * (prompt / (2.0 * u) - 3.0 * bracket / u.powi(4)),
398        )
399    };
400    let moved = at.powi(3) * slope;
401    [
402        fast - r * (3.0 * correction / alpha + moved),
403        r * (tau * correction + moved),
404        -correction,
405    ]
406}
407
408const GAUSS_LEGENDRE_16: [(f64, f64); 8] = [
409    (0.095_012_509_837_637_44, 0.189_450_610_455_068_59),
410    (0.281_603_550_779_258_9, 0.182_603_415_044_923_6),
411    (0.458_016_777_657_227_37, 0.169_156_519_395_002_62),
412    (0.617_876_244_402_643_8, 0.149_595_988_816_576_65),
413    (0.755_404_408_355_003_1, 0.124_628_971_255_533_95),
414    (0.865_631_202_387_831_6, 0.095_158_511_682_493),
415    (0.944_575_023_073_232_6, 0.062_253_523_938_647_61),
416    (0.989_400_934_991_649_9, 0.027_152_459_411_754_055),
417];
418
419fn fold_nodes(alpha: f64, fwhm_us: f64, delay_us: f64, mut node: impl FnMut(f64, f64)) {
420    let end = delay_us.min(fwhm_us);
421    let finest = 2.0 / alpha.max(MIN_RATE);
422    for (lo, hi) in [(-fwhm_us, end.min(0.0)), (0.0, end)] {
423        let (mut right, mut width) = (hi, finest);
424        while right > lo {
425            let left = (right - width).max(lo);
426            let (centre, half) = (0.5 * (left + right), 0.5 * (right - left));
427            for &(position, weight) in &GAUSS_LEGENDRE_16 {
428                for s in [centre - half * position, centre + half * position] {
429                    node(s, half * weight);
430                }
431            }
432            right = left;
433            width *= 2.0;
434        }
435    }
436}
437
438fn triangle_fold<const N: usize>(
439    alpha: f64,
440    fwhm_us: f64,
441    delay_us: f64,
442    g: impl Fn(f64) -> [f64; N],
443) -> [f64; N] {
444    let mut total = [0.0; N];
445    fold_nodes(alpha, fwhm_us, delay_us, |s, weight| {
446        for (sum, value) in total.iter_mut().zip(g(delay_us - s)) {
447            *sum += weight * (fwhm_us - s.abs()) / (fwhm_us * fwhm_us) * value;
448        }
449    });
450    total
451}
452
453fn folded_slopes(pulse: &Recorded, fwhm_us: f64, delay_us: f64) -> [f64; 4] {
454    let mut slopes = [0.0; 4];
455    fold_nodes(pulse.alpha, fwhm_us, delay_us, |s, weight| {
456        let x = delay_us - s;
457        let t = (s / fwhm_us).abs();
458        let triangle = weight * (1.0 - t) / fwhm_us;
459        let values = pulse.slopes(x);
460        for (slope, value) in slopes.iter_mut().zip(&values[..3]) {
461            *slope += triangle * value;
462        }
463        let moment = (1.0 / 6.0 - 0.5 * t * t + t.powi(3) / 3.0) / (2.0 * fwhm_us);
464        slopes[3] += weight * moment * values[3];
465    });
466    slopes
467}
468
469/// The pulse at one energy as the detector records it: rates `α` and `β`,
470/// storage fraction `R`, and the detector tail's fraction `f` and rate
471/// `1/τ_D`.
472#[derive(Debug, Clone, Copy)]
473struct Recorded {
474    alpha: f64,
475    beta: f64,
476    r: f64,
477    tail: Option<(f64, f64)>,
478}
479
480impl Recorded {
481    fn delayed(&self) -> Option<(f64, f64)> {
482        self.tail.filter(|&(fraction, _)| fraction != 0.0)
483    }
484
485    fn cdf(&self, tau: f64) -> f64 {
486        let plain = ic_cdf(self.alpha, self.beta, self.r, tau);
487        match self.delayed() {
488            None => plain,
489            Some((f, rate)) => ((1.0 - f) * plain + f * self.late(rate, tau)[0]).clamp(0.0, 1.0),
490        }
491    }
492
493    fn density(&self, tau: f64) -> f64 {
494        let plain = ic_pulse(self.alpha, self.beta, self.r, tau);
495        match self.delayed() {
496            None => plain,
497            Some((f, rate)) => (1.0 - f) * plain + f * self.late(rate, tau)[5],
498        }
499    }
500
501    /// `[∂/∂α, ∂/∂β, ∂/∂R]` of [`Self::cdf`], and the slope of
502    /// [`Self::density`].
503    fn slopes(&self, tau: f64) -> [f64; 4] {
504        let [a, b, c] = ic_cdf_slopes(self.alpha, self.beta, self.r, tau);
505        let plain = [a, b, c, ic_pulse_slope(self.alpha, self.beta, self.r, tau)];
506        match self.delayed() {
507            None => plain,
508            Some((f, rate)) => {
509                let late = self.late(rate, tau);
510                let late = [late[1], late[2], late[3], late[6]];
511                std::array::from_fn(|n| (1.0 - f) * plain[n] + f * late[n])
512            }
513        }
514    }
515
516    /// `[∂/∂f, ∂/∂τ_D]` of [`Self::cdf`], 0 without a tail.
517    fn tail_slopes(&self, tau: f64) -> [f64; 2] {
518        let Some((f, rate)) = self.tail else {
519            return [0.0; 2];
520        };
521        let late = self.late(rate, tau);
522        [
523            late[0] - ic_cdf(self.alpha, self.beta, self.r, tau),
524            -f * rate * rate * late[4],
525        ]
526    }
527
528    fn late(&self, rate: f64, tau: f64) -> [f64; 7] {
529        delayed(self.alpha, self.beta, self.r, rate, tau)
530    }
531}
532
533/// The relative distance from `β` within which [`delayed`] interpolates in
534/// the tail's rate.
535const NEAR_RATE: f64 = 1e-3;
536
537/// The pulse delayed by an exponential of rate `rate`, at delay `tau`:
538/// `[G, ∂G/∂α, ∂G/∂β, ∂G/∂R, ∂G/∂rate, G′, G″]` with
539/// `G = S_λ + Rλ(S_β − S_λ)/(λ − β)`, `λ` the rate and `S_x` the cumulative
540/// probability of Gamma(3, α) plus an exponential delay of rate `x`.  Within
541/// [`NEAR_RATE`] of `β`, each is the cubic through its values at the rates
542/// `β(1 ± NEAR_RATE)` and `β(1 ± 2·NEAR_RATE)`.
543fn delayed(alpha: f64, beta: f64, r: f64, rate: f64, tau: f64) -> [f64; 7] {
544    let gap = (rate - beta) / (NEAR_RATE * beta);
545    if gap.abs() >= 1.0 {
546        return delayed_apart(alpha, beta, r, rate, tau);
547    }
548    let mut total = [0.0; 7];
549    for (node, weight) in [
550        (-2.0, (gap * gap - 1.0) * (gap - 2.0) / -12.0),
551        (-1.0, (gap + 2.0) * (gap - 1.0) * (gap - 2.0) / 6.0),
552        (1.0, (gap + 2.0) * (gap + 1.0) * (gap - 2.0) / -6.0),
553        (2.0, (gap + 2.0) * (gap * gap - 1.0) / 12.0),
554    ] {
555        let values = delayed_apart(alpha, beta, r, beta * (1.0 + node * NEAR_RATE), tau);
556        for (sum, value) in total.iter_mut().zip(values) {
557            *sum += weight * value;
558        }
559    }
560    total
561}
562
563fn delayed_apart(alpha: f64, beta: f64, r: f64, rate: f64, tau: f64) -> [f64; 7] {
564    if tau.is_nan() || tau <= 0.0 {
565        return [0.0; 7];
566    }
567    if tau == f64::INFINITY {
568        return [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
569    }
570    let alpha = alpha.max(MIN_RATE);
571    let at = alpha * tau;
572    let (whole, prompt) = (gamma3_cdf(at), 0.5 * alpha * at * at * (-at).exp());
573    let storage = |x: f64| {
574        let [by_alpha, by_rate, lost] = ic_cdf_slopes(alpha, x, 1.0, tau);
575        let density = -x * lost;
576        [
577            whole + lost,
578            by_alpha,
579            by_rate,
580            density,
581            x * (prompt - density),
582        ]
583    };
584    let (at_beta, at_rate) = (storage(beta), storage(rate));
585    let gap = rate - beta;
586    let apart: [f64; 5] = std::array::from_fn(|n| (at_beta[n] - at_rate[n]) / gap);
587    [
588        at_rate[0] + r * rate * apart[0],
589        at_rate[1] + r * rate * apart[1],
590        r * rate * (at_beta[2] + apart[0]) / gap,
591        rate * apart[0],
592        at_rate[2] + r * apart[0] - r * rate * (at_rate[2] + apart[0]) / gap,
593        at_rate[3] + r * rate * apart[3],
594        at_rate[4] + r * rate * apart[4],
595    ]
596}
597
598/// Each bin's difference of `g` between its upper and lower edge, `g` taken
599/// at the edge's delay after `arrival_us`.
600fn bin_differences<const N: usize>(
601    edges_us: &[f64],
602    arrival_us: f64,
603    g: impl Fn(f64) -> [f64; N],
604) -> [Vec<f64>; N] {
605    let at_edges: Vec<[f64; N]> = edges_us.iter().map(|edge| g(edge - arrival_us)).collect();
606    std::array::from_fn(|n| at_edges.windows(2).map(|w| w[1][n] - w[0][n]).collect())
607}
608
609/// Gamma(3, rate=1) cumulative distribution at dimensionless time `x`.
610fn gamma3_cdf(x: f64) -> f64 {
611    if x <= 0.0 {
612        return 0.0;
613    }
614    // Beyond x ≈ 750 the survival term exp(−x)·(1+x+x²/2) underflows to an
615    // exact zero long before the polynomial can overflow (x² reaches
616    // f64::INFINITY only at x ~ 1.3e154, where 0·inf would be NaN).
617    if x >= 750.0 {
618        return 1.0;
619    }
620    if x < 0.5 {
621        // Integral of x² exp(-x) / 2 as an alternating series. The direct
622        // `1 - exp(-x)(1+x+x²/2)` loses most digits for small x.
623        let mut n = 0_u32;
624        let mut term = x.powi(3) / 6.0;
625        let mut sum = term;
626        loop {
627            let n_f = f64::from(n);
628            term *= -x * (n_f + 3.0) / ((n_f + 1.0) * (n_f + 4.0));
629            let next = sum + term;
630            n += 1;
631            if next == sum || n >= 128 {
632                return next.clamp(0.0, 1.0);
633            }
634            sum = next;
635        }
636    }
637    (1.0 - (-x).exp() * (1.0 + x + 0.5 * x * x)).clamp(0.0, 1.0)
638}
639
640/// Energy-dependence law for an Ikeda–Carpenter parameter.
641///
642/// A small closed set so the *fixed-or-fit* cases share one representation:
643/// fixed ⇒ [`Const`](EnergyLaw::Const); fit ⇒ a parametric law whose
644/// coefficients are the fit variables.
645#[derive(Debug, Clone, PartialEq)]
646pub enum EnergyLaw {
647    /// Energy-independent constant.
648    Const(f64),
649    /// `a0·√(E[eV]) + a1` — leading epithermal scaling of the fast rate `α(E)`.
650    SqrtE { a0: f64, a1: f64 },
651    /// `a0·E^exponent + a1`, `E` in eV; an exponent of 1/2 is [`SqrtE`](EnergyLaw::SqrtE).
652    PowerE { a0: f64, a1: f64, exponent: f64 },
653    /// Mantid IC form `1/(a0 + a1·λ)`, λ (Å) = `LAMBDA_ANGSTROM_FACTOR`/√E.
654    /// Behaves as `α ∝ √E` at low E and saturates to `1/a0` at high E.
655    InverseLambda { a0: f64, a1: f64 },
656    /// `exp(−E[meV]/kappa)` — storage fraction `R(E)`, → 0 in the eV regime.
657    ExpMilliEv { kappa: f64 },
658    /// Linear in `√E` from `low` at `span_ev.0` to `high` at `span_ev.1` eV,
659    /// and between `low` and `high` at every energy.
660    SqrtEBetween {
661        low: f64,
662        high: f64,
663        span_ev: (f64, f64),
664    },
665}
666
667impl EnergyLaw {
668    /// Evaluate the law at `energy_ev` (eV). Non-positive energy yields the
669    /// `E→0` limit where well-defined (and a clamped value otherwise).
670    #[must_use]
671    pub fn eval(&self, energy_ev: f64) -> f64 {
672        let e = energy_ev.max(0.0);
673        match *self {
674            EnergyLaw::Const(c) => c,
675            EnergyLaw::SqrtE { a0, a1 } => a0 * e.sqrt() + a1,
676            EnergyLaw::PowerE { a0, a1, exponent } => {
677                // `sqrt` and `powf(0.5)` may differ in the last bit.
678                let power = if exponent == 0.5 {
679                    e.sqrt()
680                } else {
681                    e.powf(exponent)
682                };
683                a0 * power + a1
684            }
685            EnergyLaw::InverseLambda { a0, a1 } => {
686                let denom = inverse_lambda_denom(a0, a1, e);
687                if denom.abs() < MIN_RATE {
688                    1.0 / MIN_RATE
689                } else {
690                    1.0 / denom
691                }
692            }
693            EnergyLaw::ExpMilliEv { kappa } => {
694                if kappa.abs() < MIN_RATE {
695                    0.0
696                } else {
697                    (-(e * 1000.0) / kappa).exp()
698                }
699            }
700            EnergyLaw::SqrtEBetween {
701                low,
702                high,
703                span_ev: (e_low, e_high),
704            } => {
705                let share = (e.sqrt() - e_low.sqrt()) / (e_high.sqrt() - e_low.sqrt());
706                (low + (high - low) * share).clamp(low.min(high), low.max(high))
707            }
708        }
709    }
710
711    /// True when the law is numerically singular at `energy_ev`: the raw
712    /// `InverseLambda` denominator lies inside the ±[`MIN_RATE`] window that
713    /// [`EnergyLaw::eval`] floors away. The floor keeps a fit trial step from
714    /// dividing by zero mid-optimization, but a *configured* law inside that
715    /// window is a mathematically undefined rate, not a large one — without
716    /// this check the floor converts an undefined (or tiny-negative)
717    /// denominator into a plausible huge positive rate before the range
718    /// validation below can see it.
719    #[must_use]
720    pub(crate) fn is_singular_at(&self, energy_ev: f64) -> bool {
721        match *self {
722            EnergyLaw::InverseLambda { a0, a1 } => {
723                inverse_lambda_denom(a0, a1, energy_ev.max(0.0)).abs() < MIN_RATE
724            }
725            // κ = 0 is undefined and a tiny NEGATIVE κ is a divergent law
726            // (exp(+E/|κ|)); eval's floor maps both to 0.0, which is the
727            // legitimate κ → 0⁺ limit only for positive κ.
728            EnergyLaw::ExpMilliEv { kappa } => (-MIN_RATE..=0.0).contains(&kappa),
729            _ => false,
730        }
731    }
732}
733
734/// Raw `InverseLambda` denominator `a0 + a1·λ(E)` — shared by [`EnergyLaw::eval`]
735/// and the singularity check so the two can never disagree on the window.
736fn inverse_lambda_denom(a0: f64, a1: f64, e: f64) -> f64 {
737    let lambda = if e > 0.0 {
738        LAMBDA_ANGSTROM_FACTOR / e.sqrt()
739    } else {
740        f64::INFINITY
741    };
742    a0 + a1 * lambda
743}
744
745/// Parameters of the Ikeda–Carpenter resolution model.
746#[derive(Debug, Clone, PartialEq)]
747pub struct IkedaCarpenterParams {
748    /// Fast (slowing-down) rate `α(E)`, 1/µs. Must evaluate to at least
749    /// 1e-9.
750    pub alpha: EnergyLaw,
751    /// Slow (storage) rate `β(E)`, 1/µs. Must evaluate to at least 1e-9.
752    pub beta: EnergyLaw,
753    /// Storage mixing fraction `R(E)`, 0 ≤ R ≤ 1.
754    pub r: EnergyLaw,
755    /// Optional proton-burst Gaussian standard deviation (µs); refused in
756    /// detector time.
757    pub burst_sigma_us: Option<f64>,
758    /// Optional chopper/channel triangle FWHM (µs).
759    pub channel_fwhm_us: Option<f64>,
760    /// Optional detector tail; detector time only, refused by the kernel
761    /// table.
762    pub detector_tail: Option<DetectorTail>,
763}
764
765/// A detector that records a fraction `f` of the counts late by an
766/// exponential delay of mean `τ_D`, and the rest at their arrival.
767#[derive(Debug, Clone, Copy, PartialEq)]
768pub struct DetectorTail {
769    /// `f`, within 0–1.
770    pub fraction: f64,
771    /// `τ_D` in µs, from 1e-9 to 1e9.
772    pub decay_us: f64,
773}
774
775impl IkedaCarpenterParams {
776    /// A pure-moderator parameter set (no burst, no channel) with constant
777    /// rates — the simplest case, useful for fixed-parameter or unit-test use.
778    #[must_use]
779    pub fn constant(alpha: f64, beta: f64, r: f64) -> Self {
780        Self {
781            alpha: EnergyLaw::Const(alpha),
782            beta: EnergyLaw::Const(beta),
783            r: EnergyLaw::Const(r),
784            burst_sigma_us: None,
785            channel_fwhm_us: None,
786            detector_tail: None,
787        }
788    }
789
790    fn tail_rate(&self) -> Result<Option<(f64, f64)>, ResolutionParseError> {
791        let Some(tail) = self.detector_tail else {
792            return Ok(None);
793        };
794        if !((0.0..=1.0).contains(&tail.fraction)
795            && DETECTOR_TAIL_DECAY_US.contains(&tail.decay_us))
796        {
797            return Err(ResolutionParseError::InvalidFormat(format!(
798                "a detector tail needs a fraction within 0–1 and a decay from {:e} to {:e} µs, \
799                 got {tail:?}",
800                DETECTOR_TAIL_DECAY_US.start(),
801                DETECTOR_TAIL_DECAY_US.end()
802            )));
803        }
804        Ok(Some((tail.fraction, 1.0 / tail.decay_us)))
805    }
806
807    fn recorded_at(&self, energy_ev: f64) -> Result<Recorded, ResolutionParseError> {
808        self.validate_probe_energy(energy_ev)?;
809        Ok(Recorded {
810            alpha: self.alpha.eval(energy_ev),
811            beta: self.beta.eval(energy_ev),
812            r: self.r.eval(energy_ev),
813            tail: self.tail_rate()?,
814        })
815    }
816
817    fn triangle_fwhm_us(&self) -> Result<f64, ResolutionParseError> {
818        if self.burst_sigma_us.unwrap_or(0.0) != 0.0 {
819            return Err(ResolutionParseError::InvalidFormat(
820                "a Gaussian burst is not supported in detector time; model the proton \
821                 pulse with channel_fwhm_us"
822                    .to_string(),
823            ));
824        }
825        let fwhm_us = self.channel_fwhm_us.unwrap_or(0.0);
826        if !(fwhm_us.is_finite() && fwhm_us >= 0.0) {
827            return Err(ResolutionParseError::InvalidFormat(format!(
828                "the triangle's FWHM must be finite and 0 or more, got {fwhm_us} µs"
829            )));
830        }
831        Ok(fwhm_us)
832    }
833
834    /// The first and last delay, in µs after the nominal arrival, of a
835    /// neutron of `energy_ev`, outside which [`IkedaCarpenter::detector_bin_probabilities`]
836    /// gives it less than [`NEGLIGIBLE_ARRIVAL_PROBABILITY`] chance of
837    /// arriving: the triangle's half-base before 0, and that half-base after
838    /// the delay where the chance of a later record without the triangle
839    /// falls to that chance.
840    ///
841    /// # Errors
842    /// [`ResolutionParseError::InvalidFormat`] when `energy_ev` is not
843    /// positive and finite, a law is singular or out of range there, the
844    /// pulse has a Gaussian burst, or its detector tail is out of range.
845    pub fn delays_us(&self, energy_ev: f64) -> Result<(f64, f64), ResolutionParseError> {
846        let pulse = self.recorded_at(energy_ev)?;
847        let h = self.triangle_fwhm_us()?;
848        Ok((-h, tail_delay(&pulse) + h))
849    }
850
851    /// Probability that a neutron of `true_energy_ev` whose nominal arrival,
852    /// before the pulse's delay, is `arrival_us` is recorded in each bin of
853    /// `detector_time_edges_us`; as [`IkedaCarpenter::detector_bin_probabilities`].
854    ///
855    /// # Errors
856    /// As [`IkedaCarpenter::detector_bin_probabilities`], with `arrival_us` finite.
857    pub fn bin_probabilities_at(
858        &self,
859        true_energy_ev: f64,
860        arrival_us: f64,
861        detector_time_edges_us: &[f64],
862    ) -> Result<Vec<f64>, ResolutionParseError> {
863        let (pulse, h) = self.at_arrival(true_energy_ev, arrival_us, detector_time_edges_us)?;
864        let cdf = |x: f64| {
865            if h == 0.0 {
866                pulse.cdf(x)
867            } else {
868                triangle_fold(pulse.alpha, h, x, |tau| [pulse.cdf(tau)])[0].clamp(0.0, 1.0)
869            }
870        };
871        let cdfs: Vec<f64> = detector_time_edges_us
872            .iter()
873            .map(|edge| cdf(edge - arrival_us))
874            .collect();
875        Ok(cdfs.windows(2).map(|w| (w[1] - w[0]).max(0.0)).collect())
876    }
877
878    /// The derivative of each of [`Self::bin_probabilities_at`] with respect
879    /// to `arrival_us`, per µs: the pulse density, folded with the triangle,
880    /// at the bin's lower edge minus that at its upper edge.
881    ///
882    /// # Errors
883    /// As [`Self::bin_probabilities_at`].
884    pub fn bin_arrival_slopes_at(
885        &self,
886        true_energy_ev: f64,
887        arrival_us: f64,
888        detector_time_edges_us: &[f64],
889    ) -> Result<Vec<f64>, ResolutionParseError> {
890        let (pulse, h) = self.at_arrival(true_energy_ev, arrival_us, detector_time_edges_us)?;
891        let density = |x: f64| {
892            if h == 0.0 {
893                pulse.density(x)
894            } else {
895                triangle_fold(pulse.alpha, h, x, |tau| [pulse.density(tau)])[0]
896            }
897        };
898        let densities: Vec<f64> = detector_time_edges_us
899            .iter()
900            .map(|edge| density(edge - arrival_us))
901            .collect();
902        Ok(densities.windows(2).map(|w| w[0] - w[1]).collect())
903    }
904
905    /// The derivatives of each of [`Self::bin_probabilities_at`] with
906    /// respect to `α`, `β`, `R` and the square of the triangle's FWHM `h`,
907    /// each evaluated at `true_energy_ev`: `[∂P/∂α, ∂P/∂β, ∂P/∂R, ∂P/∂h²]`,
908    /// one value per bin.  The probabilities are even in `h` and smooth in
909    /// `h²`, so `∂P/∂h²` is finite and generally not 0 at `h = 0`.
910    ///
911    /// # Errors
912    /// As [`Self::bin_probabilities_at`].
913    pub fn bin_pulse_slopes_at(
914        &self,
915        true_energy_ev: f64,
916        arrival_us: f64,
917        detector_time_edges_us: &[f64],
918    ) -> Result<[Vec<f64>; 4], ResolutionParseError> {
919        let (pulse, h) = self.at_arrival(true_energy_ev, arrival_us, detector_time_edges_us)?;
920        let slopes = |x: f64| {
921            if h == 0.0 {
922                let [a, b, c, d] = pulse.slopes(x);
923                [a, b, c, d / 12.0]
924            } else {
925                folded_slopes(&pulse, h, x)
926            }
927        };
928        Ok(bin_differences(detector_time_edges_us, arrival_us, slopes))
929    }
930
931    /// The derivatives of each of [`Self::bin_probabilities_at`] with
932    /// respect to the detector tail's `f` and `τ_D`, each per its unit:
933    /// `[∂P/∂f, ∂P/∂τ_D]`, one value per bin.
934    ///
935    /// # Errors
936    /// As [`Self::bin_probabilities_at`], and
937    /// [`ResolutionParseError::InvalidFormat`] for a pulse without a
938    /// detector tail.
939    pub fn bin_tail_slopes_at(
940        &self,
941        true_energy_ev: f64,
942        arrival_us: f64,
943        detector_time_edges_us: &[f64],
944    ) -> Result<[Vec<f64>; 2], ResolutionParseError> {
945        let (pulse, h) = self.at_arrival(true_energy_ev, arrival_us, detector_time_edges_us)?;
946        if pulse.tail.is_none() {
947            return Err(ResolutionParseError::InvalidFormat(
948                "the pulse has no detector tail".to_string(),
949            ));
950        }
951        let slopes = |x: f64| {
952            if h == 0.0 {
953                pulse.tail_slopes(x)
954            } else {
955                triangle_fold(pulse.alpha, h, x, |tau| pulse.tail_slopes(tau))
956            }
957        };
958        Ok(bin_differences(detector_time_edges_us, arrival_us, slopes))
959    }
960
961    fn at_arrival(
962        &self,
963        true_energy_ev: f64,
964        arrival_us: f64,
965        detector_time_edges_us: &[f64],
966    ) -> Result<(Recorded, f64), ResolutionParseError> {
967        let pulse = self.recorded_at(true_energy_ev)?;
968        if !arrival_us.is_finite() {
969            return Err(ResolutionParseError::InvalidFormat(format!(
970                "the nominal arrival must be finite, got {arrival_us} µs"
971            )));
972        }
973        if detector_time_edges_us.len() < 2
974            || detector_time_edges_us.iter().any(|x| !x.is_finite())
975            || detector_time_edges_us.windows(2).any(|w| w[0] >= w[1])
976        {
977            return Err(ResolutionParseError::InvalidFormat(
978                "detector time edges must contain at least two finite, strictly increasing values"
979                    .to_string(),
980            ));
981        }
982        Ok((pulse, self.triangle_fwhm_us()?))
983    }
984
985    fn validate_probe_energy(&self, energy_ev: f64) -> Result<(), ResolutionParseError> {
986        if !energy_ev.is_finite() || energy_ev <= 0.0 {
987            return Err(ResolutionParseError::InvalidFormat(format!(
988                "true energy must be positive and finite, got {energy_ev}"
989            )));
990        }
991        for (name, law) in [("alpha", &self.alpha), ("beta", &self.beta), ("R", &self.r)] {
992            if law.is_singular_at(energy_ev) {
993                return Err(ResolutionParseError::InvalidFormat(format!(
994                    "Ikeda–Carpenter {name}({energy_ev}) law is singular (an \
995                     InverseLambda denominator within ±{MIN_RATE} of zero, \
996                     or an ExpMilliEv κ in [−{MIN_RATE}, 0])"
997                )));
998            }
999        }
1000        let alpha = self.alpha.eval(energy_ev);
1001        let beta = self.beta.eval(energy_ev);
1002        let r = self.r.eval(energy_ev);
1003        if !alpha.is_finite() || alpha < MIN_RATE {
1004            return Err(ResolutionParseError::InvalidFormat(format!(
1005                "Ikeda–Carpenter alpha({energy_ev}) must be finite and at least {MIN_RATE} \
1006                 µs⁻¹, got {alpha}"
1007            )));
1008        }
1009        if !beta.is_finite() || beta < MIN_RATE {
1010            return Err(ResolutionParseError::InvalidFormat(format!(
1011                "Ikeda–Carpenter beta({energy_ev}) must be finite and at least {MIN_RATE} \
1012                 µs⁻¹, got {beta}"
1013            )));
1014        }
1015        if !r.is_finite() || !(0.0..=1.0).contains(&r) {
1016            return Err(ResolutionParseError::InvalidFormat(format!(
1017                "Ikeda–Carpenter R({energy_ev}) must be in [0, 1], got {r}"
1018            )));
1019        }
1020        Ok(())
1021    }
1022}
1023
1024/// Configuration of the energy / time grids used to synthesize the IC kernel
1025/// table. The energy grid spans the data range densely enough that interref
1026/// interpolation error is negligible.
1027#[derive(Debug, Clone)]
1028pub struct SynthesisGrid {
1029    /// Lowest reference energy (eV), > 0.
1030    pub e_min_ev: f64,
1031    /// Highest reference energy (eV), > `e_min_ev`.
1032    pub e_max_ev: f64,
1033    /// Number of log-spaced reference energies (≥ 2).
1034    pub n_energies: usize,
1035    /// Number of τ-samples spanning the prompt core of each kernel
1036    /// (≥ [`MIN_N_TAU`](crate::ikeda_carpenter) = 8). A long storage tail
1037    /// (β ≪ α with R > 0) grows the per-kernel sample count beyond `n_tau`;
1038    /// that count is capped at 8192 (`MAX_TAU_SAMPLES`), past which the
1039    /// τ-step widens — never below the resolution floor (prompt core at the
1040    /// `n_tau = 8` density, folds at ≥ 3 triangle samples per side / ≥ 1
1041    /// sample per burst σ): a combination that cannot be resolved within the
1042    /// cap is rejected by [`IkedaCarpenter::new`]. Active burst/channel folds
1043    /// add their ±(`GAUSS_REACH_SIGMAS`·σ + FWHM) margin samples on top of
1044    /// the cap.
1045    pub n_tau: usize,
1046}
1047
1048impl SynthesisGrid {
1049    /// A sensible default grid: `[e_min, e_max]` log-spaced over
1050    /// [`DEFAULT_N_ENERGIES`] points with [`DEFAULT_N_TAU`] τ-samples.
1051    #[must_use]
1052    pub fn new(e_min_ev: f64, e_max_ev: f64) -> Self {
1053        Self {
1054            e_min_ev,
1055            e_max_ev,
1056            n_energies: DEFAULT_N_ENERGIES,
1057            n_tau: DEFAULT_N_TAU,
1058        }
1059    }
1060}
1061
1062/// Analytical Ikeda–Carpenter resolution model.
1063///
1064/// Synthesizes a [`TabulatedResolution`] at construction and applies it through
1065/// the same broadening path as a Monte-Carlo file. Cloning is cheap (the
1066/// synthesized table is the only large field). Re-synthesize (construct anew)
1067/// when fitting changes the parameters.
1068#[derive(Debug, Clone)]
1069pub struct IkedaCarpenter {
1070    params: IkedaCarpenterParams,
1071    flight_path_m: f64,
1072    /// Shared: rebinding the flight path must not copy it.
1073    ref_energies: Arc<Vec<f64>>,
1074    n_tau: usize,
1075    tabulated: TabulatedResolution,
1076}
1077
1078impl IkedaCarpenter {
1079    /// Build the model, synthesizing its kernel table over `grid`.
1080    ///
1081    /// # Errors
1082    /// Returns [`ResolutionParseError::InvalidFormat`] for a non-positive
1083    /// flight path, a degenerate grid (`n_energies < 2`, `n_tau < 8`,
1084    /// `e_min ≤ 0`, `e_max ≤ e_min`), an `α(E)` or `β(E)` below 1e-9 µs⁻¹ at a
1085    /// reference energy, a parameter/grid
1086    /// combination whose τ-grid cannot resolve the prompt core and requested
1087    /// folds within the `MAX_TAU_SAMPLES` cap at some reference energy (see
1088    /// `tau_geometry` — remedy: larger `β`, `R = 0`, or a wider/disabled
1089    /// fold), a detector tail, or if the synthesized kernels fail
1090    /// [`TabulatedResolution::from_kernels`] validation.
1091    pub fn new(
1092        params: IkedaCarpenterParams,
1093        flight_path_m: f64,
1094        grid: &SynthesisGrid,
1095    ) -> Result<Self, ResolutionParseError> {
1096        if !flight_path_m.is_finite() || flight_path_m <= 0.0 {
1097            return Err(ResolutionParseError::InvalidFormat(format!(
1098                "Flight path must be a positive finite number, got {flight_path_m}"
1099            )));
1100        }
1101        if grid.n_energies < 2 {
1102            return Err(ResolutionParseError::InvalidFormat(format!(
1103                "n_energies must be >= 2, got {}",
1104                grid.n_energies
1105            )));
1106        }
1107        if grid.n_tau < MIN_N_TAU {
1108            return Err(ResolutionParseError::InvalidFormat(format!(
1109                "n_tau must be >= {MIN_N_TAU}, got {}",
1110                grid.n_tau
1111            )));
1112        }
1113        if !grid.e_min_ev.is_finite()
1114            || !grid.e_max_ev.is_finite()
1115            || grid.e_min_ev <= 0.0
1116            || grid.e_max_ev <= grid.e_min_ev
1117        {
1118            return Err(ResolutionParseError::InvalidFormat(format!(
1119                "Require finite 0 < e_min < e_max, got [{}, {}]",
1120                grid.e_min_ev, grid.e_max_ev
1121            )));
1122        }
1123        let ln_lo = grid.e_min_ev.ln();
1124        let ln_hi = grid.e_max_ev.ln();
1125        let denom = (grid.n_energies - 1) as f64;
1126        let ref_energies: Vec<f64> = (0..grid.n_energies)
1127            .map(|i| (ln_lo + (i as f64 / denom) * (ln_hi - ln_lo)).exp())
1128            .collect();
1129
1130        // Reject singular rate laws before the range checks: a near-zero
1131        // InverseLambda denominator is an undefined configuration, and eval's
1132        // numerical floor would otherwise convert it into a plausible huge
1133        // positive rate that the α > 0 / β > 0 checks below cannot distinguish
1134        // from genuine physics.
1135        for (name, law) in [("α", &params.alpha), ("β", &params.beta), ("R", &params.r)] {
1136            if let Some(&bad) = ref_energies.iter().find(|&&e| law.is_singular_at(e)) {
1137                return Err(ResolutionParseError::InvalidFormat(format!(
1138                    "Ikeda–Carpenter {name}(E) law is singular at E = {bad} eV \
1139                     (an InverseLambda denominator within \
1140                     ±{MIN_RATE} of zero, or an ExpMilliEv κ in [−{MIN_RATE}, 0])"
1141                )));
1142            }
1143        }
1144        if let Some(&bad) = ref_energies.iter().find(|&&e| {
1145            let a = params.alpha.eval(e);
1146            !a.is_finite() || a < MIN_RATE
1147        }) {
1148            return Err(ResolutionParseError::InvalidFormat(format!(
1149                "Ikeda–Carpenter α(E) must be at least {MIN_RATE} µs⁻¹, but α({bad}) = {} is not",
1150                params.alpha.eval(bad)
1151            )));
1152        }
1153        // β is a rate, so every synthesized reference energy must give a
1154        // positive finite value. Reject invalid laws instead of clamping them
1155        // into a different pulse.
1156        if let Some(&bad) = ref_energies.iter().find(|&&e| {
1157            let beta = params.beta.eval(e);
1158            !beta.is_finite() || beta < MIN_RATE
1159        }) {
1160            return Err(ResolutionParseError::InvalidFormat(format!(
1161                "Ikeda–Carpenter β(E) must be at least {MIN_RATE} µs⁻¹, but β({bad}) = {} is not",
1162                params.beta.eval(bad)
1163            )));
1164        }
1165        // Reject storage-fraction laws that fall outside [0, 1] (synthesis clamps
1166        // R, masking a mis-specified law); a physical mixing fraction is in [0,1].
1167        if let Some(&bad) = ref_energies.iter().find(|&&e| {
1168            let r = params.r.eval(e);
1169            !r.is_finite() || !(0.0..=1.0).contains(&r)
1170        }) {
1171            return Err(ResolutionParseError::InvalidFormat(format!(
1172                "Ikeda–Carpenter R(E) must be in [0, 1], but R({bad}) = {} is not",
1173                params.r.eval(bad)
1174            )));
1175        }
1176        // Reject invalid optional instrument-convolution widths up front; synthesis
1177        // otherwise masks a negative width via `.abs()` and silently swallows a NaN.
1178        for (name, v) in [
1179            ("burst_sigma_us", params.burst_sigma_us),
1180            ("channel_fwhm_us", params.channel_fwhm_us),
1181        ] {
1182            if let Some(x) = v
1183                && (!x.is_finite() || x < 0.0)
1184            {
1185                return Err(ResolutionParseError::InvalidFormat(format!(
1186                    "Ikeda–Carpenter {name} must be finite and >= 0, got {x}"
1187                )));
1188            }
1189        }
1190        if params.detector_tail.is_some() {
1191            return Err(ResolutionParseError::InvalidFormat(
1192                "a detector tail is not supported in the kernel table".to_string(),
1193            ));
1194        }
1195
1196        // Synthesis is fallible: a kernel whose τ-grid cannot resolve the
1197        // requested physics within MAX_TAU_SAMPLES (long slow tail vs a fine
1198        // fold / fast prompt core) errs loudly here instead of silently
1199        // degrading — see `tau_geometry`.
1200        let kernels: Vec<(Vec<f64>, Vec<f64>)> = ref_energies
1201            .iter()
1202            .map(|&e| synth_kernel(&params, grid.n_tau, e))
1203            .collect::<Result<_, _>>()?;
1204
1205        let tabulated =
1206            TabulatedResolution::from_kernels(ref_energies.clone(), kernels, flight_path_m)?;
1207
1208        Ok(Self {
1209            params,
1210            flight_path_m,
1211            ref_energies: Arc::new(ref_energies),
1212            n_tau: grid.n_tau,
1213            tabulated,
1214        })
1215    }
1216
1217    /// The synthesized tabulated kernel set (the broadening engine).
1218    #[must_use]
1219    pub fn tabulated(&self) -> &TabulatedResolution {
1220        &self.tabulated
1221    }
1222
1223    /// The IC parameters.
1224    #[must_use]
1225    pub fn params(&self) -> &IkedaCarpenterParams {
1226        &self.params
1227    }
1228
1229    /// Flight-path length (m).
1230    #[must_use]
1231    pub fn flight_path_m(&self) -> f64 {
1232        self.flight_path_m
1233    }
1234
1235    /// The same pulse read against a different flight path.
1236    ///
1237    /// The synthesized kernels are emission-time distributions built from
1238    /// α(E), β(E) and R(E) — no flight path appears in the synthesis. The
1239    /// flight path enters only the TOF↔energy map and the nominal arrival
1240    /// time, so rebinding it is exact and does not resynthesize the table.
1241    ///
1242    /// # Errors
1243    /// Returns [`ResolutionParseError::InvalidFormat`] if `flight_path_m` is
1244    /// not positive and finite.
1245    pub fn with_flight_path(&self, flight_path_m: f64) -> Result<Self, ResolutionParseError> {
1246        Ok(Self {
1247            params: self.params.clone(),
1248            flight_path_m,
1249            ref_energies: Arc::clone(&self.ref_energies),
1250            n_tau: self.n_tau,
1251            tabulated: self.tabulated.with_flight_path(flight_path_m)?,
1252        })
1253    }
1254
1255    /// Reference energies (eV, ascending) the table was synthesized on.
1256    #[must_use]
1257    pub fn ref_energies(&self) -> &[f64] {
1258        &self.ref_energies
1259    }
1260
1261    /// The pulse as the counts path reads it, over the energies the table was
1262    /// synthesized on.
1263    #[must_use]
1264    pub fn detector_pulse(&self) -> DetectorPulse {
1265        DetectorPulse {
1266            params: self.params.clone(),
1267            energy_span_ev: (
1268                self.ref_energies[0],
1269                self.ref_energies[self.ref_energies.len() - 1],
1270            ),
1271            n_tau: self.n_tau,
1272        }
1273    }
1274
1275    /// Evaluate the (burst/channel-folded) IC kernel at one energy.
1276    ///
1277    /// Returns ascending TOF-offsets (µs, 0 = pulse start) and peak-normalized
1278    /// weights (max = 1), matching the [`TabulatedResolution`] storage
1279    /// convention.
1280    ///
1281    /// # Errors
1282    /// Returns [`ResolutionParseError::InvalidFormat`] when the requested
1283    /// energy or an energy-dependent rate/fraction is non-physical, or when
1284    /// the τ-grid cannot resolve the prompt core and requested folds within
1285    /// `MAX_TAU_SAMPLES` at this energy. Construction validates every
1286    /// *reference* energy, but a probe outside `[e_min, e_max]` can still leave
1287    /// the physical or resolvable region.
1288    pub fn kernel_at(&self, energy_ev: f64) -> Result<(Vec<f64>, Vec<f64>), ResolutionParseError> {
1289        self.params.validate_probe_energy(energy_ev)?;
1290        synth_kernel(&self.params, self.n_tau, energy_ev)
1291    }
1292
1293    /// Evaluate the physical source pulse at one true neutron energy.
1294    ///
1295    /// Returns sampled moderator-delay coordinates in µs and peak-normalized
1296    /// densities. Unlike [`Self::kernel_at`], this method does not move the
1297    /// pulse mode to zero. With no symmetric proton/channel fold, the delay is
1298    /// causal and starts at zero. A symmetric fold may extend the sampled
1299    /// support below zero relative to its stated time origin.
1300    ///
1301    /// # Errors
1302    /// Returns [`ResolutionParseError::InvalidFormat`] if `energy_ev` is not a
1303    /// positive finite true energy, if an energy law is unphysical at that
1304    /// energy, or if the requested pulse cannot be resolved by the configured
1305    /// sampling limits.
1306    pub fn source_pulse_at(
1307        &self,
1308        energy_ev: f64,
1309    ) -> Result<(Vec<f64>, Vec<f64>), ResolutionParseError> {
1310        self.params.validate_probe_energy(energy_ev)?;
1311        synth_source_pulse(&self.params, self.n_tau, energy_ev)
1312    }
1313
1314    /// Probability that a neutron of known true energy is recorded in each
1315    /// supplied detector-time bin.
1316    ///
1317    /// `detector_time_edges_us` are the actual measured bin edges. The nominal
1318    /// arrival time is
1319    /// `timing_offset_us + TOF_FACTOR * flight_path_m / sqrt(true_energy_ev)`.
1320    /// `timing_offset_us` represents the shared clock/detector offset; it does
1321    /// not absorb or remove the moderator pulse's physical mode.
1322    ///
1323    /// The returned vector has one entry per adjacent edge pair and is not
1324    /// renormalized to the supplied window: bins that do not cover the full
1325    /// pulse correctly sum to less than one.
1326    ///
1327    /// Each probability is a difference of the analytical IC CDF, folded with
1328    /// the proton-pulse triangle when `channel_fwhm_us` is set.
1329    ///
1330    /// # Errors
1331    /// Returns [`ResolutionParseError::InvalidFormat`] unless the true energy
1332    /// is physical, the timing offset is finite, at least two finite bin
1333    /// edges are supplied in strictly increasing order, and the pulse has no
1334    /// Gaussian burst.
1335    pub fn detector_bin_probabilities(
1336        &self,
1337        true_energy_ev: f64,
1338        detector_time_edges_us: &[f64],
1339        timing_offset_us: f64,
1340    ) -> Result<Vec<f64>, ResolutionParseError> {
1341        if !timing_offset_us.is_finite() {
1342            return Err(ResolutionParseError::InvalidFormat(format!(
1343                "timing_offset_us must be finite, got {timing_offset_us}"
1344            )));
1345        }
1346        self.params.bin_probabilities_at(
1347            true_energy_ev,
1348            timing_offset_us + TOF_FACTOR * self.flight_path_m / true_energy_ev.sqrt(),
1349            detector_time_edges_us,
1350        )
1351    }
1352}
1353
1354/// An Ikeda–Carpenter pulse in detector time: its laws, the energies they hold
1355/// over, and the number of samples across its prompt core used to find its
1356/// rise.
1357#[derive(Debug, Clone)]
1358pub struct DetectorPulse {
1359    params: IkedaCarpenterParams,
1360    energy_span_ev: (f64, f64),
1361    n_tau: usize,
1362}
1363
1364impl DetectorPulse {
1365    /// The pulse with laws `params` over `energy_span_ev`, its rise found on
1366    /// `n_tau` samples across the prompt core.
1367    ///
1368    /// # Errors
1369    /// [`ResolutionParseError::InvalidFormat`] unless `0 < low < high` are
1370    /// finite, `n_tau` is at least 8, the triangle's FWHM is finite and 0 or
1371    /// more, the pulse has no Gaussian burst, a detector tail has its
1372    /// fraction within 0–1 and its decay from 1e-9 to 1e9 µs, and the
1373    /// laws are valid at both ends of the span: `α` and `β` finite and at
1374    /// least 1e-9 µs⁻¹, `R` within 0–1.
1375    pub fn new(
1376        params: IkedaCarpenterParams,
1377        energy_span_ev: (f64, f64),
1378        n_tau: usize,
1379    ) -> Result<Self, ResolutionParseError> {
1380        params.triangle_fwhm_us()?;
1381        params.tail_rate()?;
1382        let (low, high) = energy_span_ev;
1383        if !(low.is_finite() && high.is_finite() && 0.0 < low && low < high) {
1384            return Err(ResolutionParseError::InvalidFormat(format!(
1385                "the energy span must satisfy 0 < low < high, got {energy_span_ev:?}"
1386            )));
1387        }
1388        params.validate_probe_energy(low)?;
1389        params.validate_probe_energy(high)?;
1390        if n_tau < MIN_N_TAU {
1391            return Err(ResolutionParseError::InvalidFormat(format!(
1392                "n_tau must be >= {MIN_N_TAU}, got {n_tau}"
1393            )));
1394        }
1395        Ok(Self {
1396            params,
1397            energy_span_ev,
1398            n_tau,
1399        })
1400    }
1401
1402    /// The pulse's laws.
1403    #[must_use]
1404    pub fn params(&self) -> &IkedaCarpenterParams {
1405        &self.params
1406    }
1407
1408    /// `(low, high)`, the energies in eV the laws hold over.
1409    #[must_use]
1410    pub fn energy_span_ev(&self) -> (f64, f64) {
1411        self.energy_span_ev
1412    }
1413
1414    /// The samples across the prompt core used to find the pulse's rise.
1415    #[must_use]
1416    pub fn n_tau(&self) -> usize {
1417        self.n_tau
1418    }
1419
1420    /// The time in µs from the first sample of the pulse at `energy_ev` to
1421    /// its peak.
1422    ///
1423    /// # Errors
1424    /// [`ResolutionParseError::InvalidFormat`] when `energy_ev` is not
1425    /// positive and finite, a law is singular or out of range there, or the
1426    /// pulse has a Gaussian burst.
1427    pub fn rise_us(&self, energy_ev: f64) -> Result<f64, ResolutionParseError> {
1428        self.params.validate_probe_energy(energy_ev)?;
1429        self.params.triangle_fwhm_us()?;
1430        sampled_rise_us(&self.params, self.n_tau, energy_ev)
1431    }
1432}
1433
1434/// The chance of a later arrival below which an Ikeda–Carpenter pulse's
1435/// tail is treated as ended.
1436pub const NEGLIGIBLE_ARRIVAL_PROBABILITY: f64 = 1e-7;
1437
1438fn tail_delay(pulse: &Recorded) -> f64 {
1439    let later = |tau: f64| 1.0 - pulse.cdf(tau);
1440    let late = pulse.delayed().map_or(f64::INFINITY, |(_, rate)| rate);
1441    let mut high = 1.0 / pulse.alpha.min(pulse.beta).min(late).max(MIN_RATE);
1442    while later(high) > NEGLIGIBLE_ARRIVAL_PROBABILITY {
1443        high *= 2.0;
1444    }
1445    let mut low = 0.0;
1446    while high - low > f64::EPSILON * high {
1447        let middle = 0.5 * (low + high);
1448        if later(middle) > NEGLIGIBLE_ARRIVAL_PROBABILITY {
1449            low = middle;
1450        } else {
1451            high = middle;
1452        }
1453    }
1454    high
1455}
1456
1457fn requested_step(params: &IkedaCarpenterParams, n_tau: usize, alpha: f64) -> (f64, f64, String) {
1458    let fast_reach = FAST_REACH_E_FOLDS / alpha;
1459    let mut dtau_req = fast_reach / (n_tau as f64 - 1.0);
1460    let mut floor = fast_reach / (MIN_N_TAU as f64 - 1.0);
1461    let mut fold_desc = String::new();
1462    if let Some(fwhm) = params.channel_fwhm_us
1463        && fwhm > 0.0
1464    {
1465        let tri_floor = fwhm / TRI_MIN_SAMPLES_PER_SIDE;
1466        dtau_req = dtau_req.min(tri_floor);
1467        floor = floor.min(tri_floor);
1468        fold_desc.push_str(&format!(", channel triangle FWHM = {fwhm} µs"));
1469    }
1470    if let Some(sigma) = params.burst_sigma_us
1471        && sigma > 0.0
1472    {
1473        dtau_req = dtau_req.min(sigma);
1474        floor = floor.min(sigma);
1475        fold_desc.push_str(&format!(", burst σ = {sigma} µs"));
1476    }
1477
1478    (dtau_req, floor, fold_desc)
1479}
1480
1481/// τ-grid geometry for one kernel: `(dtau, tau_max, margin)`, or a
1482/// descriptive error when no exact sampled representation fits the cap.
1483///
1484/// The step is anchored to the PROMPT core — `n_tau` samples across the fast
1485/// Gamma(3) pulse (`fast_reach / (n_tau − 1)`) — and REFINED to resolve any
1486/// requested instrument fold (triangle: ≥ [`TRI_MIN_SAMPLES_PER_SIDE`]
1487/// samples per side, i.e. `dtau ≤ FWHM/TRI_MIN_SAMPLES_PER_SIDE`; Gaussian burst: `dtau ≤ σ`, i.e.
1488/// ≥ [`GAUSS_REACH_SIGMAS`] samples per ±`GAUSS_REACH_SIGMAS`·σ side). A longer storage tail
1489/// (β ≪ α, R > 0) extends the SAMPLE COUNT (`j_hi ∝ tau_max/dtau`) instead
1490/// of the step; [`MAX_TAU_SAMPLES`] bounds that count by widening the step —
1491/// but never past the resolution FLOOR (`fast_reach / (MIN_N_TAU − 1)` for
1492/// the prompt core, the fold minima above for folds). A combination whose
1493/// floor cannot be met within the cap has no faithful sampled representation
1494/// here, so it is rejected loudly: a capped step above the fold width would
1495/// degenerate the sampled triangle to an exact delta `[0,1,0]` (the fold
1496/// silently vanishes), and a capped step above the prompt scale steps OVER
1497/// the prompt pulse entirely (probe: α = 250, β = 0.02, R = 0.1 loses the
1498/// prompt's 0.9 weight share).
1499///
1500/// Equals `max(fast_reach/(n_tau−1), tau_max/(MAX_TAU_SAMPLES−1))` whenever
1501/// no fold is finer than the prompt design step and the capped step stays at
1502/// or below the floor.
1503fn tau_geometry(
1504    params: &IkedaCarpenterParams,
1505    n_tau: usize,
1506    alpha: f64,
1507    beta: f64,
1508    r: f64,
1509) -> Result<(f64, f64, f64), String> {
1510    let tau_max = tau_reach(alpha, beta, r);
1511    let (dtau_req, floor, fold_desc) = requested_step(params, n_tau, alpha);
1512
1513    let capped_step = tau_max / (MAX_TAU_SAMPLES as f64 - 1.0);
1514    if capped_step > floor {
1515        return Err(format!(
1516            "the {MAX_TAU_SAMPLES}-sample τ-grid cap cannot resolve the requested physics: \
1517             the pulse spans τ_max = {tau_max:.3} µs (α = {alpha:.4} µs⁻¹, β = {beta:.4} µs⁻¹, \
1518             R = {r:.3}{fold_desc}), forcing a τ-step of {capped_step:.4} µs — above the \
1519             finest-feature resolution floor of {floor:.4} µs. Increase β (shorter storage \
1520             tail), set R = 0 (drop the storage term), or widen/disable the burst/channel fold"
1521        ));
1522    }
1523    Ok((dtau_req.max(capped_step), tau_max, margin_of(params)))
1524}
1525
1526fn tau_reach(alpha: f64, beta: f64, r: f64) -> f64 {
1527    let fast_reach = FAST_REACH_E_FOLDS / alpha;
1528    if r > R_NEGLIGIBLE {
1529        fast_reach.max(SLOW_REACH_E_FOLDS / beta)
1530    } else {
1531        fast_reach
1532    }
1533}
1534
1535/// Symmetric τ-grid margin for the burst/channel folds:
1536/// ±([`GAUSS_REACH_SIGMAS`]·σ + FWHM), the folds' full reach. These samples
1537/// come ON TOP of [`MAX_TAU_SAMPLES`] (the cap governs the pulse body only).
1538fn margin_of(params: &IkedaCarpenterParams) -> f64 {
1539    params
1540        .burst_sigma_us
1541        .map_or(0.0, |s| GAUSS_REACH_SIGMAS * s)
1542        + params.channel_fwhm_us.unwrap_or(0.0)
1543}
1544
1545/// Synthesize one `(offsets, weights)` kernel for `energy_ev` from the IC
1546/// parameters: sample `I(τ)`, fold in burst + channel, trim negligible tails,
1547/// peak-normalize.
1548///
1549/// Offsets are on the emission clock: `0` is when the pulse begins, which is
1550/// where the Ikeda–Carpenter function puts it. A loaded SAMMY UDR file is
1551/// anchored differently and never passes through here.
1552///
1553/// # Errors
1554/// [`ResolutionParseError::InvalidFormat`] when [`tau_geometry`] cannot
1555/// resolve the prompt core and requested folds within [`MAX_TAU_SAMPLES`].
1556fn synth_kernel(
1557    params: &IkedaCarpenterParams,
1558    n_tau: usize,
1559    energy_ev: f64,
1560) -> Result<(Vec<f64>, Vec<f64>), ResolutionParseError> {
1561    synth_source_pulse(params, n_tau, energy_ev)
1562}
1563
1564/// Synthesize one physical-time source pulse without moving its mode.
1565fn synth_source_pulse_density(
1566    params: &IkedaCarpenterParams,
1567    n_tau: usize,
1568    energy_ev: f64,
1569) -> Result<(Vec<f64>, Vec<f64>), ResolutionParseError> {
1570    let alpha = params.alpha.eval(energy_ev).max(MIN_RATE);
1571    let beta = params.beta.eval(energy_ev).max(MIN_RATE);
1572    let r = params.r.eval(energy_ev).clamp(0.0, 1.0);
1573
1574    let geometry = tau_geometry(params, n_tau, alpha, beta, r).map_err(|msg| {
1575        ResolutionParseError::InvalidFormat(format!(
1576            "Ikeda–Carpenter kernel at E = {energy_ev} eV: {msg}"
1577        ))
1578    })?;
1579    sampled_density(params, (alpha, beta, r), geometry, energy_ev)
1580}
1581
1582fn sampled_rise_us(
1583    params: &IkedaCarpenterParams,
1584    n_tau: usize,
1585    energy_ev: f64,
1586) -> Result<f64, ResolutionParseError> {
1587    let alpha = params.alpha.eval(energy_ev).max(MIN_RATE);
1588    let beta = params.beta.eval(energy_ev).max(MIN_RATE);
1589    let r = params.r.eval(energy_ev).clamp(0.0, 1.0);
1590    let fast_reach = FAST_REACH_E_FOLDS / alpha;
1591    let margin = margin_of(params);
1592    let (dtau_req, _, _) = requested_step(params, n_tau, alpha);
1593    let dtau = dtau_req.max((fast_reach + 2.0 * margin) / (MAX_TAU_SAMPLES as f64 - 1.0));
1594    let (times, densities) = sampled_density(
1595        params,
1596        (alpha, beta, r),
1597        (dtau, fast_reach, margin),
1598        energy_ev,
1599    )?;
1600    Ok(times[argmax(&densities)] - times[0])
1601}
1602
1603fn sampled_density(
1604    params: &IkedaCarpenterParams,
1605    (alpha, beta, r): (f64, f64, f64),
1606    (dtau, tau_max, margin): (f64, f64, f64),
1607    energy_ev: f64,
1608) -> Result<(Vec<f64>, Vec<f64>), ResolutionParseError> {
1609    // Extend the grid to slightly negative τ so a symmetric burst/channel can
1610    // spread the leading edge correctly (the moderator pulse itself is 0 there).
1611    let j_lo: isize = -((margin / dtau).ceil() as isize);
1612    let j_hi: isize = ((tau_max + margin) / dtau).ceil() as isize;
1613
1614    let taus: Vec<f64> = (j_lo..=j_hi).map(|j| j as f64 * dtau).collect();
1615    let mut weights: Vec<f64> = taus.iter().map(|&t| ic_pulse(alpha, beta, r, t)).collect();
1616
1617    let sampled_area = dtau
1618        * (0.5 * weights[0]
1619            + weights[1..weights.len() - 1].iter().sum::<f64>()
1620            + 0.5 * weights[weights.len() - 1]);
1621    if !sampled_area.is_finite() || sampled_area <= 0.0 {
1622        return Err(ResolutionParseError::InvalidFormat(format!(
1623            "Ikeda–Carpenter pulse at E = {energy_ev} eV has zero sampled area"
1624        )));
1625    }
1626
1627    if let Some(sigma) = params.burst_sigma_us
1628        && sigma > 0.0
1629    {
1630        weights = convolve_same(&weights, &gaussian_kernel(dtau, sigma));
1631    }
1632    if let Some(fwhm) = params.channel_fwhm_us
1633        && fwhm > 0.0
1634    {
1635        weights = convolve_same(&weights, &triangle_kernel(dtau, fwhm));
1636    }
1637
1638    let peak_idx = argmax(&weights);
1639    let peak_val = weights[peak_idx].max(f64::MIN_POSITIVE);
1640
1641    // Trim tails below TRIM_REL of peak, keeping one guard sample each side so
1642    // the convolution's neighbor-difference trapezoid widths stay defined.
1643    let thresh = TRIM_REL * peak_val;
1644    let lo = weights
1645        .iter()
1646        .position(|&w| w > thresh)
1647        .map_or(0, |i| i.saturating_sub(1));
1648    let hi = weights
1649        .iter()
1650        .rposition(|&w| w > thresh)
1651        .map_or(weights.len() - 1, |i| (i + 1).min(weights.len() - 1));
1652
1653    let offsets: Vec<f64> = (lo..=hi).map(|j| taus[j]).collect();
1654    let densities: Vec<f64> = (lo..=hi).map(|j| weights[j]).collect();
1655    Ok((offsets, densities))
1656}
1657
1658/// Synthesize the public peak-normalized source-pulse representation.
1659fn synth_source_pulse(
1660    params: &IkedaCarpenterParams,
1661    n_tau: usize,
1662    energy_ev: f64,
1663) -> Result<(Vec<f64>, Vec<f64>), ResolutionParseError> {
1664    let (offsets, densities) = synth_source_pulse_density(params, n_tau, energy_ev)?;
1665    let peak = densities
1666        .iter()
1667        .copied()
1668        .fold(0.0_f64, f64::max)
1669        .max(f64::MIN_POSITIVE);
1670    let weights = densities.into_iter().map(|value| value / peak).collect();
1671    Ok((offsets, weights))
1672}
1673
1674/// Index of the maximum element (first on ties). Slice is non-empty by
1675/// construction in [`synth_kernel`].
1676fn argmax(xs: &[f64]) -> usize {
1677    let mut best = 0;
1678    let mut best_v = xs[0];
1679    for (i, &x) in xs.iter().enumerate().skip(1) {
1680        if x > best_v {
1681            best_v = x;
1682            best = i;
1683        }
1684    }
1685    best
1686}
1687
1688/// Symmetric, unit-sum Gaussian kernel sampled on a `dtau`-spaced grid out to
1689/// ±[`GAUSS_REACH_SIGMAS`]·σ.
1690fn gaussian_kernel(dtau: f64, sigma: f64) -> Vec<f64> {
1691    let half = ((GAUSS_REACH_SIGMAS * sigma / dtau).ceil() as isize).max(1);
1692    let mut k: Vec<f64> = (-half..=half)
1693        .map(|j| {
1694            let t = j as f64 * dtau / sigma;
1695            (-0.5 * t * t).exp()
1696        })
1697        .collect();
1698    normalize_sum(&mut k);
1699    k
1700}
1701
1702/// Symmetric, unit-sum triangle kernel of FWHM `fwhm` (half-base = FWHM;
1703/// variance FWHM²/6) sampled on a `dtau`-spaced grid.
1704fn triangle_kernel(dtau: f64, fwhm: f64) -> Vec<f64> {
1705    let a = fwhm; // half-base equals FWHM for a symmetric triangle
1706    let half = ((a / dtau).ceil() as isize).max(1);
1707    let mut k: Vec<f64> = (-half..=half)
1708        .map(|j| (1.0 - (j as f64 * dtau).abs() / a).max(0.0))
1709        .collect();
1710    normalize_sum(&mut k);
1711    k
1712}
1713
1714fn normalize_sum(k: &mut [f64]) {
1715    let s: f64 = k.iter().sum();
1716    if s > 0.0 {
1717        for v in k.iter_mut() {
1718            *v /= s;
1719        }
1720    }
1721}
1722
1723/// Discrete convolution with a centered symmetric `kernel` (odd length),
1724/// returning an output the same length as `input` (zero-padded edges).
1725fn convolve_same(input: &[f64], kernel: &[f64]) -> Vec<f64> {
1726    let n = input.len();
1727    let kh = (kernel.len() / 2) as isize;
1728    let mut out = vec![0.0f64; n];
1729    for (i, o) in out.iter_mut().enumerate() {
1730        let mut acc = 0.0;
1731        for (kk, &kv) in kernel.iter().enumerate() {
1732            let src = i as isize + (kk as isize - kh);
1733            if src >= 0 && (src as usize) < n {
1734                acc += input[src as usize] * kv;
1735            }
1736        }
1737        *o = acc;
1738    }
1739    out
1740}
1741
1742#[cfg(test)]
1743mod tests {
1744    use super::*;
1745    use crate::resolution::{
1746        ResolutionFunction, apply_resolution, apply_resolution_with_plan, build_resolution_plan,
1747    };
1748    use std::sync::Arc;
1749
1750    /// Trapezoidal integral of `I(τ)` over a fine grid out to many decay times.
1751    fn pulse_area(alpha: f64, beta: f64, r: f64) -> f64 {
1752        let tau_max = (18.0 / alpha).max(if r > 0.0 { 18.0 / beta } else { 0.0 });
1753        let n = 200_000;
1754        let dt = tau_max / n as f64;
1755        let mut area = 0.0;
1756        for i in 0..n {
1757            let t0 = i as f64 * dt;
1758            let t1 = (i + 1) as f64 * dt;
1759            area += 0.5 * (ic_pulse(alpha, beta, r, t0) + ic_pulse(alpha, beta, r, t1)) * dt;
1760        }
1761        area
1762    }
1763
1764    fn pulse_mean(alpha: f64, beta: f64, r: f64) -> f64 {
1765        let tau_max = (24.0 / alpha).max(if r > 0.0 { 24.0 / beta } else { 0.0 });
1766        let n = 400_000;
1767        let dt = tau_max / n as f64;
1768        let mut m = 0.0;
1769        for i in 0..n {
1770            let t = (i as f64 + 0.5) * dt;
1771            m += t * ic_pulse(alpha, beta, r, t) * dt;
1772        }
1773        m
1774    }
1775
1776    #[test]
1777    fn pulse_is_unit_area() {
1778        for &(a, b, r) in &[
1779            (0.5, 0.05, 0.0),
1780            (1.0, 0.1, 0.3),
1781            (2.0, 0.2, 0.6),
1782            (0.8, 0.5, 0.9),
1783        ] {
1784            let area = pulse_area(a, b, r);
1785            assert!(
1786                (area - 1.0).abs() < 1e-3,
1787                "area for (α={a},β={b},R={r}) = {area}, expected 1"
1788            );
1789        }
1790    }
1791
1792    #[test]
1793    fn pulse_mean_matches_formula() {
1794        // ⟨τ⟩ = 3/α + R/β
1795        for &(a, b, r) in &[(1.0, 0.1, 0.0), (1.0, 0.1, 0.4), (2.0, 0.25, 0.7)] {
1796            let want = 3.0 / a + r / b;
1797            let got = pulse_mean(a, b, r);
1798            assert!(
1799                (got - want).abs() / want < 2e-3,
1800                "mean (α={a},β={b},R={r}) = {got}, expected {want}"
1801            );
1802        }
1803    }
1804
1805    #[test]
1806    fn pulse_mode_is_two_over_alpha_for_pure_fast() {
1807        // r=0 ⇒ Gamma(3,α): mode at τ=2/α.
1808        let alpha = 1.3;
1809        let mode = 2.0 / alpha;
1810        let here = ic_pulse(alpha, 0.1, 0.0, mode);
1811        for d in [-0.3, -0.1, 0.1, 0.3] {
1812            assert!(ic_pulse(alpha, 0.1, 0.0, mode + d) <= here + 1e-12);
1813        }
1814    }
1815
1816    #[test]
1817    fn pulse_alpha_equals_beta_is_finite_gamma4() {
1818        // α=β limit: slow term → α⁴τ³/6·e^{−ατ} (Gamma(4)). r=1 isolates it.
1819        let a = 1.0;
1820        let tau = 2.5;
1821        let got = ic_pulse(a, a, 1.0, tau);
1822        let want = a.powi(4) * tau.powi(3) / 6.0 * (-a * tau).exp();
1823        assert!(got.is_finite());
1824        assert!(
1825            (got - want).abs() < 1e-9,
1826            "α=β pulse {got} != Gamma(4) {want}"
1827        );
1828        // Near-degenerate (β just below α) must also be finite and close.
1829        let near = ic_pulse(a, a - 1e-9, 1.0, tau);
1830        assert!(near.is_finite() && (near - want).abs() < 1e-6);
1831    }
1832
1833    #[test]
1834    fn pulse_is_finite_for_beta_much_greater_than_alpha() {
1835        // old e^{−βτ}·h(u) form factored an e^{|u|} that overflowed → 0·∞ = NaN).
1836        for &tau in &[0.0, 1.0, 50.0, 400.0, 1000.0] {
1837            let v = ic_pulse(0.05, 4.0, 0.5, tau);
1838            assert!(
1839                v.is_finite() && v >= 0.0,
1840                "ic_pulse(0.05,4,0.5,{tau}) = {v}"
1841            );
1842        }
1843        // The synthesized kernel must contain no non-finite entries.
1844        let p = IkedaCarpenterParams {
1845            alpha: EnergyLaw::Const(0.05),
1846            beta: EnergyLaw::Const(4.0),
1847            r: EnergyLaw::Const(0.5),
1848            burst_sigma_us: None,
1849            channel_fwhm_us: None,
1850            detector_tail: None,
1851        };
1852        let (offs, wts) = synth_kernel(&p, 600, 1.0).unwrap();
1853        assert!(offs.iter().chain(wts.iter()).all(|v| v.is_finite()));
1854    }
1855
1856    #[test]
1857    fn pulse_is_nonnegative_and_zero_before_t0() {
1858        assert_eq!(ic_pulse(1.0, 0.1, 0.5, -0.5), 0.0);
1859        for i in 0..200 {
1860            let t = i as f64 * 0.1;
1861            assert!(ic_pulse(1.0, 0.1, 0.5, t) >= 0.0);
1862        }
1863    }
1864
1865    #[test]
1866    fn energy_law_eval() {
1867        assert_eq!(EnergyLaw::Const(3.0).eval(50.0), 3.0);
1868        let s = EnergyLaw::SqrtE { a0: 0.2, a1: 0.1 };
1869        assert!((s.eval(100.0) - (0.2 * 10.0 + 0.1)).abs() < 1e-12);
1870        let power = |exponent| EnergyLaw::PowerE {
1871            a0: 0.2,
1872            a1: 0.1,
1873            exponent,
1874        };
1875        assert!((power(0.25).eval(16.0) - (0.2 * 2.0 + 0.1)).abs() < 1e-12);
1876        for energy in [0.0, 0.5, 7.3, 200.0] {
1877            assert_eq!(power(0.5).eval(energy), s.eval(energy));
1878        }
1879        // InverseLambda: α grows with E (λ shrinks).
1880        let il = EnergyLaw::InverseLambda { a0: 0.1, a1: 0.5 };
1881        assert!(il.eval(200.0) > il.eval(5.0));
1882        // R = exp(−E_meV/κ) → ~0 at eV-scale energies, ~1 at sub-meV.
1883        let rr = EnergyLaw::ExpMilliEv { kappa: 25.0 };
1884        assert!(rr.eval(10.0) < 1e-6); // 10 eV
1885        assert!(rr.eval(0.001) > 0.9); // 1 meV
1886    }
1887
1888    /// The synthesized table and the model that produced it place the pulse at
1889    /// the same instant.
1890    ///
1891    /// Both are evaluated on the detector clock for the same `timing_offset_us`,
1892    /// so their mean arrival and their shape must agree.
1893    #[test]
1894    fn synthesized_table_agrees_with_the_model_it_came_from() {
1895        let model = IkedaCarpenter::new(
1896            IkedaCarpenterParams {
1897                alpha: EnergyLaw::SqrtE { a0: 0.35, a1: 0.05 },
1898                beta: EnergyLaw::Const(0.25),
1899                r: EnergyLaw::Const(0.15),
1900                burst_sigma_us: None,
1901                channel_fwhm_us: None,
1902                detector_tail: None,
1903            },
1904            25.0,
1905            &SynthesisGrid {
1906                e_min_ev: 1.0,
1907                e_max_ev: 100.0,
1908                n_energies: 16,
1909                n_tau: 512,
1910            },
1911        )
1912        .expect("valid IC");
1913        let table = model.tabulated();
1914
1915        // Between reference energies, so the width blend is exercised: it
1916        // scales offsets about 0, which is the emission instant.
1917        for energy in [3.7_f64, 17.3, 55.0] {
1918            let tof = TOF_FACTOR * 25.0 / energy.sqrt();
1919            let edges: Vec<f64> = (0..=3000).map(|i| tof - 5.0 + i as f64 * 0.01).collect();
1920            let mean = |p: &[f64]| -> f64 {
1921                let mass: f64 = p.iter().sum();
1922                p.iter()
1923                    .enumerate()
1924                    .map(|(i, w)| w * 0.5 * (edges[i] + edges[i + 1]))
1925                    .sum::<f64>()
1926                    / mass
1927            };
1928            let from_model = model
1929                .detector_bin_probabilities(energy, &edges, 0.0)
1930                .expect("model evaluates");
1931            let from_table = table
1932                .detector_bin_probabilities(energy, &edges, 0.0)
1933                .expect("table evaluates");
1934            let peak = from_model.iter().copied().fold(0.0_f64, f64::max);
1935            let shape = from_model
1936                .iter()
1937                .zip(&from_table)
1938                .map(|(a, b)| (a - b).abs())
1939                .fold(0.0_f64, f64::max);
1940            assert!(
1941                shape < 0.01 * peak,
1942                "E={energy}: table differs from the analytic pulse by {:.2}% of peak",
1943                100.0 * shape / peak
1944            );
1945            let gap = mean(&from_model) - mean(&from_table);
1946            assert!(
1947                gap.abs() < 0.01,
1948                "E={energy}: model puts the pulse at {:.4} µs, its own table at \
1949                 {:.4} µs ({gap:+.4} µs apart)",
1950                mean(&from_model),
1951                mean(&from_table)
1952            );
1953        }
1954    }
1955
1956    #[test]
1957    fn kernel_tail_points_to_positive_offset() {
1958        // Asymmetry: longer/heavier tail toward +offset (later TOF, lower E).
1959        let p = IkedaCarpenterParams::constant(1.0, 0.1, 0.2);
1960        let (offsets, weights) = synth_kernel(&p, 600, 10.0).unwrap();
1961        let max_pos = offsets.iter().cloned().fold(f64::MIN, f64::max);
1962        let min_neg = offsets.iter().cloned().fold(f64::MAX, f64::min);
1963        assert!(
1964            max_pos > min_neg.abs(),
1965            "expected longer +offset tail: +{max_pos} vs −{}",
1966            min_neg.abs()
1967        );
1968        let pos_w: f64 = offsets
1969            .iter()
1970            .zip(&weights)
1971            .filter(|(o, _)| **o > 0.0)
1972            .map(|(_, w)| *w)
1973            .sum();
1974        let neg_w: f64 = offsets
1975            .iter()
1976            .zip(&weights)
1977            .filter(|(o, _)| **o < 0.0)
1978            .map(|(_, w)| *w)
1979            .sum();
1980        assert!(pos_w > neg_w, "expected more weight at +offset");
1981    }
1982
1983    #[test]
1984    fn higher_energy_gives_narrower_kernel() {
1985        // α(E) ∝ √E ⇒ prompt width 1/α shrinks with E ⇒ smaller TOF support.
1986        let p = IkedaCarpenterParams {
1987            alpha: EnergyLaw::SqrtE { a0: 0.3, a1: 0.0 },
1988            beta: EnergyLaw::Const(0.1),
1989            r: EnergyLaw::Const(0.0),
1990            burst_sigma_us: None,
1991            channel_fwhm_us: None,
1992            detector_tail: None,
1993        };
1994        let support = |e: f64| {
1995            let (o, _) = synth_kernel(&p, 600, e).unwrap();
1996            o.iter().cloned().fold(f64::MIN, f64::max) - o.iter().cloned().fold(f64::MAX, f64::min)
1997        };
1998        assert!(support(100.0) < support(5.0));
1999    }
2000
2001    #[test]
2002    fn synthesize_builds_valid_ascending_table() {
2003        let p = IkedaCarpenterParams::constant(1.0, 0.1, 0.2);
2004        let grid = SynthesisGrid {
2005            e_min_ev: 0.5e-3,
2006            e_max_ev: 1000.0,
2007            n_energies: 32,
2008            n_tau: 400,
2009        };
2010        let ic = IkedaCarpenter::new(p, 25.0, &grid).expect("synthesis");
2011        assert_eq!(ic.ref_energies().len(), 32);
2012        assert_eq!(ic.tabulated().ref_energies().len(), 32);
2013        for w in ic.ref_energies().windows(2) {
2014            assert!(w[1] > w[0]);
2015        }
2016    }
2017
2018    #[test]
2019    fn rejects_bad_config() {
2020        let p = IkedaCarpenterParams::constant(1.0, 0.1, 0.2);
2021        let bad = SynthesisGrid {
2022            e_min_ev: 1.0,
2023            e_max_ev: 0.5,
2024            n_energies: 16,
2025            n_tau: 100,
2026        };
2027        assert!(IkedaCarpenter::new(p.clone(), 25.0, &bad).is_err());
2028        assert!(IkedaCarpenter::new(p, -1.0, &SynthesisGrid::new(1.0, 10.0)).is_err());
2029        // A parameter law that yields α(E) ≤ 0 is rejected, not silently clamped.
2030        let neg_alpha = IkedaCarpenterParams {
2031            alpha: EnergyLaw::Const(-1.0),
2032            ..IkedaCarpenterParams::constant(1.0, 0.1, 0.0)
2033        };
2034        assert!(IkedaCarpenter::new(neg_alpha, 25.0, &SynthesisGrid::new(1.0, 100.0)).is_err());
2035        // Negative / non-finite burst or channel widths are rejected up front
2036        // (not `.abs()`-masked or NaN-swallowed during synthesis).
2037        for bad_width in [-1.0, f64::NAN, f64::INFINITY] {
2038            let neg_burst = IkedaCarpenterParams {
2039                burst_sigma_us: Some(bad_width),
2040                ..IkedaCarpenterParams::constant(1.0, 0.1, 0.0)
2041            };
2042            assert!(
2043                IkedaCarpenter::new(neg_burst, 25.0, &SynthesisGrid::new(1.0, 100.0)).is_err(),
2044                "burst_sigma_us={bad_width} should be rejected"
2045            );
2046            let neg_chan = IkedaCarpenterParams {
2047                channel_fwhm_us: Some(bad_width),
2048                ..IkedaCarpenterParams::constant(1.0, 0.1, 0.0)
2049            };
2050            assert!(
2051                IkedaCarpenter::new(neg_chan, 25.0, &SynthesisGrid::new(1.0, 100.0)).is_err(),
2052                "channel_fwhm_us={bad_width} should be rejected"
2053            );
2054        }
2055    }
2056
2057    #[test]
2058    fn broadens_constant_to_constant() {
2059        // An area-normalized kernel preserves a flat spectrum.
2060        let p = IkedaCarpenterParams::constant(1.0, 0.1, 0.3);
2061        let ic = IkedaCarpenter::new(p, 25.0, &SynthesisGrid::new(1.0, 200.0)).unwrap();
2062        let energies: Vec<f64> = (0..400).map(|i| 1.0 + i as f64 * 0.5).collect();
2063        let spectrum = vec![0.7f64; energies.len()];
2064        let res = ResolutionFunction::IkedaCarpenter(Arc::new(ic));
2065        let out = apply_resolution(&energies, &spectrum, &res).unwrap();
2066        // Interior points (away from grid edges where the kernel is clipped).
2067        for v in &out[40..energies.len() - 40] {
2068            assert!((v - 0.7).abs() < 1e-3, "flat broadening drifted: {v}");
2069        }
2070    }
2071
2072    #[test]
2073    fn ic_centering_shifts_broadened_symmetric_dip_with_alpha() {
2074        // The IC kernel anchors its MODE at offset 0, but the right-skewed pulse's
2075        // intensity centroid lags the mode by ~1/α in TOF (module docstring).
2076        // Broadening a symmetric-in-energy resonance therefore moves the dip
2077        // minimum off the nominal energy by an α-dependent amount. This guards the
2078        // documented bias (the loop-closure calibration tests cannot see it) and
2079        // pins it against a silent "fix" (e.g. re-centering on the centroid).
2080        const E0: f64 = 20.0;
2081        // Absorption-weighted centroid of the broadened dip — a robust position
2082        // estimator (the bare minimum is fragile under the wide low-α kernel).
2083        fn dip_centroid_energy(alpha: f64) -> f64 {
2084            // Constant-α kernel so the shape (hence the mode→mean lag) is uniform.
2085            let p = IkedaCarpenterParams::constant(alpha, 0.1, 0.0);
2086            let ic = IkedaCarpenter::new(p, 25.0, &SynthesisGrid::new(1.0, 200.0)).unwrap();
2087            let res = ResolutionFunction::IkedaCarpenter(Arc::new(ic));
2088            // Fine uniform grid; symmetric (in energy) Gaussian dip centered at E0.
2089            let energies: Vec<f64> = (0..4000).map(|i| 10.0 + i as f64 * 0.005).collect();
2090            let spectrum: Vec<f64> = energies
2091                .iter()
2092                .map(|&e| 1.0 - 0.8 * (-((e - E0) / 0.1).powi(2)).exp())
2093                .collect();
2094            let out = apply_resolution(&energies, &spectrum, &res).unwrap();
2095            let (mut num, mut den) = (0.0, 0.0);
2096            for (&e, &t) in energies.iter().zip(&out) {
2097                if (e - E0).abs() <= 2.0 {
2098                    let a = (1.0 - t).max(0.0); // absorption weight
2099                    num += e * a;
2100                    den += a;
2101                }
2102            }
2103            num / den
2104        }
2105        let signed_small_alpha = dip_centroid_energy(0.8) - E0;
2106        let signed_large_alpha = dip_centroid_energy(2.0) - E0;
2107        // The shift is toward LOWER apparent energy: the delayed-emission
2108        // tail gathers theory from earlier TOF (higher E), so the theory
2109        // dip at E0 surfaces at measured energies below E0. A positive
2110        // shift here means the kernel was applied time-mirrored.
2111        assert!(
2112            signed_small_alpha < 0.0 && signed_large_alpha < 0.0,
2113            "centering shift must be toward lower energy: \
2114             α=0.8 {signed_small_alpha:+e}, α=2.0 {signed_large_alpha:+e}"
2115        );
2116        let shift_small_alpha = signed_small_alpha.abs();
2117        let shift_large_alpha = signed_large_alpha.abs();
2118        // The bias is real (resolvable at the 1e-3 eV level)…
2119        assert!(
2120            shift_small_alpha > 1e-3,
2121            "centering shift vanished: {shift_small_alpha}"
2122        );
2123        // …and shrinks with increasing α (the ~1/α scaling of the mode→mean lag).
2124        assert!(
2125            shift_small_alpha > 1.3 * shift_large_alpha,
2126            "shift should scale ~1/α: α=0.8 {shift_small_alpha} vs α=2.0 {shift_large_alpha}"
2127        );
2128    }
2129
2130    #[test]
2131    fn plan_path_matches_direct_path() {
2132        let p = IkedaCarpenterParams::constant(1.2, 0.15, 0.25);
2133        let ic = IkedaCarpenter::new(p, 25.0, &SynthesisGrid::new(1.0, 200.0)).unwrap();
2134        let res = ResolutionFunction::IkedaCarpenter(Arc::new(ic));
2135        let energies: Vec<f64> = (0..300).map(|i| 1.0 + i as f64 * 0.6).collect();
2136        // A localized dip to exercise the convolution non-trivially.
2137        let spectrum: Vec<f64> = energies
2138            .iter()
2139            .map(|&e| if (e - 90.0).abs() < 5.0 { 0.2 } else { 1.0 })
2140            .collect();
2141        let direct = apply_resolution(&energies, &spectrum, &res).unwrap();
2142        let plan = build_resolution_plan(&energies, &res).unwrap();
2143        let planned =
2144            apply_resolution_with_plan(plan.as_ref(), &energies, &spectrum, &res).unwrap();
2145        assert_eq!(direct.len(), planned.len());
2146        for (a, b) in direct.iter().zip(&planned) {
2147            assert!((a - b).abs() < 1e-12, "plan vs direct mismatch: {a} vs {b}");
2148        }
2149    }
2150
2151    #[test]
2152    fn tau_step_anchors_to_prompt_core_not_storage_tail() {
2153        // Regression for the τ-grid fix: with a slow storage tail active
2154        // (β ≪ α, R > 0) the τ-step must stay anchored to the prompt core —
2155        // the old `tau_max/(n_tau−1)` step let the tail dilate dtau and
2156        // degenerate the 0.35 µs channel triangle toward a delta.
2157        let n_tau = 600;
2158        let alpha = 2.0; // fast_reach = 18/α = 9 µs
2159        let prompt_step = (18.0 / alpha) / (n_tau as f64 - 1.0);
2160
2161        let p = IkedaCarpenterParams {
2162            channel_fwhm_us: Some(0.35),
2163            ..IkedaCarpenterParams::constant(alpha, 0.25, 0.5)
2164        };
2165        let (offs, wts) = synth_kernel(&p, n_tau, 10.0).unwrap();
2166        let dtau = offs[1] - offs[0];
2167        assert!(
2168            (dtau - prompt_step).abs() < 1e-12,
2169            "uncapped step {dtau} != prompt-core step {prompt_step}"
2170        );
2171        assert!(
2172            dtau <= prompt_step + 1e-12,
2173            "prompt-core spacing {dtau} > fast_reach/(n_tau−1) = {prompt_step}"
2174        );
2175        // ≥ 3 nonzero triangle samples per side at this step.
2176        let tri = triangle_kernel(dtau, 0.35);
2177        let nonzero_per_side = tri.iter().take(tri.len() / 2).filter(|&&v| v > 0.0).count();
2178        assert!(
2179            nonzero_per_side >= 3,
2180            "triangle degenerated: {nonzero_per_side} nonzero samples per side"
2181        );
2182        // The tail is still reached: for β = 0.25 the slow tail crosses the
2183        // TRIM_REL = 1e-7 trim level near τ ≈ 63 µs (e^{−βτ}·slow-amplitude ÷
2184        // peak = 1e-7 at τ ≈ 62.6 µs), so the trimmed kernel must still span
2185        // well past 40 µs — a step anchored to τ_max instead of the prompt
2186        // core would pass a narrow-span check, but a grid that stops short of
2187        // the storage tail would not survive this one.
2188        let span = offs.last().unwrap() - offs.first().unwrap();
2189        let peak = wts.iter().cloned().fold(f64::MIN, f64::max);
2190        assert!((peak - 1.0).abs() < 1e-12, "weights not peak-normalized");
2191        assert!(span > 3.0 / alpha, "kernel span {span} lost the pulse body");
2192        assert!(
2193            span > 40.0,
2194            "kernel span {span} µs stops short of the β = 0.25 storage tail \
2195             (trim horizon ≈ 63 µs)"
2196        );
2197
2198        // (b) Extreme admitted tail (β = 0.02 ⇒ slow_reach = 800 µs): the
2199        // MAX_TAU_SAMPLES cap bites; the step widens to tau_max/(cap−1) but
2200        // must still resolve the 0.35 µs triangle with ≥ 3 samples per side
2201        // (the old tail-anchored step was 800/599 ≈ 1.34 µs — a delta).
2202        let p_ext = IkedaCarpenterParams {
2203            channel_fwhm_us: Some(0.35),
2204            ..IkedaCarpenterParams::constant(alpha, 0.02, 0.5)
2205        };
2206        let (offs_ext, _) = synth_kernel(&p_ext, n_tau, 10.0).unwrap();
2207        let dtau_ext = offs_ext[1] - offs_ext[0];
2208        let capped_step = 800.0 / (MAX_TAU_SAMPLES as f64 - 1.0);
2209        assert!(
2210            (dtau_ext - capped_step).abs() < 1e-9,
2211            "capped step {dtau_ext} != tau_max/(MAX_TAU_SAMPLES−1) = {capped_step}"
2212        );
2213        assert!(
2214            dtau_ext <= 0.35 / 3.0,
2215            "capped step {dtau_ext} cannot resolve the 0.35 µs triangle"
2216        );
2217        let tri_ext = triangle_kernel(dtau_ext, 0.35);
2218        let nonzero_ext = tri_ext
2219            .iter()
2220            .take(tri_ext.len() / 2)
2221            .filter(|&&v| v > 0.0)
2222            .count();
2223        assert!(
2224            nonzero_ext >= 3,
2225            "triangle degenerated under cap: {nonzero_ext} nonzero samples per side"
2226        );
2227    }
2228
2229    #[test]
2230    fn burst_and_channel_broaden_further() {
2231        // Folding in burst + channel widens the kernel TOF support.
2232        let base = IkedaCarpenterParams::constant(1.0, 0.1, 0.0);
2233        let (o0, _) = synth_kernel(&base, 600, 10.0).unwrap();
2234        let support0 = o0.iter().cloned().fold(f64::MIN, f64::max)
2235            - o0.iter().cloned().fold(f64::MAX, f64::min);
2236        let folded = IkedaCarpenterParams {
2237            burst_sigma_us: Some(0.3),
2238            channel_fwhm_us: Some(0.35),
2239            ..IkedaCarpenterParams::constant(1.0, 0.1, 0.0)
2240        };
2241        let (o1, _) = synth_kernel(&folded, 600, 10.0).unwrap();
2242        let support1 = o1.iter().cloned().fold(f64::MIN, f64::max)
2243            - o1.iter().cloned().fold(f64::MAX, f64::min);
2244        assert!(support1 > support0, "folded {support1} !> bare {support0}");
2245    }
2246
2247    /// Sum-weighted variance of a sampled `(offsets, weights)` kernel on a
2248    /// uniform τ-grid. Normalization-independent (divides by Σw).
2249    fn kernel_variance(offsets: &[f64], weights: &[f64]) -> f64 {
2250        let w_sum: f64 = weights.iter().sum();
2251        let mean: f64 = offsets.iter().zip(weights).map(|(o, w)| o * w).sum::<f64>() / w_sum;
2252        offsets
2253            .iter()
2254            .zip(weights)
2255            .map(|(o, w)| (o - mean).powi(2) * w)
2256            .sum::<f64>()
2257            / w_sum
2258    }
2259
2260    #[test]
2261    fn unresolvable_tau_grid_is_rejected_loudly() {
2262        // Review F1, probe 1: β = 0.005 ⇒ slow reach 16/β = 3200 µs ⇒
2263        // capped step 3200/8191 ≈ 0.39 µs > the 0.35 µs triangle FWHM — the
2264        // sampled triangle would be the exact delta [0, 1, 0] and the
2265        // requested fold would silently vanish from the kernel. Must be a
2266        // loud construction error, not silent physics degradation.
2267        let p1 = IkedaCarpenterParams {
2268            channel_fwhm_us: Some(0.35),
2269            ..IkedaCarpenterParams::constant(2.0, 0.005, 0.5)
2270        };
2271        let err = IkedaCarpenter::new(p1.clone(), 25.0, &SynthesisGrid::new(1.0, 100.0))
2272            .expect_err("a delta-degenerate fold must be rejected");
2273        let msg = format!("{err:?}");
2274        assert!(
2275            msg.contains("cannot resolve") && msg.contains("Increase"),
2276            "error must diagnose the cap and name remedies: {msg}"
2277        );
2278        // The per-energy synthesis (kernel_at path) refuses identically.
2279        assert!(synth_kernel(&p1, 600, 10.0).is_err());
2280
2281        // Probe 2: α = 250 ⇒ the whole prompt pulse spans 18/α ≈ 0.07 µs,
2282        // less than ONE capped step (800/8191 ≈ 0.098 µs): sampling would
2283        // step over the prompt term entirely (0.9 of the pulse weight at
2284        // R = 0.1). Must also be rejected.
2285        let p2 = IkedaCarpenterParams::constant(250.0, 0.02, 0.1);
2286        assert!(
2287            IkedaCarpenter::new(p2, 25.0, &SynthesisGrid::new(1.0, 100.0)).is_err(),
2288            "a capped step wider than the prompt core must be rejected"
2289        );
2290    }
2291
2292    #[test]
2293    fn requested_fold_is_never_a_silent_no_op() {
2294        // Adjacent to probe 1 but resolvable (β = 0.05 ⇒ capped step
2295        // 320/8191 ≈ 0.039 µs ≤ FWHM/3): when synthesis is Ok and a fold is
2296        // requested, the folded kernel must genuinely differ from the
2297        // unfolded one — by approximately the analytic fold variance
2298        // FWHM²/6 — never by ~0 (the silent delta no-op this guards against).
2299        let base = IkedaCarpenterParams::constant(2.0, 0.05, 0.5);
2300        let folded = IkedaCarpenterParams {
2301            channel_fwhm_us: Some(0.35),
2302            ..base.clone()
2303        };
2304        let (o0, w0) = synth_kernel(&base, 600, 10.0).unwrap();
2305        let (o1, w1) = synth_kernel(&folded, 600, 10.0).unwrap();
2306        let dv = kernel_variance(&o1, &w1) - kernel_variance(&o0, &w0);
2307        let expected = 0.35f64.powi(2) / 6.0;
2308        assert!(
2309            dv > 0.5 * expected,
2310            "fold variance increment {dv} µs² vs analytic {expected} µs²: \
2311             the requested fold (nearly) vanished"
2312        );
2313    }
2314
2315    #[test]
2316    fn boundary_step_fwhm_over_3_is_admitted_and_fold_survives() {
2317        // Pin the exactly-admitted boundary `dtau = FWHM/3` (rejection is
2318        // STRICT: `capped_step > floor`). Per the TRI_MIN_SAMPLES_PER_SIDE
2319        // doc, each triangle side then samples
2320        // at {FWHM/3, 2FWHM/3, FWHM} — weights {2/3, 1/3, 0}: exactly 2
2321        // strictly interior nonzero samples, endpoint ON the triangle zero —
2322        // and the fold stays effective (non-delta, second moment ≈ 4FWHM²/27).
2323        //
2324        // Route to the boundary: n_tau = MIN_N_TAU = 8 with α = 1 gives a
2325        // prompt design step 18/7 ≈ 2.57 µs, far coarser than FWHM/3 for a
2326        // 1 µs triangle, so the fold refinement pins dtau to exactly
2327        // `fwhm / TRI_MIN_SAMPLES_PER_SIDE`. R = 0 keeps the cap inert
2328        // (capped step 18/8191 ≪ floor).
2329        let fwhm = 1.0;
2330        let p = IkedaCarpenterParams {
2331            channel_fwhm_us: Some(fwhm),
2332            ..IkedaCarpenterParams::constant(1.0, 0.1, 0.0)
2333        };
2334        let (offs, _) = synth_kernel(&p, MIN_N_TAU, 10.0)
2335            .expect("the dtau = FWHM/3 boundary must be admitted, not rejected");
2336        let dtau = offs[1] - offs[0];
2337        let boundary = fwhm / TRI_MIN_SAMPLES_PER_SIDE;
2338        assert!(
2339            (dtau - boundary).abs() < 1e-12,
2340            "step {dtau} µs is not the FWHM/3 boundary {boundary} µs"
2341        );
2342
2343        // The sampled triangle at the boundary: ≥ 7 samples, exactly 2
2344        // strictly interior nonzero per side, center far below the delta's 1.
2345        let tri = triangle_kernel(dtau, fwhm);
2346        assert!(tri.len() >= 7, "boundary triangle too short: {}", tri.len());
2347        let per_side = tri
2348            .iter()
2349            .take(tri.len() / 2)
2350            .filter(|&&v| v > 1e-9)
2351            .count();
2352        assert_eq!(
2353            per_side, 2,
2354            "boundary triangle must keep 2 strictly interior nonzero samples \
2355             per side: {tri:?}"
2356        );
2357        let center = tri[tri.len() / 2];
2358        assert!(
2359            center < 0.5,
2360            "center weight {center} — boundary triangle degenerated toward a delta"
2361        );
2362
2363        // Fold effectiveness: the discrete triangle's variance is 4·FWHM²/27
2364        // (samples {0, ±FWHM/3, ±2FWHM/3} with weights ∝ {1, 2/3, 1/3}),
2365        // ≈ 89 % of the analytic FWHM²/6 — the fold physics survives the
2366        // 2-interior-sample discretization.
2367        let tri_offs: Vec<f64> = (0..tri.len())
2368            .map(|i| (i as f64 - (tri.len() / 2) as f64) * dtau)
2369            .collect();
2370        let v = kernel_variance(&tri_offs, &tri);
2371        let want = 4.0 * fwhm * fwhm / 27.0;
2372        assert!(
2373            ((v - want) / want).abs() < 0.02,
2374            "boundary triangle variance {v} µs² vs discrete analytic {want} µs²"
2375        );
2376        assert!(
2377            v > 0.5 * (fwhm * fwhm / 6.0),
2378            "boundary fold variance {v} µs² collapsed below half the \
2379             continuous FWHM²/6 — fold (nearly) vanished"
2380        );
2381    }
2382
2383    #[test]
2384    fn fold_variance_matches_analytic_oracle() {
2385        // Independent analytic oracle for the fold convention: a
2386        // convolution adds second central moments, so the sampled kernel's
2387        // variance must grow by EXACTLY the fold kernel's analytic variance —
2388        // FWHM²/6 for the symmetric channel triangle (half-base = FWHM),
2389        // σ² for the Gaussian burst. Unlike the closed-loop calibration
2390        // tests, the expectation here comes from analysis, not from the
2391        // shared synthesis code. Pure-prompt pulse (R = 0) keeps trim /
2392        // edge-truncation error far below the increments.
2393        let base = IkedaCarpenterParams::constant(2.0, 0.1, 0.0);
2394        let (o0, w0) = synth_kernel(&base, 600, 10.0).unwrap();
2395        let v0 = kernel_variance(&o0, &w0);
2396        // Sanity: the bare Gamma(3, α) variance is 3/α².
2397        let v_gamma = 3.0 / (2.0f64 * 2.0);
2398        assert!(
2399            (v0 - v_gamma).abs() < 0.01 * v_gamma,
2400            "bare pulse variance {v0}, Gamma(3) analytic {v_gamma}"
2401        );
2402
2403        let fwhm = 0.35;
2404        let tri = IkedaCarpenterParams {
2405            channel_fwhm_us: Some(fwhm),
2406            ..base.clone()
2407        };
2408        let (o1, w1) = synth_kernel(&tri, 600, 10.0).unwrap();
2409        let dv_tri = kernel_variance(&o1, &w1) - v0;
2410        let want_tri = fwhm * fwhm / 6.0;
2411        assert!(
2412            ((dv_tri - want_tri) / want_tri).abs() < 0.02,
2413            "triangle fold added {dv_tri} µs², analytic FWHM²/6 = {want_tri} µs²"
2414        );
2415
2416        let sigma = 0.3;
2417        let gau = IkedaCarpenterParams {
2418            burst_sigma_us: Some(sigma),
2419            ..base.clone()
2420        };
2421        let (o2, w2) = synth_kernel(&gau, 600, 10.0).unwrap();
2422        let dv_gau = kernel_variance(&o2, &w2) - v0;
2423        let want_gau = sigma * sigma;
2424        assert!(
2425            ((dv_gau - want_gau) / want_gau).abs() < 0.02,
2426            "Gaussian burst added {dv_gau} µs², analytic σ² = {want_gau} µs²"
2427        );
2428    }
2429}