Skip to main content

nereids_pipeline/
counts_fit.rs

1//! The areal densities and temperatures of the materials in one or more
2//! regions of the detector, each region's background and gamma transmission,
3//! the sample run's normalization, the time background, the timing offset,
4//! the flight path and the pulse's numbers, fitted to the counts of an
5//! open-beam run and a sample run recorded in the same time bins.
6
7use std::borrow::Cow;
8use std::cell::RefCell;
9use std::ops::{Range, RangeInclusive};
10use std::sync::Arc;
11
12use faer::{Mat, Side};
13use nereids_endf::resonance::{ResonanceCovariance, ResonanceData, RmlRange};
14use nereids_endf::retrieval::EndfLibrary;
15use nereids_fitting::error::FittingError;
16use nereids_fitting::lm::{FitModel, FlatMatrix};
17use nereids_fitting::parameters::{FitParameter, ParameterSet};
18use nereids_fitting::poisson::{
19    NEWTON_DECREMENT_TOL, Prior, Unbounded, half_deviance, information_inverse,
20};
21use nereids_fitting::statistics::{Consistency, consistency};
22use nereids_physics::continuous_doppler::{
23    Channel, QuadratureBudget, SUPPORT_X, TierOneBroadening, broaden_with_budget,
24};
25use nereids_physics::detector_spread::region_shares;
26use nereids_physics::doppler::DopplerParams;
27use nereids_physics::flight_time_grid::{FlightTimeGrid, Rows};
28use nereids_physics::forward_scatter::{ForwardYield, forward_yield, lowest_exit_ratio};
29use nereids_physics::ikeda_carpenter::{EnergyLaw, IkedaCarpenterParams};
30use nereids_physics::lattice_doppler::{PhononSpectrum, broaden_in_lattice};
31use nereids_physics::resolution::TOF_FACTOR;
32use nereids_physics::thickness::{interacting_per_depth, uneven_transmission};
33use nereids_physics::transmission::resonance_center_energies;
34use rayon::prelude::*;
35use serde::{Deserialize, Serialize};
36
37use crate::beam::BeamSpline;
38use crate::error::PipelineError;
39use crate::open_beam::{
40    BOUND, COUNTS_TO_MEASURE_NOISE, Calibration, OpenBeamFit, PULSE_NUMBERS, Pulse, Recorded,
41    combined, counted, fit_on_halved_grids, laws, open_beam_with_intervals, overdispersion,
42    validate_counts, validate_live, weights_of,
43};
44
45/// A count in a bin predicted fewer counts than this has a chance below it
46/// under the model.
47pub const NEGLIGIBLE_PREDICTION: f64 = 1e-10;
48
49const SETTLED_OVERDISPERSION: f64 = 0.01;
50/// The most cells a spread's grid holds.
51const MOST_SPREAD_CELLS: usize = 1 << 20;
52
53pub(crate) const MOST_PASSES: usize = 20;
54
55/// The `(low, high)` temperature bounds in K that a fit with a free
56/// temperature uses.
57pub(crate) const TEMPERATURE_BOUNDS_K: (f64, f64) = (1.0, 5000.0);
58
59/// The start in K of a fitted temperature's second fit.
60const SECOND_START_K: f64 = TEMPERATURE_BOUNDS_K.1 / 2.0;
61
62/// The standard deviations under Poisson counts by which a sample run's
63/// overdispersion exceeds 1 when its counts reject a fit.
64const REJECTING_SDS: f64 = 3.0;
65
66/// A quantity the fit holds at a known value, fits from a starting value
67/// over the quantity's range, fits from `start` within `lower..=upper` inside
68/// that range, or fits over the range from a `value` measured elsewhere with
69/// standard deviation `sd`, a Gaussian prior on it.
70#[derive(Debug, Clone, Copy, PartialEq)]
71pub enum Value {
72    Known(f64),
73    Fitted(f64),
74    Within { start: f64, lower: f64, upper: f64 },
75    Measured { value: f64, sd: f64 },
76}
77
78impl Value {
79    pub(crate) fn parameter(
80        self,
81        name: impl Into<Cow<'static, str>>,
82        range: RangeInclusive<f64>,
83        allowed: &str,
84    ) -> Result<FitParameter, PipelineError> {
85        let name = name.into();
86        let (value, lower, upper) = match self {
87            Self::Known(v) | Self::Fitted(v) | Self::Measured { value: v, .. } => {
88                (v, *range.start(), *range.end())
89            }
90            Self::Within {
91                start,
92                lower,
93                upper,
94            } => (start, lower, upper),
95        };
96        if !(value.is_finite()
97            && range.contains(&lower)
98            && lower < upper
99            && range.contains(&upper)
100            && (lower..=upper).contains(&value)
101            && !matches!(self, Self::Measured { sd, .. } if !(sd.is_finite() && sd > 0.0)))
102        {
103            return Err(PipelineError::InvalidParameter(match self {
104                Self::Within { .. } => format!(
105                    "{name} must be {allowed}, with bounds lower < upper and a finite start \
106                     between them; got {self:?}"
107                ),
108                Self::Measured { .. } => format!(
109                    "{name} must be finite and {allowed}, with a finite positive sd; got {self:?}"
110                ),
111                _ => format!("{name} must be finite and {allowed}; got {self:?}"),
112            }));
113        }
114        Ok(FitParameter {
115            name,
116            value,
117            lower,
118            upper,
119            fixed: matches!(self, Self::Known(_)),
120        })
121    }
122}
123
124/// An open-beam run and a sample run recorded in the same time bins, read in
125/// one or more regions of the detector.
126#[derive(Debug, Clone)]
127pub struct Measurement {
128    /// Time-bin edges in µs.
129    pub time_edges_us: Vec<f64>,
130    /// `c_q`, the sample run's proton charge over the open-beam run's.
131    pub charge_ratio: f64,
132    /// `a`, the normalization of the sample run, positive, the same in every
133    /// region.
134    pub normalization: Value,
135    /// `[C, A, τ, D]` of the time background
136    /// `C + D·(t − t₁)/W + A·exp(−(t − t₁)/τ)`, the counts per µs and per pixel
137    /// at the open-beam run's proton charge that reach the detector without
138    /// passing through the moderator pulse, at time `t` of the time edges'
139    /// clock, `t₁` the first edge and `W` the edges' span: `C` and `A` 0 or
140    /// more, `τ` in µs positive and, unless known, at least the first bin's
141    /// width, since far below it only `A·τ` shows in the counts, `D` the rise
142    /// over the span, any real number.
143    /// A `D` not known needs `τ` known or within an upper bound of at most
144    /// `W/2`. [`NO_TIME_BACKGROUND`] gives none.
145    pub time_background: [Value; 4],
146    /// Counts that follow each run's duration, not its proton charge; `None`
147    /// for none.
148    pub room_background: Option<RoomBackground>,
149    /// Counts the detector records in another region than the one they
150    /// arrive in; `None` for none.
151    pub spread: Option<Spread>,
152    /// Neutrons the sample environment scatters evenly over the detector;
153    /// `None` for none.
154    pub environment_scatter: Option<EnvironmentScatter>,
155    /// A filter the beam crosses ahead of every region in both runs; `None`
156    /// for none.
157    pub filter: Option<Filter>,
158    /// The regions, separate sets of pixels timed by one clock.
159    pub regions: Vec<Region>,
160}
161
162/// A filter in the beam, such as a cadmium sheet, crossed by the neutrons of
163/// both runs before they reach any region.
164///
165/// Each run's arriving beam is `φ·exp(−N·Σ_i x_i σ_i)` at every flight time
166/// before the pulse, `σ_i` each isotope's total cross section broadened by the
167/// free gas at the filter's temperature.  The open-beam fits that start a
168/// counts fit hold `N` at its start.
169#[derive(Debug, Clone)]
170pub struct Filter {
171    /// Each isotope with its share `x_i` of the filter's atoms, finite and
172    /// positive.
173    pub isotopes: Vec<(ResonanceData, f64)>,
174    /// `N`, the filter's areal density in atoms/barn, known, fitted or
175    /// measured, at least 0.
176    pub areal_density: Value,
177    /// The filter's temperature in K, within 1–5000 K.
178    pub temperature_k: f64,
179}
180
181impl Filter {
182    /// `Σ_i x_i σ_i` in barns at `energies_ev`, ascending.
183    pub(crate) fn cross_section(&self, energies_ev: &[f64]) -> Result<Vec<f64>, PipelineError> {
184        let (low, high) = TEMPERATURE_BOUNDS_K;
185        if !(low..=high).contains(&self.temperature_k)
186            || self.isotopes.is_empty()
187            || !(self.isotopes.iter()).all(|(_, x)| x.is_finite() && *x > 0.0)
188        {
189            return Err(PipelineError::InvalidParameter(format!(
190                "a filter needs isotopes of finite, positive shares and a temperature within \
191                 {low}–{high} K, got shares {:?} at {} K",
192                self.isotopes.iter().map(|(_, x)| x).collect::<Vec<_>>(),
193                self.temperature_k
194            )));
195        }
196        let mut total = vec![0.0; energies_ev.len()];
197        let (Some(&first), Some(&last)) = (energies_ev.first(), energies_ev.last()) else {
198            return Ok(total);
199        };
200        for (isotope, share) in &self.isotopes {
201            let doppler = DopplerParams::new(self.temperature_k, isotope.awr)
202                .map_err(|e| PipelineError::InvalidParameter(e.to_string()))?;
203            let read = (
204                (first.sqrt() - SUPPORT_X * doppler.u()).max(0.0).powi(2),
205                (last.sqrt() + SUPPORT_X * doppler.u()).powi(2),
206            );
207            if !isotope.ranges.iter().any(|range| {
208                range.is_evaluable() && range.energy_low <= read.0 && read.1 <= range.energy_high
209            }) {
210                return Err(PipelineError::InvalidParameter(format!(
211                    "the Doppler-broadened cross section of the filter's {} reads {:.6e}–{:.6e} \
212                     eV, which no single one of its evaluated resolved ranges holds",
213                    isotope.isotope, read.0, read.1
214                )));
215            }
216            let sigma = broadened(
217                energies_ev,
218                isotope,
219                self.temperature_k,
220                Channel::Total,
221                None,
222            )
223            .map_err(PipelineError::InvalidParameter)?;
224            for (t, s) in total.iter_mut().zip(&sigma.values) {
225                *t += share * s;
226            }
227        }
228        Ok(total)
229    }
230
231    /// The filter's cross section at `grid`'s points, in their order.
232    pub(crate) fn on_grid(&self, grid: &FlightTimeGrid) -> Result<Vec<f64>, PipelineError> {
233        let mut energies = grid.energies_ev();
234        energies.reverse();
235        let mut sigma = self.cross_section(&energies)?;
236        sigma.reverse();
237        Ok(sigma)
238    }
239}
240
241/// A [`Measurement::time_background`] of no counts.
242pub const NO_TIME_BACKGROUND: [Value; 4] = [
243    Value::Known(0.0),
244    Value::Known(0.0),
245    Value::Known(1.0),
246    Value::Known(0.0),
247];
248
249/// Counts that arrive at the same rate at every time of every frame, in
250/// both runs alike, whatever the proton charge and whatever is in front of
251/// the pixels, such as the detector's dark counts: `ρ` per µs per pixel per
252/// frame, `ρ · w_k · F` per pixel in a bin of width `w_k` of a run of `F`
253/// frames.
254#[derive(Debug, Clone, Copy, PartialEq)]
255pub struct RoomBackground {
256    /// `ρ`, 0 or more.
257    pub rate: Value,
258    /// The frames each run recorded, the open-beam run's then the sample
259    /// run's, finite and positive.
260    pub frames: [f64; 2],
261}
262
263/// A share `h` of the counts arriving in each cell of a detector grid that
264/// the detector records elsewhere, spread by the radial kernel
265/// `Σ_c w_c·exp(−r/s_c)/(2π s_c²)`
266/// ([`transfer`](nereids_physics::detector_spread::transfer)): region `r`
267/// records `(1 − h)·μ_r + h·Σ_q F_rq·μ_q` of the counts `μ` arriving in the
268/// regions in each bin of both runs, `F_rq` the share of the spread counts
269/// arriving evenly over region `q`'s cells that lands in region `r`'s cells
270/// ([`region_shares`]).  Cells in no region neither send nor record counts.
271#[derive(Debug, Clone, PartialEq)]
272pub struct Spread {
273    /// `h`, within 0–1.
274    pub share: Value,
275    /// `(w_c, s_c)`: each term's weight, finite and positive, normalized by
276    /// their sum, and length in cells, finite and positive.
277    pub kernel: Vec<(f64, f64)>,
278    /// The grid's rows and columns, at most 2^20 cells in all.
279    pub grid: [usize; 2],
280    /// Each region's cells as `[row, column]`, in the order of
281    /// [`Measurement::regions`]; a cell is in one region at most.
282    pub cells: Vec<Vec<[usize; 2]>>,
283}
284
285/// The fraction `s` of the neutrons leaving the sample position that the
286/// sample environment, such as a furnace, scatters evenly over the detector.
287///
288/// A region of `P` pixels gains `s(P·m − N)` neutron counts per bin, with local
289/// neutron counts `N` and detector mean `m` per pixel. Photons keep their local
290/// counts. An open-beam run does not cancel the sample run's scatter.
291///
292/// # References
293/// P. Boillat et al., Opt. Express 26, 15769 (2018).
294#[derive(Debug, Clone, PartialEq)]
295pub struct EnvironmentScatter {
296    /// Fraction of the neutrons redistributed, within 0–1.
297    pub fraction: Value,
298    /// Source of the detector-wide mean in each bin.
299    pub source: ScatterSource,
300}
301
302/// Detector coverage for the environment's scattered neutrons.
303#[derive(Debug, Clone, PartialEq)]
304pub enum ScatterSource {
305    /// The regions partition all illuminated detector pixels on the same clock.
306    FullDetector,
307    /// Detector-wide mean counts per pixel before live losses on the regions’ clock, open then sample.
308    Measured {
309        /// Total counts per pixel in each bin of each run.
310        total: [Vec<f64>; 2],
311        /// Independently measured photon counts per pixel on the same exposure scale.
312        photons: Option<[Vec<f64>; 2]>,
313    },
314}
315
316/// The counts of a set of pixels in both runs, its background and the
317/// material the beam crosses there.
318#[derive(Debug, Clone)]
319pub struct Region {
320    /// Raw counts of the open-beam run, one per bin.
321    pub open_counts: Vec<f64>,
322    /// Raw counts of the sample run, one per bin.
323    pub sample_counts: Vec<f64>,
324    /// The fraction of the open-beam run's counts arriving in each bin that
325    /// the detector records, in (0, 1]; `None` records every one.
326    pub open_live: Option<Vec<f64>>,
327    /// The fraction of the sample run's counts arriving in each bin that the
328    /// detector records, in (0, 1]; `None` records every one.
329    pub sample_live: Option<Vec<f64>>,
330    /// `[b0, b1, b2, d, f]` of the background
331    /// `b(E) = b0 + b1/√E + b2·√E + d·exp(−f/√E)`: `b0` and `d`
332    /// dimensionless, `b1` in √eV, `b2` in 1/√eV and `f` in √eV, `f` 0 or
333    /// more and the others any real number.
334    pub background: [Value; 5],
335    /// The region's area in pixels, finite and positive.
336    pub pixels: f64,
337    /// The fraction of the time background that reaches the region's pixels in
338    /// the sample run through what is in front of them, within 0–1.
339    pub gamma_transmission: Value,
340    /// `ε`, the share of the neutrons captured in the region's sample whose
341    /// gammas its pixels record, 0 or more: the sample run gains
342    /// `c_q·a·ε·φ·(1 − T)·Σ_m n_m σ_γm/D`, the captures at the neutrons' first
343    /// collision, `σ_γm` each isotope's capture cross section broadened like
344    /// its total one, at the neutrons' flight times.
345    pub capture_gammas: Value,
346    /// `Ω`, the share of the neutrons scattered once in the region's sample
347    /// and leaving through its back face that its pixels record, 0 or more:
348    /// the sample run gains `c_q·a·Ω·φ·Σ_m n_m σ_sm·G_m`, `σ_sm` each isotope's
349    /// elastic cross section broadened like its total one and `G_m` its share
350    /// leaving through the back face ([`forward_yield`]), at the mean areal
351    /// density and the neutrons' flight times.
352    pub in_scatter: Value,
353    /// `δt` in µs, any real number: the region's pixels record every count
354    /// `δt` later than `t0`'s clock, a neutron of flight time `u` at
355    /// `t0 + δt + u` and the time background `δt` late.
356    pub timing_offset_us: Value,
357    /// The material the beam crosses in the region; `None` for nothing, which
358    /// transmits every neutron.
359    pub material: Option<Material>,
360}
361
362/// An energy range a fit leaves out of a material's sample run.
363///
364/// The fit leaves out the sample run's bins that the mean arrival time of a
365/// neutron of an energy in the range can fall in, at the fitted clock offsets,
366/// flight path and pulse.
367#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
368#[serde(deny_unknown_fields)]
369pub struct ExcludedRange {
370    /// The range's ends in eV, the lower first, both positive.
371    pub energy_ev: (f64, f64),
372    /// The evidence that the evaluated cross section is wrong there; not blank.
373    pub reason: String,
374}
375
376impl ExcludedRange {
377    pub(crate) fn check(&self) -> Result<(), PipelineError> {
378        let (low, high) = self.energy_ev;
379        if low > 0.0 && low < high && high.is_finite() && !self.reason.trim().is_empty() {
380            return Ok(());
381        }
382        Err(PipelineError::InvalidParameter(format!(
383            "an excluded range needs positive ends in eV, the lower first, and the reason the \
384             evaluation is wrong there, got {self:?}"
385        )))
386    }
387}
388
389/// A material's isotopes and temperature.
390#[derive(Debug, Clone)]
391pub struct Material {
392    /// Each isotope with its areal density in atoms/barn, known, fitted or
393    /// measured, at least 0.
394    pub isotopes: Vec<(ResonanceData, Value)>,
395    /// The temperature in K, within 1–5000 K: the thermodynamic one with a
396    /// [`Self::lattice`], an effective one for the free gas.
397    pub temperature_k: Value,
398    /// `v`, the relative variance of the areal density over the region's
399    /// pixels, weighted by the beam that reaches them, 0 or more: 0 for a
400    /// uniform sample.  The region transmits `(1 + v·D)^(−1/v)`, the mean for a
401    /// Gamma-distributed areal density, `D` the optical depth at the mean density
402    /// ([`uneven_transmission`]).
403    pub thickness_variance: Value,
404    /// The library the isotopes' resonance data were read from.
405    pub library: EndfLibrary,
406    /// Energy ranges where an isotope's evaluated cross section is wrong.
407    pub excluded_ranges: Vec<ExcludedRange>,
408    /// The covariance of the resonance parameters of the isotopes listed, each
409    /// with its index in `isotopes`, which [`CountsFit::covariance`] carries;
410    /// an isotope not listed has its resonance parameters taken as exact.
411    pub covariances: Vec<(usize, ResonanceCovariance)>,
412    /// The phonon density of states the material's nuclei vibrate with, which
413    /// broadens its cross sections by the harmonic lattice
414    /// ([`broaden_in_lattice`]); `None` broadens them by the free gas.
415    pub lattice: Option<PhononSpectrum>,
416}
417
418/// The fitted quantities of every region, and the normalization, time
419/// background, timing offset, flight path and pulse numbers the regions share.
420#[derive(Debug, Clone)]
421pub struct CountsFit {
422    /// Each region's fitted quantities and counts, in the order given.
423    pub regions: Vec<RegionFit>,
424    /// The normalization `a`: the known one, or the fitted one.
425    pub normalization: f64,
426    /// The timing offset `t0` in µs: the known one, or the fitted one.
427    pub t0_us: f64,
428    /// The flight path in m: the known one, or the fitted one.
429    pub flight_path_m: f64,
430    /// The pulse's `[α₀, α₁]`, each the known or the fitted one.
431    pub alpha: [f64; 2],
432    /// The pulse's `[β₀, β₁]`, each the known or the fitted one.
433    pub beta: [f64; 2],
434    /// The pulse's `[p_α, p_β]`, each the known or the fitted one.
435    pub exponents: [f64; 2],
436    /// The pulse's `R`: the known one, or the fitted one.
437    pub r: f64,
438    /// The square of the pulse's triangle FWHM, `h²` in µs²: the known one, or
439    /// the fitted one.
440    pub fwhm_squared_us2: f64,
441    /// The pulse's `R_high`, the known or the fitted one; `None` without one.
442    pub r_high: Option<f64>,
443    /// The detector tail's `[f, τ_D]`, each the known or the fitted one;
444    /// `None` without one.
445    pub detector_tail: Option<[f64; 2]>,
446    /// The time background's `[C, A, τ, D]`, each the known or the fitted one;
447    /// a fitted `τ` is undetermined when `A` ends at 0.
448    pub time_background: [f64; 4],
449    /// The room background's `ρ`: the known one, the fitted one, or 0 without
450    /// one.
451    pub room_background: f64,
452    /// The spread's `h`: the known one, the fitted one, or 0 without one.
453    pub spread_share: f64,
454    /// The environment scatter's `s`: the known one, the fitted one, or 0
455    /// without one.
456    pub scatter_fraction: f64,
457    /// The filter's areal density `N` in atoms/barn: the known one, or the
458    /// fitted one; 0 without a filter.
459    pub filter_density: f64,
460    /// Covariance of the fitted quantities among, in this order, each region's
461    /// densities, in the order given, temperature and thickness variance,
462    /// region by region; the
463    /// normalization; each region's `b0`, `b1`, `b2`, `d` and `f`, region by region;
464    /// each region's gamma transmission, region by region; each region's
465    /// capture gammas' `ε`, region by region; each region's in-scatter's `Ω`,
466    /// region by region; each region's timing offset `δt`, region by region;
467    /// the time background's `C`, `A`, `τ` and `D`; the room
468    /// background's `ρ`; the spread's `h`; the environment scatter's `s`; the
469    /// filter's `N`; `t0`; the
470    /// flight path; `α₀`, `α₁`,
471    /// `β₀`, `β₁`, `R`, `h²`, `R_high`, `f` and `τ_D`: the inverse of the information at the fit, each run's expected information over its
472    /// overdispersion plus `1/sd²` for each measured quantity and `C⁻¹` over
473    /// the pulse numbers a calibration's
474    /// [`Pulse::prior`](crate::open_beam::Pulse::prior) covers.  The row and
475    /// column of a quantity on one of its bounds, or that neither the counts
476    /// nor a measurement determine, are NaN, and the other entries are
477    /// conditional on every quantity that ended on a bound being held there;
478    /// every entry is NaN when the fitted temperature of any region ends at
479    /// 1 K or 5000 K.  `None` when the fit did not converge.
480    ///
481    /// Each covariance in a material's [`Material::covariances`] adds `S M Sᵀ`,
482    /// first order in the resonance parameters it lists, so valid while a
483    /// standard deviation of each moves the fit little: `M` that covariance,
484    /// `S = −C Jᵀ W c`, `C` this covariance without the term, `J` and `c` the
485    /// counts' slopes with respect to the fitted quantities and to those
486    /// parameters, the latter by central differences at a tenth of each
487    /// standard deviation, and `W` the counts' weights.  Every other known
488    /// quantity is taken as exact.
489    /// They are not reliable where the counts barely determine a fitted
490    /// temperature or barely separate it from a density, as at few counts or
491    /// for a thin sample at modest counts.
492    pub covariance: Option<FlatMatrix>,
493    /// The fitted quantities' Gaussian without their bounds, in the
494    /// covariance's order (see [`Unbounded`]), with the resonance parameters
495    /// taken as exact, NaN where `covariance` is at a temperature edge.  `None` when `covariance` is, or when the fitter
496    /// reports none.
497    pub unbounded: Option<Unbounded>,
498    /// Whether each fitted quantity, in the covariance's order, ended on one
499    /// of its bounds.
500    pub on_bound: Vec<bool>,
501    /// Each run's half Poisson deviance over the overdispersion it was
502    /// weighted with, summed over both runs of every region at the fit, outside
503    /// the sample runs' [`RegionFit::excluded_bins`].
504    pub deviance: f64,
505    /// Whether the fitter converged, the open-beam fits' time background
506    /// settled at the fitted one, every sample run's overdispersion settled,
507    /// the grid met its rule at the fitted temperatures, its flight times
508    /// cover the fitted `t0`, flight path and pulse, and the bins left out at
509    /// those are the ones the fit left out.
510    pub converged: bool,
511    /// The rule that ended the fit unconverged, with the quantities the fitter
512    /// was still moving, the decrease still predicted and the impossible or
513    /// refused trial steps at its step limit or with no step; `None` when it converged.
514    pub unconverged: Option<String>,
515    /// For each measured quantity, in the covariance's order, its value
516    /// without the fit's bounds ([`Self::unbounded`]) less its measurement
517    /// over the standard deviation of that difference, `√(sd² − variance + N)`,
518    /// the variance also without the bounds and `N` the term resonance
519    /// covariances add to it: near 0 ± 1 when the counts agree
520    /// with the measurement.  NaN for a quantity the counts and measurements
521    /// do not determine, and for every quantity when a fitted temperature ends
522    /// at 1 K or 5000 K; it loses precision as the counts' information on the
523    /// quantity vanishes beside the measurement's.  `None` when `unbounded`
524    /// is.
525    pub measured_pulls: Option<Vec<f64>>,
526    /// Whether the counts accept the pulse's calibration on the numbers it
527    /// covers, by [`consistency`] with the fit's numbers and covariance
528    /// without their bounds ([`Self::unbounded`]).  The counts' information is
529    /// divided by each run's overdispersion, so the test weakens as the
530    /// overdispersion grows.  The
531    /// overdispersion is at least 1, so with Poisson counts its estimate
532    /// inflates the covariances the test uses, and `p` rejects a right
533    /// calibration less often than its value says, the more so the fewer bins
534    /// each run counts.  A calibration fitted to the same open-beam run is not
535    /// independent of the fit, which the test does not account for.  `None`
536    /// without a calibration, when `unbounded` is `None` or withheld, or when
537    /// [`consistency`] gives none.
538    pub pulse_consistency: Option<Consistency>,
539    /// Step, in µs, of the fit's grid.
540    pub step_us: f64,
541    /// Number of points of that grid.
542    pub points: usize,
543    /// How many times the grid of
544    /// [`FlightTimeGrid::new`](nereids_physics::flight_time_grid::FlightTimeGrid::new)
545    /// was halved to reach it; that grid is built at the starting `t0`,
546    /// flight path and pulse, or at fitted ones when the fit rebuilt it.
547    pub halvings: usize,
548}
549
550/// One region's fitted quantities and counts.
551#[derive(Debug, Clone)]
552pub struct RegionFit {
553    /// Areal density of each isotope of the region's material in atoms/barn,
554    /// in the order given: the known one, or the fitted one; empty without a
555    /// material.
556    pub densities: Vec<f64>,
557    /// The material's temperature in K: the known one, or the fitted one;
558    /// `None` without a material.
559    pub temperature_k: Option<f64>,
560    /// The material's thickness variance `v`: the known one, or the fitted
561    /// one; `None` without a material.
562    pub thickness_variance: Option<f64>,
563    /// `[b0, b1, b2, d, f]` of [`Region::background`], each the known or the
564    /// fitted one.
565    pub background: [f64; 5],
566    /// The gamma transmission: the known one, or the fitted one.
567    pub gamma_transmission: f64,
568    /// The capture gammas' `ε`: the known one, or the fitted one.
569    pub capture_gammas: f64,
570    /// The in-scatter's `Ω`: the known one, or the fitted one.
571    pub in_scatter: f64,
572    /// The timing offset `δt` in µs: the known one, or the fitted one.
573    pub timing_offset_us: f64,
574    /// The region's beam per µs, as a function of the arrival time its pixels
575    /// record less the starting `t0`, fitted to both runs, with the intervals
576    /// the region's open-beam fit chose.
577    pub beam: BeamSpline,
578    /// Whether the region's open-beam fit chose its richest beam; see
579    /// [`OpenBeamFit::at_limit`](crate::open_beam::OpenBeamFit::at_limit).
580    pub beam_at_limit: bool,
581    /// The open-beam and sample counts the fit predicts in each bin at its
582    /// answer, live fractions included, on the grid it accepted: the counts
583    /// [`CountsFit::deviance`] compares with the measured ones.
584    pub predicted: [Vec<f64>; 2],
585    /// Variance of the counts of the open-beam run, then of the sample run,
586    /// over their Poisson variance: the value each run's counts are divided by
587    /// in the returned fit.  The open-beam run's is the region's open-beam
588    /// fit's [`OpenBeamFit::overdispersion`](crate::open_beam::OpenBeamFit::overdispersion); the sample run's is measured the
589    /// same way, on the bins outside `excluded_bins` the first fit predicts at
590    /// least one count, by the
591    /// previous fit, and within 1% by the returned one when the fit converged.
592    /// `None` when the run's counts have not measured it; the open-beam run is
593    /// then weighted with 1, and the sample run as the open-beam run.
594    pub overdispersion: [Option<f64>; 2],
595    /// Indices, ascending, of the sample run's bins its material's
596    /// [`Material::excluded_ranges`] leave out, and, under a spread whose share
597    /// is not known 0, those of every region that spreads counts into it: they
598    /// add nothing to the deviance, the information or the sample run's
599    /// overdispersion.
600    pub excluded_bins: Vec<usize>,
601}
602
603/// Fit the areal densities and temperatures of the regions' materials, each
604/// region's background terms and gamma transmission, the normalization, the
605/// time background, and the timing offset, flight path and pulse numbers of
606/// `calibration`, that are not known, to the
607/// raw counts of both runs in every region.  On a uniform grid of flight
608/// times `u_i`, energies `E_i` and step `w`, the counts of region `r` in bin
609/// `k` are
610///
611/// ```text
612/// O_rk   = ℓ^O_rk · [w Σ_i φ_ri P_ki + p_r G_k + p_r ρ F^O w_k]
613/// S_rk   = ℓ^S_rk · [c_q · a · (w Σ_i φ_ri [T_ri + b_r(E_i)] P_ki + γ_r p_r G_k)
614///                    + p_r ρ F^S w_k]
615/// T_ri   = (1 + v_r D_ri)^(−1/v_r), D_ri = Σ_m n_rm σ_m(E_i; T_r), or 1 without a material
616/// b_r(E) = b0_r + b1_r/√E + b2_r·√E + d_r·exp(−f_r/√E)
617/// G_k    = ∫ over bin k of (C + D·(t − t₁)/W + A·exp(−(t − t₁)/τ)) dt
618/// ```
619///
620/// with `φ_r` the region's beam per µs, `P_ki` the chance of a neutron at
621/// `u_i` arriving in bin `k`, `n_rm` and `σ_m` each isotope's density and
622/// total cross section Doppler-broadened at the material's temperature `T_r`,
623/// `c_q` the charge ratio, `a` the normalization and `ℓ^O_rk`, `ℓ^S_rk` each
624/// run's live fraction.  The background is beam neutrons that reach the
625/// detector another way, so it passes through the pulse and scales with the
626/// normalization; SAMMY's `BackA`, `BackB`, `BackC`, `BackD` and `BackF`
627/// (`cro/mnrm1.f90`) are `a·b0`, `a·b1`, `a·b2`, `a·d` and `f`, to within the
628/// background's change over the pulse's delay.  The time
629/// background `G` is counts that follow the proton charge but reach the
630/// detector without passing through the moderator pulse, such as the prompt
631/// gammas of each proton pulse and their tail and earlier pulses' slow
632/// neutrons, at the time `t` of the edges' clock, `t₁` the first edge, `W` the
633/// edges' span and `D` its rise over it: it is not folded with the pulse, and the sample
634/// run scales it with `c_q·a`, which correct the charge ratio and an
635/// efficiency change alike in every pixel, and the fraction `γ_r` that reaches
636/// the region's pixels, `p_r` the region's pixels.  It turns
637/// the ratio `R` of the neutrons alone into `R + g·(γ_r − R)`, `g` its share of
638/// the open-beam counts; SAMMY's backgrounds in time (`Bgfrpi`) are added to
639/// the transmission instead.  The room background `ρ` ([`RoomBackground`])
640/// follows each run's duration instead, `F^O` and `F^S` its frames and `w_k`
641/// bin `k`'s width: it is neither folded with the pulse nor scaled by the
642/// charge ratio, the normalization or the gamma transmission, so it separates
643/// from the time background's `C` only where `c_q·a·γ_r` differs from
644/// `F^S/F^O`.
645///
646/// The regions share the normalization, the run pair's scale; and `t0`, the
647/// flight path and the pulse, which one clock, flight path and moderator set
648/// for every pixel, and with them the grid and `P_ki`.  Each region has its
649/// own beam, from its own open-beam counts, with the intervals its
650/// [`fit_open_beam`](crate::open_beam::fit_open_beam) chooses, fitted with
651/// the rest to both runs; and its own
652/// background, which depends on what surrounds its pixels.  A region without
653/// a material counts `c_q·a·(1 + b_r)` of its beam in the sample run, so it
654/// pins the normalization when its `b0` is known, as zero in the open-region
655/// normalization of imaging, and nothing about it when its `b0` is fitted.
656/// A measurement whose regions hold no material is fitted for an
657/// [`EnvironmentScatter`]'s fraction: open pixels alone measure it, with no
658/// cross section or temperature, where the ratio of the two runs' detector
659/// means changes from bin to bin.
660/// The regions must be separate pixels: the covariance takes every bin as
661/// independent.
662///
663/// The [`Calibration`]'s `t0` and flight path `L` are fitted unless known.
664/// The grid is built at a `t0₀` and `L₀`, at first the starting ones.  Grid
665/// point `i` keeps its energy and arrives at `t0 + (L/L₀)·u_i`, with `u_i`
666/// its flight time at `t0₀` and `L₀`, standing for `(L/L₀)·w` of flight time;
667/// the beams are functions of the arrival time less the starting `t0`.  This
668/// is SAMMY's energy scale: its `Tzero` is `t0`, and its `Elzero` times its
669/// flight path is `L` (`dat/mdat0.f90`, `Mtzero`).
670///
671/// The pulse's numbers are fitted unless known, each point's `P_ki` taken at
672/// the pulse's laws at its energy `E_i`.  A trial pulse whose `α` or `β` is 0
673/// at some energy is outside the model and rejected; a fit driven there ends
674/// unconverged.  The open-beam fits that start the beams and weight the
675/// open-beam runs use the starting pulse and, at first, the time background's
676/// starting numbers; the fit is repeated with them at its fitted numbers, up
677/// to twenty times, until the fitted numbers change the counts they took as
678/// known by `Σ_r Σ_k (ΔO_rk)²/O_rk` at most [`BOUND`] over every region's
679/// open-beam bins, and from the third time on each region keeps the beam
680/// intervals its second open-beam fit chose.
681///
682/// The grid's first step is at most half the narrowest Doppler full width at
683/// half maximum, in flight time, of any resonance of any region inside its
684/// energy span, at that region's starting temperature; it is then halved
685/// until the counts of every run of every region, together, meet
686/// [`BOUND`].  The step is uniform and shared, so a
687/// wide window whose span holds a narrow resonance at high energy, or a low
688/// fitted temperature in any region, can exceed the grid's point cap; a
689/// temperature a region's counts barely determine can run to 1 K and refuse
690/// the fit that way.
691///
692/// The fit minimizes each run's half Poisson deviance over its
693/// overdispersion, plus `½((x − value)/sd)²` for each [`Value::Measured`]
694/// quantity `x`, and `½(θ − m)ᵀC⁻¹(θ − m)` over the pulse numbers `θ` a
695/// calibration's [`Pulse::prior`](crate::open_beam::Pulse::prior) covers,
696/// with `m` and `C` that prior's mean, which may lie past a number's bound,
697/// and covariance.  Each region's open-beam run is weighted with its
698/// open-beam fit's overdispersion, and its sample run first with the same.
699/// The fit is repeated from its answer while any sample run's
700/// overdispersion, measured on the bins outside those left out that the first
701/// fit predicts at least one count, changes by more than 1%, the coarser grid
702/// of the accepted pair is
703/// wider than the rule at the fitted temperatures, its flight times miss
704/// some that the fitted `t0`, `L` and pulse need, or the bins left out at
705/// those differ from the ones it left out, which for the first fit are those
706/// at the starting ones.  The next first grid is the
707/// finer of that pair's coarser grid and the rule's grid at the fitted
708/// temperatures, or, when the flight times miss, the rule's grid of a grid
709/// built at the fitted `t0`, `L` and pulse.  After twenty fits it is reported
710/// unconverged; [`CountsFit::unconverged`] names the rule that ended a fit.
711///
712/// The fitter finds a local minimum.  Where a temperature is fitted and the
713/// counts reject the fit, some region's sample-run overdispersion exceeding 1
714/// by more than three of its standard deviations under Poisson counts,
715/// `√(2/ν)` over the run's `ν` bins outside those left out, the fit is made
716/// again with each fitted temperature started at 2,500 K, or at the bound
717/// nearest it.  The second fit is returned when it converged and the first
718/// did not, or when both or neither converged and its half Poisson deviance
719/// of every run's counts, outside the sample bins either fit leaves out, is
720/// lower by more than [`NEWTON_DECREMENT_TOL`]; a second fit that fails is
721/// set aside.  Where a black resonance
722/// empties bins and the background is near zero, a fitted background with no
723/// lower bound can drive a black bin's prediction to zero, and the fit ends
724/// unconverged; with `b1` and `b2` known, `b0` bounded below by 0 ends on
725/// that bound, converged.
726///
727/// # Errors
728/// [`PipelineError::ShapeMismatch`] unless each run of each region has one
729/// count, and one live fraction when given, per bin;
730/// [`PipelineError::InvalidParameter`] if a count is not a whole non-negative
731/// number, a run has no counts, a live fraction is not in (0, 1], the charge
732/// ratio or a room background's frames are not finite and positive, a
733/// region's pixels are not finite and
734/// positive, a region without a material has capture gammas or in-scatter
735/// other than known 0, a spread's kernel has a term whose weight or length is
736/// not finite and positive, its grid holds no cell or more than 2^20, it does
737/// not give each region one or more cells on the grid, or a cell is in two
738/// regions, an environment scatter's detector means do not each hold one
739/// finite count of 0 or more per bin or it comes with a spread, a known,
740/// starting or measured value is
741/// not finite and in its quantity's range, a measured value's sd is not finite
742/// and positive, bounds are not `lower < upper` in that range
743/// with the start between them, the pulse's calibration covers a number that
744/// is not fitted or is measured, no region holds a material and no environment
745/// scatter's fraction is fitted, a material has
746/// no isotopes or lists one twice, an isotope's resonance data are not
747/// finite, an isotope not known to be absent has a resonance between the
748/// energies of the last and first time edges, at the starting `t0` and flight
749/// path or a converged fit's, outside the pulse's
750/// [`line_span_ev`](crate::open_beam::Pulse::line_span_ev), or the energies
751/// its broadened cross section reads on the grid at the starting `t0`, flight
752/// path and pulse, or at the fitted ones of any pass that rebuilds it, at the
753/// region's known temperature or at the upper bound of a fitted one, down to
754/// zero for a window within the thermal spread of zero energy, are not inside
755/// a single one of its evaluated resolved ranges,
756/// or, in a region with in-scatter, an isotope has a resonance below that
757/// grid's lowest energy and above the lowest energy a neutron scattered forward
758/// leaves with;
759/// [`PipelineError::UnmodelledCounts`] if at the fit, converged or not, a bin
760/// is predicted negative or non-finite counts, recorded or, under a spread
761/// or an environment scatter, arriving, or, outside the bins left
762/// out, holds counts predicted below [`NEGLIGIBLE_PREDICTION`]: starting or known values the fitter cannot
763/// leave;
764/// [`PipelineError::InvalidParameter`] if a material's covariance names no
765/// isotope of it, or one twice, lists no resonance, one twice or one the
766/// isotope does not have, or is not a finite symmetric positive
767/// semi-definite matrix over their energies and widths, or if it is given for
768/// an isotope another region also holds or with a pulse calibration's prior;
769/// everything [`fit_open_beam`](crate::open_beam::fit_open_beam) refuses for
770/// any region;
771/// [`PipelineError::FlightTimeGrid`] for the grid's refusals at the starting
772/// `t0`, flight path and pulse or the fitted ones of any pass, including more
773/// points than it allows; [`PipelineError::Fitting`] if the fitter fails, a
774/// region's open-beam fit does not converge with the beam intervals it keeps,
775/// the cross sections fail at the start or, for a listed resonance parameter
776/// shifted, at the fit, or a decomposition of the pulse's
777/// consistency test fails; a failure at a trial temperature is a rejected
778/// step.
779pub fn fit_counts(
780    measurement: &Measurement,
781    calibration: &Calibration,
782) -> Result<CountsFit, PipelineError> {
783    let scatter_fitted = measurement
784        .environment_scatter
785        .as_ref()
786        .is_some_and(|scatter| !matches!(scatter.fraction, Value::Known(_)));
787    if !scatter_fitted
788        && measurement
789            .regions
790            .iter()
791            .all(|region| region.material.is_none())
792    {
793        return Err(PipelineError::InvalidParameter(
794            "no region of the measurement holds a material to fit".into(),
795        ));
796    }
797    let first = fit_settled(measurement, calibration, MOST_PASSES)?;
798    let Some(started_hot) = rejected(measurement, &first)
799        .then(|| started_hot(measurement))
800        .flatten()
801    else {
802        return Ok(first);
803    };
804    Ok(match fit_settled(&started_hot, calibration, MOST_PASSES) {
805        Ok(second) if better(measurement, &second, &first) => second,
806        _ => first,
807    })
808}
809
810/// Whether some region's sample-run overdispersion at `fit` exceeds 1 by more
811/// than [`REJECTING_SDS`] of its standard deviations under Poisson counts,
812/// `√(2/ν)` over the run's `ν` bins outside those left out.
813fn rejected(measurement: &Measurement, fit: &CountsFit) -> bool {
814    measurement
815        .regions
816        .iter()
817        .zip(&fit.regions)
818        .any(|(region, at)| {
819            let bins = (region.sample_counts.len() - at.excluded_bins.len()) as f64;
820            at.overdispersion[1].is_some_and(|phi| phi > 1.0 + REJECTING_SDS * (2.0 / bins).sqrt())
821        })
822}
823
824/// `measurement` with each fitted temperature started at [`SECOND_START_K`],
825/// or at the bound nearest it; `None` when no start moves.
826fn started_hot(measurement: &Measurement) -> Option<Measurement> {
827    let mut hot = measurement.clone();
828    let mut moved = false;
829    for material in hot.regions.iter_mut().filter_map(|r| r.material.as_mut()) {
830        let start = match material.temperature_k {
831            Value::Fitted(_) => SECOND_START_K,
832            Value::Within { lower, upper, .. } => SECOND_START_K.max(lower).min(upper),
833            Value::Known(_) | Value::Measured { .. } => continue,
834        };
835        if let Value::Fitted(old) | Value::Within { start: old, .. } = &mut material.temperature_k {
836            moved |= *old != start;
837            *old = start;
838        }
839    }
840    moved.then_some(hot)
841}
842
843/// Whether `fit` beats `other` on `measurement`'s counts, as
844/// [`fit_counts`] chooses.
845fn better(measurement: &Measurement, fit: &CountsFit, other: &CountsFit) -> bool {
846    if fit.converged != other.converged {
847        return fit.converged;
848    }
849    counts_deviance(measurement, fit, other) + NEWTON_DECREMENT_TOL
850        < counts_deviance(measurement, other, fit)
851}
852
853/// The half Poisson deviance of every run's counts at `fit`, outside the
854/// sample bins `fit` or `other` leaves out.
855fn counts_deviance(measurement: &Measurement, fit: &CountsFit, other: &CountsFit) -> f64 {
856    let runs = measurement
857        .regions
858        .iter()
859        .zip(&fit.regions)
860        .zip(&other.regions);
861    runs.map(|((region, at), beside)| {
862        let kept = |k: &usize| {
863            at.excluded_bins.binary_search(k).is_err()
864                && beside.excluded_bins.binary_search(k).is_err()
865        };
866        let open: f64 = (region.open_counts.iter().zip(&at.predicted[0]))
867            .map(|(&y, &mu)| half_deviance(y, mu))
868            .sum();
869        let sample: f64 = (region
870            .sample_counts
871            .iter()
872            .zip(&at.predicted[1])
873            .enumerate())
874        .filter(|(k, _)| kept(k))
875        .map(|(_, (&y, &mu))| half_deviance(y, mu))
876        .sum();
877        open + sample
878    })
879    .sum()
880}
881
882fn fit_settled(
883    measurement: &Measurement,
884    calibration: &Calibration,
885    most_passes: usize,
886) -> Result<CountsFit, PipelineError> {
887    let bins = starts_and_widths_us(&measurement.time_edges_us);
888    let frames = open_frames(measurement.room_background.as_ref());
889    let mut open = starting_bypass(measurement)?;
890    let mut offsets = (0..measurement.regions.len())
891        .map(|region| starting(measurement, Role::TimingOffset { region }))
892        .collect::<Result<Vec<f64>, PipelineError>>()?;
893    let mut intervals: Option<Vec<usize>> = None;
894    let shares = spread_shares(measurement)?;
895    for passes in 1.. {
896        let (mut fit, _) = fit_counts_answer(
897            measurement,
898            calibration,
899            BeamStarts::OpenFitsAt(open, intervals.clone(), offsets.clone()),
900            shares.clone(),
901        )?;
902        let fitted = Bypass {
903            time: fit.time_background,
904            room: fit.room_background,
905        };
906        let fitted_offsets: Vec<f64> = fit.regions.iter().map(|r| r.timing_offset_us).collect();
907        let mut spread = 0.0;
908        for (q, (r, region)) in fit.regions.iter().zip(&measurement.regions).enumerate() {
909            let used = open.open_counts_per_pixel(&bins, offsets[q], frames);
910            let now = fitted.open_counts_per_pixel(&bins, fitted_offsets[q], frames);
911            for (k, &mu) in r.predicted[0]
912                .iter()
913                .enumerate()
914                .filter(|(_, mu)| **mu > 0.0)
915            {
916                let live = region.open_live.as_ref().map_or(1.0, |live| live[k]);
917                spread += (live * region.pixels * (now[k] - used[k])).powi(2) / mu;
918            }
919        }
920        if !fit.converged || spread <= BOUND || passes == most_passes {
921            if spread > BOUND {
922                fit.converged = false;
923                fit.unconverged.get_or_insert_with(|| {
924                    format!(
925                        "the open-beam fits' time and room backgrounds did not settle in \
926                         {most_passes} fits"
927                    )
928                });
929                fit.covariance = None;
930                fit.unbounded = None;
931                fit.measured_pulls = None;
932                fit.pulse_consistency = None;
933            }
934            return Ok(fit);
935        }
936        if passes >= 2 {
937            intervals
938                .get_or_insert_with(|| fit.regions.iter().map(|r| r.beam.intervals()).collect());
939        }
940        open = fitted;
941        offsets = fitted_offsets;
942    }
943    unreachable!("the passes end at most_passes")
944}
945
946/// The time background's `[C, A, τ, D]` and the room background's `ρ`, which
947/// together give the counts per pixel of a run that bypass the pulse.
948#[derive(Debug, Clone, Copy, PartialEq)]
949pub(crate) struct Bypass {
950    pub(crate) time: [f64; 4],
951    pub(crate) room: f64,
952}
953
954impl Bypass {
955    /// The counts per pixel these numbers put in each bin of the open-beam run
956    /// of `frames` frames, `bins` recorded `late_us` late.
957    pub(crate) fn open_counts_per_pixel(
958        &self,
959        bins: &[(f64, f64)],
960        late_us: f64,
961        frames: f64,
962    ) -> Vec<f64> {
963        let (time, _) = time_counts_per_pixel(&late(bins, late_us), self.time, span_us(bins));
964        time.iter()
965            .zip(bins)
966            .map(|(g, (_, width))| g + self.room * frames * width)
967            .collect()
968    }
969}
970
971/// The open-beam run's frames, 0 without a room background.
972pub(crate) fn open_frames(room: Option<&RoomBackground>) -> f64 {
973    room.map_or(0.0, |room| room.frames[0])
974}
975
976/// The starting value of the measurement's quantity `role`.
977fn starting(measurement: &Measurement, role: Role) -> Result<f64, PipelineError> {
978    let (value, name, range, allowed) = quantity(measurement, role).expect("a quantity");
979    Ok(value.parameter(name, range, &allowed)?.value)
980}
981
982/// `bins` recorded `late_us` late, their starts on the clock they arrive by.
983fn late(bins: &[(f64, f64)], late_us: f64) -> Vec<(f64, f64)> {
984    bins.iter()
985        .map(|&(start, width)| (start - late_us, width))
986        .collect()
987}
988
989pub(crate) fn starting_bypass(measurement: &Measurement) -> Result<Bypass, PipelineError> {
990    let start = |role| starting(measurement, role);
991    Ok(Bypass {
992        time: [
993            start(Role::TimeBackground(0))?,
994            start(Role::TimeBackground(1))?,
995            start(Role::TimeBackground(2))?,
996            start(Role::TimeBackground(3))?,
997        ],
998        room: start(Role::RoomBackground)?,
999    })
1000}
1001
1002pub(crate) struct Starts {
1003    pub(crate) beams: Vec<BeamStart>,
1004    pub(crate) origin_us: f64,
1005    pub(crate) shared_leverage: Option<Vec<f64>>,
1006    pub(crate) bound: f64,
1007    pub(crate) excluded: Vec<Vec<usize>>,
1008}
1009
1010#[derive(Debug, Clone)]
1011pub(crate) struct BeamStart {
1012    pub(crate) beam: BeamSpline,
1013    pub(crate) overdispersion: Option<f64>,
1014    pub(crate) at_limit: bool,
1015}
1016
1017impl From<OpenBeamFit> for BeamStart {
1018    fn from(open: OpenBeamFit) -> Self {
1019        Self {
1020            beam: open.beam,
1021            overdispersion: open.overdispersion,
1022            at_limit: open.at_limit,
1023        }
1024    }
1025}
1026
1027pub(crate) struct Checked<'a> {
1028    shape: Vec<Option<usize>>,
1029    sample_parameters: Vec<FitParameter>,
1030    measured: Vec<(usize, f64, f64)>,
1031    lines: Vec<Lines<'a>>,
1032    instrument: Vec<FitParameter>,
1033    offsets: Vec<f64>,
1034    base: FlightTimeGrid,
1035    resonances_in_span: Vec<Vec<Vec<f64>>>,
1036}
1037
1038pub(crate) fn checked<'a>(
1039    measurement: &'a Measurement,
1040    calibration: &Calibration,
1041) -> Result<Checked<'a>, PipelineError> {
1042    let Measurement {
1043        time_edges_us,
1044        charge_ratio,
1045        regions,
1046        ..
1047    } = measurement;
1048    let invalid = |message: String| Err(PipelineError::InvalidParameter(message));
1049    let materials = || {
1050        regions
1051            .iter()
1052            .enumerate()
1053            .filter_map(|(r, region)| Some((r, region.material.as_ref()?)))
1054    };
1055    if !(charge_ratio.is_finite() && *charge_ratio > 0.0) {
1056        return invalid(format!(
1057            "the charge ratio must be finite and positive, got {charge_ratio}"
1058        ));
1059    }
1060    for range in materials().flat_map(|(_, m)| &m.excluded_ranges) {
1061        range.check()?;
1062    }
1063    // An exponential far slower than the span is nearly a line, which C and D already give.
1064    let [_, _, tau, d] = &measurement.time_background;
1065    let span_us = time_edges_us
1066        .last()
1067        .zip(time_edges_us.first())
1068        .map_or(0.0, |(l, f)| l - f);
1069    let short = match tau {
1070        Value::Known(_) => true,
1071        Value::Within { upper, .. } => *upper <= 0.5 * span_us,
1072        _ => false,
1073    };
1074    if !matches!(d, Value::Known(_)) && !short {
1075        return invalid(format!(
1076            "a fitted time background D needs τ known or within an upper bound of at most half \
1077             the edges' span, {:.6e} µs, or a slow exponential and D trade",
1078            0.5 * span_us
1079        ));
1080    }
1081    if let Some(room) = &measurement.room_background
1082        && !room.frames.iter().all(|f| f.is_finite() && *f > 0.0)
1083    {
1084        return invalid(format!(
1085            "the room background's frames must be finite and positive, got {:?}",
1086            room.frames
1087        ));
1088    }
1089    if let Some(spread) = &measurement.spread {
1090        spread_checked(spread, regions.len())?;
1091        if spread.share != Value::Known(0.0)
1092            && !regions.iter().all(|region| {
1093                matches!(region.timing_offset_us, Value::Known(_))
1094                    && region.timing_offset_us == regions[0].timing_offset_us
1095            })
1096        {
1097            return invalid(
1098                "a detector spread needs every region's timing offset known and the same".into(),
1099            );
1100        }
1101    }
1102    let free = |value: &Value| matches!(value, Value::Fitted(_) | Value::Within { .. });
1103    if let Some(scatter) = &measurement.environment_scatter {
1104        if measurement.spread.is_some() {
1105            return invalid(
1106                "an environment scatter with a detector spread is not supported".into(),
1107            );
1108        }
1109        let active = scatter.fraction != Value::Known(0.0);
1110        if active
1111            && regions.len() > 1
1112            && !regions.iter().all(|r| {
1113                matches!(r.timing_offset_us, Value::Known(_))
1114                    && r.timing_offset_us == regions[0].timing_offset_us
1115            })
1116        {
1117            return invalid(
1118                "environment scatter needs one common known region timing offset".into(),
1119            );
1120        }
1121        match &scatter.source {
1122            ScatterSource::FullDetector if active => {
1123                if regions.len() == 1 && free(&scatter.fraction) {
1124                    return invalid(
1125                        "one full-detector region cannot measure the scatter fraction".into(),
1126                    );
1127                }
1128                if !regions.iter().map(|r| r.pixels).sum::<f64>().is_finite() {
1129                    return invalid("the full detector area must be finite".into());
1130                }
1131            }
1132            ScatterSource::Measured { total, photons } => {
1133                let bins = time_edges_us.len().saturating_sub(1);
1134                for mean in total.iter().chain(photons.iter().flatten()) {
1135                    if mean.len() != bins || !mean.iter().all(|v| v.is_finite() && *v >= 0.0) {
1136                        return invalid(format!(
1137                            "an environment scatter mean needs {bins} finite counts per pixel of 0 or more"
1138                        ));
1139                    }
1140                }
1141                if let Some(photons) = photons {
1142                    if photons
1143                        .iter()
1144                        .flatten()
1145                        .zip(total.iter().flatten())
1146                        .any(|(p, t)| p > t)
1147                    {
1148                        return invalid(
1149                            "the detector mean photon counts exceed its total counts".into(),
1150                        );
1151                    }
1152                } else if active && measurement_has_photons(measurement) {
1153                    return invalid("partial-detector environment scatter with a photon background needs detector-wide mean photon counts".into());
1154                }
1155            }
1156            ScatterSource::FullDetector => {}
1157        }
1158    }
1159    if free(&calibration.t0_us)
1160        && !regions.is_empty()
1161        && regions.iter().all(|region| free(&region.timing_offset_us))
1162    {
1163        return invalid(
1164            "t0 and every region's timing offset are fitted, and they move together: know or \
1165             measure t0 or one region's offset"
1166                .into(),
1167        );
1168    }
1169    if let Some((r, region)) = regions
1170        .iter()
1171        .enumerate()
1172        .find(|(_, region)| !(region.pixels.is_finite() && region.pixels > 0.0))
1173    {
1174        return invalid(format!(
1175            "the pixels of region {r} must be finite and positive, got {}",
1176            region.pixels
1177        ));
1178    }
1179    if let Some(r) = regions.iter().position(|region| {
1180        region.material.is_none()
1181            && [region.capture_gammas, region.in_scatter] != [Value::Known(0.0); 2]
1182    }) {
1183        return invalid(format!(
1184            "region {r} holds no material to capture or scatter neutrons, so its capture gammas \
1185             and in-scatter must be known 0"
1186        ));
1187    }
1188    for (r, material) in materials() {
1189        if material.isotopes.is_empty() {
1190            return invalid(format!("the material of region {r} has no isotopes"));
1191        }
1192        for (i, (isotope, _)) in material.isotopes.iter().enumerate() {
1193            if material.isotopes[..i]
1194                .iter()
1195                .any(|(other, _)| other.za == isotope.za)
1196            {
1197                return invalid(format!(
1198                    "{} is listed twice in region {r}; its densities cannot be told apart",
1199                    isotope.isotope
1200                ));
1201            }
1202            if !finite(isotope) {
1203                return invalid(format!(
1204                    "the resonance data of {} in region {r} are not finite",
1205                    isotope.isotope
1206                ));
1207            }
1208        }
1209        for (k, (i, covariance)) in material.covariances.iter().enumerate() {
1210            let n = 3 * covariance.resonances.len();
1211            let listed = &covariance.resonances;
1212            let placed = material.isotopes.get(*i).is_some_and(|(data, _)| {
1213                !listed.is_empty()
1214                    && listed.iter().enumerate().all(|(x, &[a, b, c])| {
1215                        !listed[..x].contains(&[a, b, c])
1216                            && data
1217                                .ranges
1218                                .get(a)
1219                                .and_then(|range| range.l_groups.get(b))
1220                                .is_some_and(|group| c < group.resonances.len())
1221                    })
1222            });
1223            let matrix = &covariance.covariance;
1224            let sd = |p: usize| matrix[p * n + p].abs().sqrt();
1225            let symmetric = matrix.len() == n * n
1226                && (0..n).all(|p| {
1227                    (0..n).all(|q| {
1228                        let scale = sd(p) * sd(q);
1229                        matrix[p * n + q].is_finite()
1230                            && (matrix[p * n + q] - matrix[q * n + p]).abs() <= 1e-12 * scale
1231                            && (p == q || scale > 0.0 || matrix[p * n + q] == 0.0)
1232                    })
1233                });
1234            let semidefinite = placed
1235                && symmetric
1236                && Mat::<f64>::from_fn(n, n, |p, q| {
1237                    let scale = sd(p) * sd(q);
1238                    if scale > 0.0 {
1239                        matrix[p * n + q] / scale
1240                    } else {
1241                        matrix[p * n + q]
1242                    }
1243                })
1244                .self_adjoint_eigenvalues(Side::Lower)
1245                .is_ok_and(|e| e[0] >= -f64::EPSILON * n as f64 * e[n - 1].max(1.0));
1246            if material.covariances[..k].iter().any(|(j, _)| j == i) || !semidefinite {
1247                return invalid(format!(
1248                    "covariance {k} of region {r} must name an isotope of its material once and \
1249                     distinct resonances it has, with a finite symmetric positive semi-definite \
1250                     matrix over their energies and widths"
1251                ));
1252            }
1253        }
1254    }
1255    let carried: Vec<(usize, u32)> = materials()
1256        .flat_map(|(r, m)| {
1257            m.covariances
1258                .iter()
1259                .map(move |(i, _)| (r, m.isotopes[*i].0.za))
1260        })
1261        .collect();
1262    if materials().any(|(s, m)| {
1263        m.isotopes
1264            .iter()
1265            .any(|(d, _)| carried.iter().any(|&(r, za)| r != s && za == d.za))
1266    }) {
1267        return invalid(
1268            "a resonance covariance is carried for an isotope another region also holds, whose \
1269             counts it would leave out"
1270                .into(),
1271        );
1272    }
1273    if let Some(filter) = &measurement.filter
1274        && filter
1275            .isotopes
1276            .iter()
1277            .any(|(d, _)| carried.iter().any(|&(_, za)| za == d.za))
1278    {
1279        return invalid(
1280            "a resonance covariance is carried for an isotope the filter also holds, whose \
1281             counts it would leave out"
1282                .into(),
1283        );
1284    }
1285    if calibration.pulse.prior.is_some() && materials().any(|(_, m)| !m.covariances.is_empty()) {
1286        return invalid(
1287            "a pulse calibration's prior records no sensitivity to the resonance parameters, so a \
1288             fit under it cannot carry their covariance"
1289                .into(),
1290        );
1291    }
1292    let shape = shape(measurement);
1293    let quantity_roles = roles(&vec![0; regions.len()], &shape);
1294    let sample_parameters = quantity_roles
1295        .iter()
1296        .filter_map(|&role| {
1297            let (value, name, range, allowed) = quantity(measurement, role)?;
1298            Some(value.parameter(name, range, &allowed))
1299        })
1300        .collect::<Result<Vec<FitParameter>, PipelineError>>()?;
1301    let measured: Vec<(usize, f64, f64)> = quantities(measurement, calibration)
1302        .enumerate()
1303        .filter_map(|(offset, (_, value))| match *value {
1304            Value::Measured { value, sd } => Some((offset, value, sd)),
1305            _ => None,
1306        })
1307        .collect();
1308    let lines: Vec<Lines<'_>> = materials()
1309        .map(|(region, material)| {
1310            let temperature = &sample_parameters[quantity_roles
1311                .iter()
1312                .position(|&role| role == Role::Temperature { region })
1313                .expect("a material has a temperature")];
1314            let reach_k = if temperature.fixed {
1315                temperature.value
1316            } else {
1317                temperature.upper
1318            };
1319            let dopplers = material
1320                .isotopes
1321                .iter()
1322                .map(|(isotope, _)| {
1323                    DopplerParams::new(reach_k, isotope.awr).map_err(|e| {
1324                        in_region(region, PipelineError::InvalidParameter(e.to_string()))
1325                    })
1326                })
1327                .collect::<Result<Vec<_>, _>>()?;
1328            Ok(Lines {
1329                region,
1330                isotopes: &material.isotopes,
1331                dopplers,
1332                reach_k,
1333                lattice: material.lattice.as_ref(),
1334                scatters: measurement.regions[region].in_scatter != Value::Known(0.0),
1335            })
1336        })
1337        .collect::<Result<_, PipelineError>>()?;
1338    let instrument = calibration.instrument()?;
1339    validate_pulse_prior(calibration)?;
1340    let start: Vec<f64> = instrument.iter().map(|parameter| parameter.value).collect();
1341    let offsets: Vec<f64> = (0..regions.len())
1342        .map(|region| {
1343            let at = quantity_roles
1344                .iter()
1345                .position(|&role| role == Role::TimingOffset { region })
1346                .expect("every region has a timing offset");
1347            sample_parameters[at].value
1348        })
1349        .collect();
1350    let starts: Vec<f64> = offsets.iter().map(|offset| start[0] + offset).collect();
1351    let base = FlightTimeGrid::spanning(
1352        time_edges_us,
1353        span(&starts),
1354        start[1],
1355        &calibration.pulse.at(&start[2..])?,
1356    )?;
1357    calibrated_lines(&lines, &calibration.pulse, time_edges_us, &starts, start[1])?;
1358    let resonances_in_span = in_span(&lines, &base)?;
1359    Ok(Checked {
1360        shape,
1361        sample_parameters,
1362        measured,
1363        lines,
1364        instrument,
1365        offsets,
1366        base,
1367        resonances_in_span,
1368    })
1369}
1370
1371/// The most pieces an excluded range is split into to bound its arrival times.
1372const MOST_RANGE_PIECES: u32 = 4096;
1373
1374pub(crate) fn excluded_bins(
1375    time_edges_us: &[f64],
1376    material: Option<&Material>,
1377    numbers: &[f64],
1378    storage_span: Option<(f64, f64)>,
1379) -> Vec<usize> {
1380    let laws = laws(&numbers[2..], storage_span);
1381    let tail = laws
1382        .detector_tail
1383        .map_or(0.0, |tail| tail.fraction * tail.decay_us);
1384    let flight = |e: f64| numbers[0] + TOF_FACTOR * numbers[1] / e.sqrt() + tail;
1385    let arrival =
1386        |e: f64| flight(e) + 3.0 / laws.alpha.eval(e) + laws.r.eval(e) / laws.beta.eval(e);
1387    // Each term of the arrival time is monotonic in the energy, so its values at two
1388    // energies bound it between them, and the sums of the bounds hold every arrival.
1389    let bound = |low: f64, high: f64| {
1390        let ends = |f: &dyn Fn(f64) -> f64| {
1391            let (a, b) = (f(low), f(high));
1392            (a.min(b), a.max(b))
1393        };
1394        let rise = ends(&|e| 3.0 / laws.alpha.eval(e));
1395        let (r, beta) = (ends(&|e| laws.r.eval(e)), ends(&|e| laws.beta.eval(e)));
1396        (
1397            flight(high) + rise.0 + (r.0 / beta.0).min(r.0 / beta.1),
1398            flight(low) + rise.1 + (r.1 / beta.0).max(r.1 / beta.1),
1399        )
1400    };
1401    let reached = |(first, last): (f64, f64)| -> Vec<usize> {
1402        (0..time_edges_us.len() - 1)
1403            .filter(|&k| time_edges_us[k] < last && first < time_edges_us[k + 1])
1404            .collect()
1405    };
1406    let widest = |spans: &mut dyn Iterator<Item = (f64, f64)>| {
1407        spans.fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (lo, hi)| {
1408            (a.min(lo), b.max(hi))
1409        })
1410    };
1411    let mut bins: Vec<usize> = material
1412        .into_iter()
1413        .flat_map(|m| &m.excluded_ranges)
1414        .flat_map(|range| {
1415            let (low, high) = range.energy_ev;
1416            // The arrivals fill the interval between their extrema.  The pieces halve until their
1417            // bounds and end arrivals agree on the bins; at the limit the bounds decide.
1418            let mut pieces = 1;
1419            loop {
1420                let knot = |i: u32| low + (high - low) * f64::from(i) / f64::from(pieces);
1421                let sampled = widest(&mut (0..=pieces).map(|i| {
1422                    let t = arrival(knot(i));
1423                    (t, t)
1424                }));
1425                let bounded = widest(&mut (0..pieces).map(|i| bound(knot(i), knot(i + 1))));
1426                let out = reached(bounded);
1427                if out == reached(sampled) || pieces == MOST_RANGE_PIECES {
1428                    break out;
1429                }
1430                pieces *= 2;
1431            }
1432        })
1433        .collect();
1434    bins.sort_unstable();
1435    bins.dedup();
1436    bins
1437}
1438
1439type Slopes = (Vec<Vec<f64>>, FlatMatrix);
1440
1441fn nuclear_slopes(
1442    regions: &[Region],
1443    model: &Recorded<'_, RegionsModel>,
1444    dispersion: &[f64],
1445    parameters: &ParameterSet,
1446) -> Result<Option<Slopes>, PipelineError> {
1447    let (params, free) = (parameters.all_values(), parameters.free_indices());
1448    let mu = model.evaluate(&params)?;
1449    let jacobian = model
1450        .analytical_jacobian(&params, &free, &mu)
1451        .expect("the counts model has an analytical Jacobian");
1452    let mut picked: Vec<(&ResonanceCovariance, usize, Vec<f64>)> = Vec::new();
1453    for (r, material) in regions
1454        .iter()
1455        .enumerate()
1456        .filter_map(|(r, region)| Some((r, region.material.as_ref()?)))
1457    {
1458        for (i, covariance) in &material.covariances {
1459            let data = &material.isotopes[*i].0;
1460            let n = 3 * covariance.resonances.len();
1461            for p in (0..n).filter(|p| covariance.covariance[p * n + p] > 0.0) {
1462                let [a, b, c] = covariance.resonances[p / 3];
1463                let h = 0.1 * covariance.covariance[p * n + p].sqrt();
1464                let shifted = |by: f64| {
1465                    let mut copy = data.clone();
1466                    let resonance = &mut copy.ranges[a].l_groups[b].resonances[c];
1467                    *[&mut resonance.energy, &mut resonance.gn, &mut resonance.gg][p % 3] += by;
1468                    copy
1469                };
1470                let slope =
1471                    model
1472                        .model
1473                        .resonance_slope(&params, r, *i, [&shifted(h), &shifted(-h)], h)?;
1474                let cross = (0..free.len())
1475                    .map(|j| {
1476                        slope
1477                            .iter()
1478                            .enumerate()
1479                            .filter(|(k, _)| mu[*k] > 0.0)
1480                            .map(|(k, c)| {
1481                                jacobian.get(k, j) * c * model.live[k] / (mu[k] * dispersion[k])
1482                            })
1483                            .sum()
1484                    })
1485                    .collect();
1486                picked.push((covariance, p, cross));
1487            }
1488        }
1489    }
1490    let width = picked.len();
1491    if width == 0 {
1492        return Ok(None);
1493    }
1494    let mut prior = FlatMatrix::zeros(width, width);
1495    for (a, (first, p, _)) in picked.iter().enumerate() {
1496        for (b, (second, q, _)) in picked.iter().enumerate() {
1497            if std::ptr::eq(*first, *second) {
1498                *prior.get_mut(a, b) = first.covariance[p * 3 * first.resonances.len() + q];
1499            }
1500        }
1501    }
1502    Ok(Some((
1503        picked.into_iter().map(|(_, _, cross)| cross).collect(),
1504        prior,
1505    )))
1506}
1507
1508fn sandwich(conditional: &FlatMatrix, slopes: &Slopes) -> FlatMatrix {
1509    let (crosses, prior) = slopes;
1510    let (free, width) = (conditional.nrows, crosses.len());
1511    let resolved: Vec<bool> = (0..free)
1512        .map(|i| conditional.get(i, i).is_finite())
1513        .collect();
1514    let sensitivity: Vec<Vec<f64>> = (0..free)
1515        .map(|i| {
1516            crosses
1517                .iter()
1518                .map(|cross| {
1519                    if !resolved[i] {
1520                        return f64::NAN;
1521                    }
1522                    -(0..free)
1523                        .filter(|&j| resolved[j])
1524                        .map(|j| conditional.get(i, j) * cross[j])
1525                        .sum::<f64>()
1526                })
1527                .collect()
1528        })
1529        .collect();
1530    let weighted: Vec<Vec<f64>> = sensitivity
1531        .iter()
1532        .map(|sx| {
1533            (0..width)
1534                .map(|b| (0..width).map(|a| sx[a] * prior.get(a, b)).sum())
1535                .collect()
1536        })
1537        .collect();
1538    let mut term = FlatMatrix::zeros(free, free);
1539    for (x, wx) in weighted.iter().enumerate() {
1540        for (y, sy) in sensitivity.iter().enumerate() {
1541            *term.get_mut(x, y) = wx.iter().zip(sy).map(|(w, s)| w * s).sum();
1542        }
1543    }
1544    term
1545}
1546
1547/// The earliest and the latest of `starts`.
1548fn span(starts: &[f64]) -> (f64, f64) {
1549    starts
1550        .iter()
1551        .fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), &t| {
1552            (low.min(t), high.max(t))
1553        })
1554}
1555
1556fn calibrated_lines(
1557    lines: &[Lines<'_>],
1558    pulse: &Pulse,
1559    time_edges_us: &[f64],
1560    starts: &[f64],
1561    flight_path_m: f64,
1562) -> Result<(), PipelineError> {
1563    for lines in lines {
1564        if let Some(((low, high), line)) = pulse.line_span_ev.zip(pulse.uncalibrated_line(
1565            lines.isotopes,
1566            time_edges_us,
1567            starts[lines.region],
1568            flight_path_m,
1569        )) {
1570            return Err(PipelineError::InvalidParameter(format!(
1571                "region {} has a resonance at {line} eV, outside the {low}–{high} eV of the \
1572                 resonances the pulse was calibrated on",
1573                lines.region
1574            )));
1575        }
1576    }
1577    Ok(())
1578}
1579
1580fn in_span(
1581    lines: &[Lines<'_>],
1582    grid: &FlightTimeGrid,
1583) -> Result<Vec<Vec<Vec<f64>>>, PipelineError> {
1584    let energies = grid.energies_ev();
1585    let span_ev = (energies[energies.len() - 1], energies[0]);
1586    lines
1587        .iter()
1588        .map(|lines| {
1589            if lines.scatters {
1590                let lowest = span_ev.0
1591                    * lines
1592                        .isotopes
1593                        .iter()
1594                        .map(|(isotope, _)| lowest_exit_ratio(isotope.awr))
1595                        .fold(1.0, f64::min);
1596                if let Some((isotope, e)) = lines.isotopes.iter().find_map(|(isotope, _)| {
1597                    resonance_center_energies(&[isotope])
1598                        .into_iter()
1599                        .find(|e| (lowest..span_ev.0).contains(e))
1600                        .map(|e| (isotope, e))
1601                }) {
1602                    return Err(PipelineError::InvalidParameter(format!(
1603                        "the in-scatter of region {} leaves with energies down to {lowest:.6e} \
1604                         eV, below the flight-time grid's lowest {:.6e} eV, and {} has a \
1605                         resonance at {e:.6e} eV there",
1606                        lines.region, span_ev.0, isotope.isotope
1607                    )));
1608                }
1609            }
1610            lines
1611                .isotopes
1612                .iter()
1613                .zip(&lines.dopplers)
1614                .map(|((isotope, _), doppler)| {
1615                    let read = match lines.lattice {
1616                        Some(spectrum) => {
1617                            let reach = |e: f64| spectrum.reach_ev(e, lines.reach_k, isotope.awr);
1618                            (span_ev.0 - reach(span_ev.0), span_ev.1 + reach(span_ev.1))
1619                        }
1620                        None => (
1621                            (span_ev.0.sqrt() - SUPPORT_X * doppler.u())
1622                                .max(0.0)
1623                                .powi(2),
1624                            (span_ev.1.sqrt() + SUPPORT_X * doppler.u()).powi(2),
1625                        ),
1626                    };
1627                    if !isotope.ranges.iter().any(|range| {
1628                        range.is_evaluable()
1629                            && range.energy_low <= read.0
1630                            && read.1 <= range.energy_high
1631                    }) {
1632                        return Err(PipelineError::InvalidParameter(format!(
1633                            "the Doppler-broadened cross section of {} in region {} reads \
1634                             {:.6e}–{:.6e} eV, which no single one of its evaluated resolved \
1635                             ranges holds",
1636                            isotope.isotope, lines.region, read.0, read.1
1637                        )));
1638                    }
1639                    Ok(resonance_center_energies(&[isotope])
1640                        .into_iter()
1641                        .filter(|e| (span_ev.0..=span_ev.1).contains(e))
1642                        .collect())
1643                })
1644                .collect()
1645        })
1646        .collect()
1647}
1648
1649pub(crate) enum BeamStarts<'a> {
1650    Given(&'a Starts),
1651    OpenFitsAt(Bypass, Option<Vec<usize>>, Vec<f64>),
1652}
1653
1654/// The spread's shares `F_rq` between the measurement's regions, or `None`
1655/// without a spread.
1656pub(crate) fn spread_shares(
1657    measurement: &Measurement,
1658) -> Result<Option<Arc<Vec<Vec<f64>>>>, PipelineError> {
1659    let Some(spread) = &measurement.spread else {
1660        return Ok(None);
1661    };
1662    spread_checked(spread, measurement.regions.len())?;
1663    Ok(Some(Arc::new(region_shares(
1664        &spread.kernel,
1665        spread.grid,
1666        &spread.cells,
1667    ))))
1668}
1669
1670fn measurement_has_photons(m: &Measurement) -> bool {
1671    m.time_background
1672        .iter()
1673        .enumerate()
1674        .any(|(i, value)| Role::TimeBackground(i).photon_amplitude() && *value != Value::Known(0.0))
1675        || m.regions
1676            .iter()
1677            .any(|r| r.capture_gammas != Value::Known(0.0))
1678}
1679
1680struct Furnace {
1681    source: NeutronSource,
1682    local_photons: bool,
1683}
1684
1685enum NeutronSource {
1686    AreaFractions(Vec<f64>),
1687    Measured(Vec<f64>),
1688}
1689
1690impl Furnace {
1691    fn new(m: &Measurement) -> Option<Arc<Self>> {
1692        let scatter = m.environment_scatter.as_ref()?;
1693        if scatter.fraction == Value::Known(0.0) {
1694            return None;
1695        }
1696        let source = match &scatter.source {
1697            ScatterSource::FullDetector => {
1698                let area: f64 = m.regions.iter().map(|r| r.pixels).sum();
1699                NeutronSource::AreaFractions(m.regions.iter().map(|r| r.pixels / area).collect())
1700            }
1701            ScatterSource::Measured { total, photons } => {
1702                let mean: Vec<_> = total
1703                    .iter()
1704                    .enumerate()
1705                    .flat_map(|(run, bins)| {
1706                        bins.iter()
1707                            .enumerate()
1708                            .map(move |(k, t)| t - photons.as_ref().map_or(0.0, |p| p[run][k]))
1709                    })
1710                    .collect();
1711                NeutronSource::Measured(mean)
1712            }
1713        };
1714        Some(Arc::new(Self {
1715            source,
1716            local_photons: measurement_has_photons(m),
1717        }))
1718    }
1719
1720    /// Gain minus loss for a unit scattered fraction, or its slope for a fixed measured mean.
1721    fn change(&self, local: &[f64], derivative: bool, regions: &[Place]) -> Vec<f64> {
1722        match &self.source {
1723            NeutronSource::AreaFractions(areas) => {
1724                let bins = local.len() / areas.len();
1725                let mut total = vec![0.0; bins];
1726                for region in local.chunks_exact(bins) {
1727                    for (sum, v) in total.iter_mut().zip(region) {
1728                        *sum += v;
1729                    }
1730                }
1731                areas
1732                    .iter()
1733                    .zip(local.chunks_exact(bins))
1734                    .flat_map(|(area, region)| {
1735                        total.iter().zip(region).map(move |(t, v)| area * t - v)
1736                    })
1737                    .collect()
1738            }
1739            NeutronSource::Measured(mean) if !derivative => regions
1740                .iter()
1741                .zip(local.chunks_exact(mean.len()))
1742                .flat_map(|(region, bins)| {
1743                    mean.iter()
1744                        .zip(bins)
1745                        .map(move |(m, v)| region.pixels * m - v)
1746                })
1747                .collect(),
1748            NeutronSource::Measured(_) => local.iter().map(|v| -v).collect(),
1749        }
1750    }
1751}
1752
1753/// The fit of `measurement` from `beam_starts`, with the spread's shares
1754/// `mixing` from [`spread_shares`].
1755pub(crate) fn fit_counts_answer(
1756    measurement: &Measurement,
1757    calibration: &Calibration,
1758    beam_starts: BeamStarts<'_>,
1759    mixing: Option<Arc<Vec<Vec<f64>>>>,
1760) -> Result<(CountsFit, Answer), PipelineError> {
1761    let starts = match beam_starts {
1762        BeamStarts::Given(starts) => Some(starts),
1763        BeamStarts::OpenFitsAt(..) => None,
1764    };
1765    let Measurement {
1766        time_edges_us,
1767        charge_ratio,
1768        regions,
1769        ..
1770    } = measurement;
1771    let Checked {
1772        shape,
1773        sample_parameters,
1774        measured,
1775        lines,
1776        instrument,
1777        offsets,
1778        mut base,
1779        mut resonances_in_span,
1780    } = checked(measurement, calibration)?;
1781    let scattered = Furnace::new(measurement);
1782    let pulse = &calibration.pulse;
1783    let start: Vec<f64> = instrument.iter().map(|parameter| parameter.value).collect();
1784    let beam_origin_us = starts.map_or(start[0], |starts| starts.origin_us);
1785    let frames = measurement
1786        .room_background
1787        .map_or([0.0; 2], |room| room.frames);
1788    let spreading = measurement
1789        .spread
1790        .as_ref()
1791        .is_some_and(|spread| spread.share != Value::Known(0.0));
1792    let bins = time_edges_us.len() - 1;
1793    if let Some(starts) = starts {
1794        assert_eq!(starts.beams.len(), regions.len(), "one beam per region");
1795        if let Some(leverage) = &starts.shared_leverage {
1796            assert_eq!(leverage.len(), regions.len(), "one leverage per region");
1797        }
1798    }
1799    let excluded_at = |numbers: &[f64], offsets: &[f64]| -> Vec<Vec<usize>> {
1800        let own: Vec<Vec<usize>> = regions
1801            .iter()
1802            .zip(offsets)
1803            .map(|(region, offset)| {
1804                let mut numbers = numbers.to_vec();
1805                numbers[0] += offset;
1806                excluded_bins(
1807                    time_edges_us,
1808                    region.material.as_ref(),
1809                    &numbers,
1810                    calibration.pulse.storage_span(),
1811                )
1812            })
1813            .collect();
1814        match &mixing {
1815            Some(shares) if spreading => shares
1816                .iter()
1817                .enumerate()
1818                .map(|(r, from)| {
1819                    let mut out: Vec<usize> = own
1820                        .iter()
1821                        .enumerate()
1822                        .filter(|&(q, _)| q == r || from[q] > 0.0)
1823                        .flat_map(|(_, out)| out.iter().copied())
1824                        .collect();
1825                    out.sort_unstable();
1826                    out.dedup();
1827                    out
1828                })
1829                .collect(),
1830            _ if scattered
1831                .as_ref()
1832                .is_some_and(|f| matches!(f.source, NeutronSource::AreaFractions(_))) =>
1833            {
1834                let mut all: Vec<_> = own.into_iter().flatten().collect();
1835                all.sort_unstable();
1836                all.dedup();
1837                vec![all; regions.len()]
1838            }
1839            _ => own,
1840        }
1841    };
1842    let dispersion_of = |excluded: &[Vec<usize>], weights: &[f64]| -> Vec<f64> {
1843        let mut dispersion: Vec<f64> = (0..2 * regions.len() * bins)
1844            .map(|k| weights[k / bins])
1845            .collect();
1846        for (r, out) in excluded.iter().enumerate() {
1847            for &k in out {
1848                dispersion[(2 * r + 1) * bins + k] = f64::INFINITY;
1849            }
1850        }
1851        dispersion
1852    };
1853    let mut excluded = starts.map_or_else(|| excluded_at(&start, &offsets), |s| s.excluded.clone());
1854    let mut live = Vec::with_capacity(2 * regions.len() * bins);
1855    for (r, region) in regions.iter().enumerate() {
1856        let checked = || -> Result<[Vec<f64>; 2], PipelineError> {
1857            validate_counts("open-beam", &region.open_counts, bins)?;
1858            validate_counts("sample", &region.sample_counts, bins)?;
1859            Ok([
1860                validate_live("open-beam", region.open_live.as_deref(), bins)?,
1861                validate_live("sample", region.sample_live.as_deref(), bins)?,
1862            ])
1863        };
1864        live.extend(checked().map_err(|e| in_region(r, e))?.concat());
1865    }
1866
1867    let filter_start = starting(measurement, Role::Filter)?;
1868    let filter = measurement.filter.as_ref().map(|f| (f, filter_start));
1869    let opens: Vec<BeamStart> = match beam_starts {
1870        BeamStarts::Given(starts) => starts.beams.clone(),
1871        BeamStarts::OpenFitsAt(numbers, ref intervals, ref offsets) => regions
1872            .iter()
1873            .enumerate()
1874            .map(|(r, region)| {
1875                let per_pixel = numbers.open_counts_per_pixel(
1876                    &starts_and_widths_us(time_edges_us),
1877                    offsets[r],
1878                    open_frames(measurement.room_background.as_ref()),
1879                );
1880                let known: Vec<f64> = per_pixel.iter().map(|g| region.pixels * g).collect();
1881                let open = open_beam_with_intervals(
1882                    time_edges_us,
1883                    &region.open_counts,
1884                    calibration,
1885                    Some(&live[2 * r * bins..(2 * r + 1) * bins]),
1886                    Some(&known),
1887                    intervals.as_ref().map(|chosen| chosen[r]),
1888                    filter,
1889                )
1890                .map_err(|e| in_region(r, e))?;
1891                Ok(BeamStart::from(open))
1892            })
1893            .collect::<Result<_, PipelineError>>()?,
1894    };
1895    let beams: Vec<BeamSpline> = opens.iter().map(|open| open.beam.clone()).collect();
1896    let sizes: Vec<usize> = beams.iter().map(|beam| beam.coefficients().len()).collect();
1897    let pixels: Vec<f64> = regions.iter().map(|region| region.pixels).collect();
1898    let switches: Vec<[bool; 2]> = regions
1899        .iter()
1900        .map(|region| {
1901            [region.capture_gammas, region.in_scatter].map(|value| value != Value::Known(0.0))
1902        })
1903        .collect();
1904    let mut layout = Layout::new(roles(&sizes, &shape), &pixels, &switches);
1905    layout.storage_span = calibration.pulse.storage_span();
1906    let layout = Arc::new(layout);
1907    let mut parameters = ParameterSet::new(
1908        beams
1909            .iter()
1910            .enumerate()
1911            .flat_map(|(r, beam)| {
1912                beam.coefficients()
1913                    .iter()
1914                    .enumerate()
1915                    .map(move |(i, &c)| FitParameter {
1916                        lower: beam.floor(),
1917                        ..FitParameter::unbounded(format!("beam {i} of region {r}"), c)
1918                    })
1919            })
1920            .chain(sample_parameters)
1921            .chain(instrument)
1922            .collect(),
1923    );
1924    let lattices: Vec<Option<PhononSpectrum>> = regions
1925        .iter()
1926        .map(|region| region.material.as_ref().and_then(|m| m.lattice.clone()))
1927        .collect();
1928    let resonances: Vec<Arc<[ResonanceData]>> = regions
1929        .iter()
1930        .map(|region| {
1931            region
1932                .material
1933                .iter()
1934                .flat_map(|material| material.isotopes.iter().map(|(data, _)| data.clone()))
1935                .collect()
1936        })
1937        .collect();
1938    let observed: Vec<f64> = regions
1939        .iter()
1940        .flat_map(|region| region.open_counts.iter().chain(&region.sample_counts))
1941        .copied()
1942        .collect();
1943    let calibrated_parameters: Vec<usize> = pulse
1944        .prior
1945        .iter()
1946        .flat_map(|prior| prior.numbers.iter().map(|n| layout.pulse + n))
1947        .collect();
1948    let pulse_prior = pulse
1949        .prior
1950        .as_ref()
1951        .map(|prior| Prior::correlated(&calibrated_parameters, &prior.mean, &prior.covariance))
1952        .transpose()?;
1953    let priors: Vec<Prior> = measured
1954        .iter()
1955        .map(|&(offset, mean, sd)| Prior::measured(layout.quantities + offset, mean, sd))
1956        .chain(pulse_prior.clone())
1957        .collect();
1958    let half_maximum = 2.0 * std::f64::consts::LN_2.sqrt();
1959    let narrowest_us = |grid: &FlightTimeGrid,
1960                        resonances_in_span: &[Vec<Vec<f64>>],
1961                        params: &[f64]|
1962     -> Result<f64, PipelineError> {
1963        let clock = TOF_FACTOR * grid.flight_path_m();
1964        let mut narrowest = f64::INFINITY;
1965        for (lines, energies) in lines.iter().zip(resonances_in_span) {
1966            let temperature_k = params[layout.regions[lines.region]
1967                .temperature
1968                .expect("a material has a temperature")];
1969            for ((isotope, _), energies) in lines.isotopes.iter().zip(energies) {
1970                let effective_k = lines
1971                    .lattice
1972                    .map_or(temperature_k, |s| s.effective_temperature_k(temperature_k));
1973                let doppler = DopplerParams::new(effective_k, isotope.awr)
1974                    .map_err(|e| PipelineError::InvalidParameter(e.to_string()))?;
1975                for &energy in energies {
1976                    let width_ev = half_maximum * doppler.doppler_width(energy);
1977                    narrowest = narrowest.min(clock / energy.sqrt() * width_ev / (2.0 * energy));
1978                }
1979            }
1980        }
1981        if let Some(filter) = &measurement.filter {
1982            let energies = grid.energies_ev();
1983            let span_ev = energies[energies.len() - 1]..=energies[0];
1984            for (isotope, _) in &filter.isotopes {
1985                let doppler = DopplerParams::new(filter.temperature_k, isotope.awr)
1986                    .map_err(|e| PipelineError::InvalidParameter(e.to_string()))?;
1987                for energy in resonance_center_energies(&[isotope]) {
1988                    if span_ev.contains(&energy) {
1989                        let width_ev = half_maximum * doppler.doppler_width(energy);
1990                        narrowest =
1991                            narrowest.min(clock / energy.sqrt() * width_ev / (2.0 * energy));
1992                    }
1993                }
1994            }
1995        }
1996        Ok(narrowest)
1997    };
1998    let first_grid = |grid: &FlightTimeGrid,
1999                      resonances_in_span: &[Vec<Vec<f64>>],
2000                      params: &[f64]|
2001     -> Result<(Arc<FlightTimeGrid>, usize), PipelineError> {
2002        let rule_us = 0.5 * narrowest_us(grid, resonances_in_span, params)?;
2003        let mut first = grid.clone();
2004        let mut halvings = 0;
2005        while first.step_us() > rule_us {
2006            first = first.halved()?;
2007            halvings += 1;
2008        }
2009        Ok((Arc::new(first), halvings))
2010    };
2011    let covering = |grid: &FlightTimeGrid, params: &[f64]| -> Result<bool, PipelineError> {
2012        let pulse = laws(&params[layout.pulse..], layout.storage_span);
2013        let (first, last) = span(&layout.starts(params));
2014        let covers = |t0_us: f64| grid.covers(t0_us, params[layout.flight_path], &pulse);
2015        Ok(covers(first)? && covers(last)?)
2016    };
2017    let starting: Vec<f64> = parameters.params.iter().map(|p| p.value).collect();
2018    let mut first = first_grid(&base, &resonances_in_span, &starting)?;
2019    let mut weights: Vec<f64> = opens
2020        .iter()
2021        .flat_map(|open| [open.overdispersion.unwrap_or(1.0); 2])
2022        .collect();
2023    let mut sample_measured = vec![false; regions.len()];
2024    let mut noise_bins: Option<Vec<Vec<usize>>> = None;
2025    let mut passes = 0;
2026    let (fit, rule_halvings, overdispersions, unsettled) = loop {
2027        passes += 1;
2028        let dispersion = dispersion_of(&excluded, &weights);
2029        let fit = fit_on_halved_grids(
2030            &first.0,
2031            &mut parameters,
2032            &observed,
2033            &dispersion,
2034            &priors,
2035            |grid| {
2036                Ok(Recorded {
2037                    model: RegionsModel::new(
2038                        grid,
2039                        &beams,
2040                        &resonances,
2041                        (*charge_ratio, frames),
2042                        beam_origin_us,
2043                        &layout,
2044                    )
2045                    .lattices(&lattices)
2046                    .spread(mixing.clone())
2047                    .environment(scattered.clone())
2048                    .filtered(measurement.filter.as_ref())?,
2049                    live: &live,
2050                })
2051            },
2052            |spread, grid, params| {
2053                Ok(spread <= starts.map_or(BOUND, |starts| starts.bound)
2054                    || !covering(grid, params)?)
2055            },
2056        )?;
2057        let fitted = |index: usize| fit.result.params[index];
2058        let noise_bins = noise_bins.get_or_insert_with(|| {
2059            (0..regions.len())
2060                .map(|r| counted(&fit, (2 * r + 1) * bins..(2 * r + 2) * bins))
2061                .collect()
2062        });
2063        let samples: Vec<Option<f64>> = noise_bins
2064            .iter()
2065            .enumerate()
2066            .map(|(r, counted)| {
2067                let weighted: Vec<usize> = counted
2068                    .iter()
2069                    .copied()
2070                    .filter(|&k| dispersion[k].is_finite())
2071                    .collect();
2072                overdispersion(
2073                    &observed,
2074                    &fit,
2075                    &weighted,
2076                    starts
2077                        .and_then(|starts| starts.shared_leverage.as_ref())
2078                        .map_or(0.0, |extra| extra[r]),
2079                )
2080            })
2081            .collect();
2082        let next: Vec<f64> = samples
2083            .iter()
2084            .enumerate()
2085            .map(|(r, sample)| sample.unwrap_or(weights[2 * r]))
2086            .collect();
2087        let each_settled: Vec<bool> = next
2088            .iter()
2089            .enumerate()
2090            .map(|(r, next)| (next / weights[2 * r + 1] - 1.0).abs() <= SETTLED_OVERDISPERSION)
2091            .collect();
2092        let at_fit = starts.map_or_else(
2093            || {
2094                excluded_at(
2095                    &[fitted(layout.t0), fitted(layout.flight_path)]
2096                        .into_iter()
2097                        .chain(fit.result.params[layout.pulse..].iter().copied())
2098                        .collect::<Vec<f64>>(),
2099                    &layout
2100                        .regions
2101                        .iter()
2102                        .map(|place| fitted(place.offset))
2103                        .collect::<Vec<f64>>(),
2104                )
2105            },
2106            |s| s.excluded.clone(),
2107        );
2108        let resolved = 2.0 * fit.step_us
2109            <= 0.5 * narrowest_us(&base, &resonances_in_span, &fit.result.params)?;
2110        let covered = fit.converged && covering(&fit.coarse, &fit.result.params)?;
2111        let unsettled = [
2112            (
2113                each_settled.iter().all(|&s| s),
2114                "a sample run's overdispersion still changes by more than 1%",
2115            ),
2116            (
2117                at_fit == excluded,
2118                "the bins left out at the fit are not the ones the fit left out",
2119            ),
2120            (
2121                resolved,
2122                "the grid is wider than its rule at the fitted temperatures",
2123            ),
2124            (
2125                covered,
2126                "the grid's flight times miss some that the fitted t0, flight path and pulse need",
2127            ),
2128        ]
2129        .into_iter()
2130        .find_map(|(met, rule)| (!met).then_some(rule));
2131        if !fit.converged || unsettled.is_none() || passes == MOST_PASSES {
2132            let weighted: Vec<[Option<f64>; 2]> = (0..regions.len())
2133                .map(|r| {
2134                    [
2135                        opens[r].overdispersion,
2136                        (sample_measured[r] || (each_settled[r] && samples[r].is_some()))
2137                            .then_some(weights[2 * r + 1]),
2138                    ]
2139                })
2140                .collect();
2141            break (fit, first.1, weighted, unsettled);
2142        }
2143        if covered {
2144            let resumed = (Arc::clone(&fit.coarse), first.1 + fit.halvings - 1);
2145            first = [
2146                first_grid(&base, &resonances_in_span, &fit.result.params)?,
2147                resumed,
2148            ]
2149            .into_iter()
2150            .min_by(|a, b| a.0.step_us().total_cmp(&b.0.step_us()))
2151            .expect("two grids");
2152        } else {
2153            base = FlightTimeGrid::spanning(
2154                time_edges_us,
2155                span(&layout.starts(&fit.result.params)),
2156                fitted(layout.flight_path),
2157                &calibration.pulse.at(&fit.result.params[layout.pulse..])?,
2158            )?;
2159            resonances_in_span = in_span(&lines, &base)?;
2160            first = first_grid(&base, &resonances_in_span, &fit.result.params)?;
2161        }
2162        for (r, sample) in samples.iter().enumerate() {
2163            weights[2 * r + 1] = next[r];
2164            sample_measured[r] = sample.is_some();
2165        }
2166        excluded = at_fit;
2167    };
2168    let dispersion = dispersion_of(&excluded, &weights);
2169    let unconverged = fit
2170        .unconverged
2171        .clone()
2172        .or_else(|| unsettled.map(|rule| format!("after {MOST_PASSES} fits {rule}")));
2173    let converged = unconverged.is_none();
2174    if converged {
2175        calibrated_lines(
2176            &lines,
2177            pulse,
2178            time_edges_us,
2179            &layout.starts(&fit.result.params),
2180            fit.result.params[layout.flight_path],
2181        )?;
2182    }
2183
2184    if let Some((k, (&counts, &predicted))) =
2185        observed
2186            .iter()
2187            .zip(&fit.predicted)
2188            .enumerate()
2189            .find(|(k, (y, mu))| {
2190                !mu.is_finite()
2191                    || **mu < 0.0
2192                    || (dispersion[*k].is_finite() && **y > 0.0 && **mu < NEGLIGIBLE_PREDICTION)
2193            })
2194    {
2195        return Err(PipelineError::UnmodelledCounts {
2196            region: k / (2 * bins),
2197            run: ["open-beam", "sample"][(k / bins) % 2],
2198            bin: k % bins,
2199            counts,
2200            predicted,
2201        });
2202    }
2203
2204    let carried = regions
2205        .iter()
2206        .flat_map(|region| &region.material)
2207        .any(|m| !m.covariances.is_empty());
2208    let slopes = if converged && carried && fit.result.covariance.is_some() {
2209        let model = Recorded {
2210            model: RegionsModel::new(
2211                &fit.fine,
2212                &beams,
2213                &resonances,
2214                (*charge_ratio, frames),
2215                beam_origin_us,
2216                &layout,
2217            )
2218            .lattices(&lattices)
2219            .spread(mixing.clone())
2220            .environment(scattered.clone())
2221            .filtered(measurement.filter.as_ref())?,
2222            live: &live,
2223        };
2224        nuclear_slopes(regions, &model, &dispersion, &parameters)?
2225    } else {
2226        None
2227    };
2228    let carried_with = |c: Option<&FlatMatrix>| Some(sandwich(c?, slopes.as_ref()?));
2229    let nuclear = carried_with(fit.result.covariance.as_ref());
2230    let unbounded_nuclear = carried_with(fit.result.unbounded.as_ref().map(|u| &u.covariance));
2231    let (t_low, t_high) = TEMPERATURE_BOUNDS_K;
2232    let free = parameters.free_indices();
2233    let on_edge = layout
2234        .regions
2235        .iter()
2236        .filter_map(|region| region.temperature)
2237        .any(|t| free.contains(&t) && [t_low, t_high].contains(&fit.result.params[t]));
2238    let sample_quantities: Vec<usize> = (0..free.len())
2239        .filter(|&p| free[p] >= layout.quantities)
2240        .collect();
2241    let block = |full: &FlatMatrix| {
2242        let size = sample_quantities.len();
2243        let mut block = FlatMatrix::zeros(size, size);
2244        for (a, &p) in sample_quantities.iter().enumerate() {
2245            for (b, &q) in sample_quantities.iter().enumerate() {
2246                *block.get_mut(a, b) = if on_edge { f64::NAN } else { full.get(p, q) };
2247            }
2248        }
2249        block
2250    };
2251    let covariance = fit
2252        .result
2253        .covariance
2254        .as_ref()
2255        .filter(|_| converged)
2256        .map(|conditional| {
2257            let mut full = conditional.clone();
2258            for (entry, added) in full
2259                .data
2260                .iter_mut()
2261                .zip(nuclear.iter().flat_map(|n| &n.data))
2262            {
2263                *entry += added;
2264            }
2265            block(&full)
2266        });
2267    let unbounded = fit
2268        .result
2269        .unbounded
2270        .as_ref()
2271        .filter(|_| converged)
2272        .map(|full| Unbounded {
2273            mean: sample_quantities
2274                .iter()
2275                .map(|&p| if on_edge { f64::NAN } else { full.mean[p] })
2276                .collect(),
2277            covariance: block(&full.covariance),
2278        });
2279    let params = &fit.result.params;
2280    let on_bound: Vec<bool> = sample_quantities
2281        .iter()
2282        .map(|&p| fit.result.on_bound[p])
2283        .collect();
2284    let position = |parameter: usize| {
2285        sample_quantities
2286            .iter()
2287            .position(|&p| free[p] == parameter)
2288            .expect("a measured or calibrated quantity is fitted")
2289    };
2290    let pulse_consistency = match (&pulse_prior, &unbounded) {
2291        (Some(prior), Some(unbounded)) => {
2292            let at: Vec<usize> = calibrated_parameters
2293                .iter()
2294                .map(|&parameter| position(parameter))
2295                .collect();
2296            let mut posterior = FlatMatrix::zeros(at.len(), at.len());
2297            for (a, &i) in at.iter().enumerate() {
2298                for (b, &j) in at.iter().enumerate() {
2299                    *posterior.get_mut(a, b) = unbounded.covariance.get(i, j);
2300                }
2301            }
2302            let estimate: Vec<f64> = at.iter().map(|&i| unbounded.mean[i]).collect();
2303            consistency(prior, &estimate, &posterior)?
2304        }
2305        _ => None,
2306    };
2307    let measured_pulls = unbounded.as_ref().map(|unbounded| {
2308        measured
2309            .iter()
2310            .map(|&(offset, mean, sd)| {
2311                let a = position(layout.quantities + offset);
2312                let p = sample_quantities[a];
2313                let nuclear = unbounded_nuclear.as_ref().map_or(0.0, |n| n.get(p, p));
2314                (unbounded.mean[a] - mean)
2315                    / (sd * sd - unbounded.covariance.get(a, a) + nuclear).sqrt()
2316            })
2317            .collect()
2318    });
2319    let region_fits = layout
2320        .regions
2321        .iter()
2322        .zip(&opens)
2323        .zip(overdispersions)
2324        .enumerate()
2325        .map(|(r, ((place, open), overdispersion))| RegionFit {
2326            densities: params[place.densities.clone()].to_vec(),
2327            temperature_k: place.temperature.map(|t| params[t]),
2328            thickness_variance: place.thickness.map(|v| params[v]),
2329            background: std::array::from_fn(|i| params[place.background + i]),
2330            gamma_transmission: params[place.gamma],
2331            capture_gammas: params[place.capture],
2332            in_scatter: params[place.scatter],
2333            timing_offset_us: params[place.offset],
2334            beam: open.beam.with_coefficients(&params[place.beam.clone()]),
2335            beam_at_limit: open.at_limit,
2336            predicted: [
2337                fit.predicted[2 * r * bins..(2 * r + 1) * bins].to_vec(),
2338                fit.predicted[(2 * r + 1) * bins..(2 * r + 2) * bins].to_vec(),
2339            ],
2340            overdispersion,
2341            excluded_bins: excluded[r].clone(),
2342        })
2343        .collect();
2344    let mut fitted = vec![false; params.len()];
2345    let mut at_bound = vec![false; params.len()];
2346    for (&index, &bound) in free.iter().zip(&fit.result.on_bound) {
2347        fitted[index] = true;
2348        at_bound[index] = bound;
2349    }
2350    let answer = Answer {
2351        grid: Arc::clone(&fit.fine),
2352        dispersion,
2353        params: params.clone(),
2354        fitted,
2355        at_bound,
2356        beams,
2357        resonances,
2358        lattices,
2359        filter: measurement.filter.clone(),
2360        charge_ratio: *charge_ratio,
2361        frames,
2362        beam_origin_us,
2363        layout: Arc::clone(&layout),
2364        live,
2365        observed,
2366    };
2367    let fit = CountsFit {
2368        regions: region_fits,
2369        normalization: params[layout.normalization],
2370        t0_us: params[layout.t0],
2371        flight_path_m: params[layout.flight_path],
2372        alpha: [params[layout.pulse], params[layout.pulse + 1]],
2373        beta: [params[layout.pulse + 2], params[layout.pulse + 3]],
2374        exponents: [params[layout.pulse + 9], params[layout.pulse + 10]],
2375        r: params[layout.pulse + 4],
2376        fwhm_squared_us2: params[layout.pulse + 5],
2377        r_high: calibration.pulse.r_high.map(|_| params[layout.pulse + 6]),
2378        detector_tail: calibration
2379            .pulse
2380            .detector_tail
2381            .map(|_| [params[layout.pulse + 7], params[layout.pulse + 8]]),
2382        time_background: [0, 1, 2, 3].map(|i| params[layout.time_background + i]),
2383        room_background: params[layout.room_background],
2384        spread_share: params[layout.spread],
2385        scatter_fraction: params[layout.environment],
2386        filter_density: params[layout.filter],
2387        covariance,
2388        unbounded,
2389        on_bound,
2390        deviance: fit.result.deviance,
2391        converged,
2392        unconverged,
2393        measured_pulls,
2394        pulse_consistency,
2395        step_us: fit.step_us,
2396        points: fit.points,
2397        halvings: rule_halvings + fit.halvings,
2398    };
2399    Ok((fit, answer))
2400}
2401
2402pub(crate) struct Answer {
2403    grid: Arc<FlightTimeGrid>,
2404    beams: Vec<BeamSpline>,
2405    resonances: Vec<Arc<[ResonanceData]>>,
2406    lattices: Vec<Option<PhononSpectrum>>,
2407    filter: Option<Filter>,
2408    charge_ratio: f64,
2409    frames: [f64; 2],
2410    beam_origin_us: f64,
2411    layout: Arc<Layout>,
2412    live: Vec<f64>,
2413    observed: Vec<f64>,
2414    dispersion: Vec<f64>,
2415    params: Vec<f64>,
2416    fitted: Vec<bool>,
2417    at_bound: Vec<bool>,
2418}
2419
2420pub(crate) struct RegionTerms {
2421    pub(crate) quantities: Vec<Role>,
2422    pub(crate) gradient: Vec<f64>,
2423    pub(crate) information: FlatMatrix,
2424    pub(crate) diagonal: Vec<f64>,
2425    pub(crate) unbounded: Option<(FlatMatrix, Vec<f64>)>,
2426    pub(crate) sensitivity: FlatMatrix,
2427    pub(crate) covariance: FlatMatrix,
2428    pub(crate) counted_information: FlatMatrix,
2429}
2430
2431impl Answer {
2432    pub(crate) fn region_terms(
2433        &self,
2434        region: usize,
2435        shared: &[Role],
2436    ) -> Result<RegionTerms, PipelineError> {
2437        let roles = &self.layout.roles;
2438        let own: Vec<usize> = (0..roles.len())
2439            .filter(|&i| {
2440                self.fitted[i]
2441                    && matches!(
2442                        roles[i],
2443                        Role::Beam { region: r, .. }
2444                            | Role::Density { region: r, .. }
2445                            | Role::Temperature { region: r }
2446                            | Role::ThicknessVariance { region: r }
2447                            | Role::Background { region: r, .. }
2448                            | Role::GammaTransmission { region: r }
2449                            | Role::CaptureGammas { region: r }
2450                            | Role::InScatter { region: r }
2451                            | Role::TimingOffset { region: r }
2452                            if r == region
2453                    )
2454            })
2455            .collect();
2456        let shared: Vec<usize> = shared
2457            .iter()
2458            .map(|&role| {
2459                roles
2460                    .iter()
2461                    .position(|&r| r == role)
2462                    .expect("a shared role is in the layout")
2463            })
2464            .collect();
2465        let columns: Vec<usize> = own.iter().chain(&shared).copied().collect();
2466        let model = Recorded {
2467            model: RegionsModel::new(
2468                &self.grid,
2469                &self.beams,
2470                &self.resonances,
2471                (self.charge_ratio, self.frames),
2472                self.beam_origin_us,
2473                &self.layout,
2474            )
2475            .lattices(&self.lattices)
2476            .filtered(self.filter.as_ref())?,
2477            live: &self.live,
2478        };
2479        let predicted = model.evaluate(&self.params)?;
2480        let jacobian = model
2481            .analytical_jacobian(&self.params, &columns, &predicted)
2482            .expect("the counts model has an analytical Jacobian");
2483        let n = columns.len();
2484        let mut full = Mat::<f64>::zeros(n, n);
2485        let mut gradient = vec![0.0; n];
2486        let bins = self.observed.len() / (2 * self.layout.regions.len());
2487        let rows = 2 * region * bins..2 * (region + 1) * bins;
2488        let mut weights = vec![0.0; rows.len()];
2489        for ((((k, &mu), &dispersion), &observed), weight) in rows
2490            .clone()
2491            .zip(&predicted[rows.clone()])
2492            .zip(&self.dispersion[rows.clone()])
2493            .zip(&self.observed[rows.clone()])
2494            .zip(weights.iter_mut())
2495        {
2496            if mu > 0.0 {
2497                *weight = 1.0 / (mu * dispersion);
2498                for a in 0..n {
2499                    let slope = jacobian.get(k, a);
2500                    gradient[a] += *weight * slope * (mu - observed);
2501                    for b in 0..n {
2502                        full[(a, b)] += *weight * slope * jacobian.get(k, b);
2503                    }
2504                }
2505            } else {
2506                for (a, g) in gradient.iter_mut().enumerate() {
2507                    *g += jacobian.get(k, a) / dispersion;
2508                }
2509            }
2510        }
2511        let (o, s) = (own.len(), shared.len());
2512        let counted = rows.len();
2513        let profile = |set: Vec<usize>| -> Result<Profile, PipelineError> {
2514            let m = set.len();
2515            let mut block = FlatMatrix::zeros(m, m);
2516            for (a, &i) in set.iter().enumerate() {
2517                for (b, &j) in set.iter().enumerate() {
2518                    *block.get_mut(a, b) = full[(i, j)];
2519                }
2520            }
2521            let diagonal: Vec<f64> = set.iter().map(|&i| full[(i, i)]).collect();
2522            let inverse = information_inverse(&block, &diagonal, counted)?;
2523            let mut moved = FlatMatrix::zeros(m, s);
2524            for a in 0..m {
2525                for j in 0..s {
2526                    *moved.get_mut(a, j) = -(0..m)
2527                        .map(|b| inverse.spanned.get(a, b) * full[(set[b], o + j)])
2528                        .sum::<f64>();
2529                }
2530            }
2531            let profiled = |i: usize, j: usize| {
2532                full[(o + i, o + j)]
2533                    + (0..m)
2534                        .map(|a| full[(o + i, set[a])] * moved.get(a, j))
2535                        .sum::<f64>()
2536            };
2537            let mut information = FlatMatrix::zeros(s, s);
2538            for i in 0..s {
2539                for j in 0..s {
2540                    *information.get_mut(i, j) = 0.5 * (profiled(i, j) + profiled(j, i));
2541                }
2542            }
2543            let slope = (0..s)
2544                .map(|j| {
2545                    gradient[o + j]
2546                        + (0..m)
2547                            .map(|a| moved.get(a, j) * gradient[set[a]])
2548                            .sum::<f64>()
2549                })
2550                .collect();
2551            Ok(Profile {
2552                set,
2553                inverse: inverse.determined,
2554                resolved: inverse.resolved,
2555                moved,
2556                information,
2557                gradient: slope,
2558            })
2559        };
2560        let bounded = profile((0..o).filter(|&a| !self.at_bound[own[a]]).collect())?;
2561        let unbounded = profile((0..o).collect())?;
2562        let Profile {
2563            set,
2564            inverse,
2565            resolved,
2566            moved,
2567            information,
2568            gradient,
2569        } = bounded;
2570        let quantities: Vec<usize> = (0..set.len())
2571            .filter(|&a| !matches!(roles[own[set[a]]], Role::Beam { .. }))
2572            .collect();
2573        let mut sensitivity = FlatMatrix::zeros(quantities.len(), s);
2574        let mut covariance = FlatMatrix::zeros(quantities.len(), quantities.len());
2575        for (row, &a) in quantities.iter().enumerate() {
2576            for j in 0..s {
2577                *sensitivity.get_mut(row, j) = if resolved[a] {
2578                    moved.get(a, j)
2579                } else {
2580                    f64::NAN
2581                };
2582            }
2583            for (col, &b) in quantities.iter().enumerate() {
2584                *covariance.get_mut(row, col) = if resolved[a] && resolved[b] {
2585                    inverse.get(a, b)
2586                } else {
2587                    f64::NAN
2588                };
2589            }
2590        }
2591        let mut counted_information = FlatMatrix::zeros(s, s);
2592        let sample = rows.start + counted / 2..rows.end;
2593        for (k, &weight) in sample.clone().zip(&weights[counted / 2..]) {
2594            if predicted[k] < COUNTS_TO_MEASURE_NOISE {
2595                continue;
2596            }
2597            let slope: Vec<f64> = (0..s)
2598                .map(|j| {
2599                    jacobian.get(k, o + j)
2600                        + (0..set.len())
2601                            .map(|a| jacobian.get(k, set[a]) * moved.get(a, j))
2602                            .sum::<f64>()
2603                })
2604                .collect();
2605            for i in 0..s {
2606                for j in 0..s {
2607                    *counted_information.get_mut(i, j) += weight * slope[i] * slope[j];
2608                }
2609            }
2610        }
2611        Ok(RegionTerms {
2612            quantities: quantities.iter().map(|&a| roles[own[set[a]]]).collect(),
2613            gradient,
2614            information,
2615            diagonal: (0..s).map(|j| full[(o + j, o + j)]).collect(),
2616            unbounded: Some((unbounded.information, unbounded.gradient)),
2617            sensitivity,
2618            covariance,
2619            counted_information,
2620        })
2621    }
2622}
2623
2624struct Profile {
2625    set: Vec<usize>,
2626    inverse: FlatMatrix,
2627    resolved: Vec<bool>,
2628    moved: FlatMatrix,
2629    information: FlatMatrix,
2630    gradient: Vec<f64>,
2631}
2632
2633pub(crate) const BACKGROUND_TERMS: [&str; 5] = ["b0", "b1", "b2", "d", "f"];
2634
2635pub(crate) const SHARED: [Role; 19] = [
2636    Role::Normalization,
2637    Role::TimeBackground(0),
2638    Role::TimeBackground(1),
2639    Role::TimeBackground(2),
2640    Role::TimeBackground(3),
2641    Role::RoomBackground,
2642    Role::T0,
2643    Role::FlightPath,
2644    Role::Pulse(0),
2645    Role::Pulse(1),
2646    Role::Pulse(2),
2647    Role::Pulse(3),
2648    Role::Pulse(4),
2649    Role::Pulse(5),
2650    Role::Pulse(6),
2651    Role::Pulse(7),
2652    Role::Pulse(8),
2653    Role::Pulse(9),
2654    Role::Pulse(10),
2655];
2656
2657pub(crate) fn shared_parameters(
2658    measurement: &Measurement,
2659    calibration: &Calibration,
2660) -> Result<Vec<(Value, FitParameter)>, PipelineError> {
2661    validate_pulse_prior(calibration)?;
2662    let mut parameters = Vec::with_capacity(SHARED.len());
2663    for (value, name, range, allowed) in SHARED
2664        .iter()
2665        .filter_map(|&role| quantity(measurement, role))
2666    {
2667        parameters.push(value.parameter(name, range, &allowed)?);
2668    }
2669    parameters.extend(calibration.instrument()?);
2670    let values = quantities(measurement, calibration)
2671        .filter(|(role, _)| SHARED.contains(role))
2672        .map(|(_, value)| *value);
2673    Ok(values.zip(parameters).collect())
2674}
2675
2676fn validate_pulse_prior(calibration: &Calibration) -> Result<(), PipelineError> {
2677    let pulse = &calibration.pulse;
2678    let numbers = pulse.numbers();
2679    match pulse
2680        .prior
2681        .iter()
2682        .flat_map(|prior| &prior.numbers)
2683        .find(|&&n| !matches!(numbers[n], Value::Fitted(_) | Value::Within { .. }))
2684    {
2685        Some(&number) => Err(PipelineError::InvalidParameter(format!(
2686            "the pulse's calibration covers {}, which must be fitted, without a measurement; \
2687             got {:?}",
2688            PULSE_NUMBERS[number], numbers[number]
2689        ))),
2690        None => Ok(()),
2691    }
2692}
2693
2694pub(crate) fn quantities<'a>(
2695    measurement: &'a Measurement,
2696    calibration: &'a Calibration,
2697) -> impl Iterator<Item = (Role, &'a Value)> {
2698    let shape = shape(measurement);
2699    let numbers = calibration.pulse.numbers();
2700    roles(&vec![0; shape.len()], &shape)
2701        .into_iter()
2702        .filter_map(move |role| {
2703            let value = match role {
2704                Role::T0 => &calibration.t0_us,
2705                Role::FlightPath => &calibration.flight_path_m,
2706                Role::Pulse(number) => numbers[number],
2707                _ => quantity(measurement, role)?.0,
2708            };
2709            Some((role, value))
2710        })
2711}
2712
2713fn shape(measurement: &Measurement) -> Vec<Option<usize>> {
2714    measurement
2715        .regions
2716        .iter()
2717        .map(|region| region.material.as_ref().map(|m| m.isotopes.len()))
2718        .collect()
2719}
2720
2721#[derive(Clone, Copy, Debug, PartialEq)]
2722pub(crate) enum Role {
2723    Beam { region: usize, coefficient: usize },
2724    Density { region: usize, isotope: usize },
2725    Temperature { region: usize },
2726    ThicknessVariance { region: usize },
2727    Normalization,
2728    Background { region: usize, term: usize },
2729    GammaTransmission { region: usize },
2730    CaptureGammas { region: usize },
2731    InScatter { region: usize },
2732    TimingOffset { region: usize },
2733    TimeBackground(usize),
2734    RoomBackground,
2735    SpreadShare,
2736    ScatterFraction,
2737    Filter,
2738    T0,
2739    FlightPath,
2740    Pulse(usize),
2741}
2742
2743fn roles(beams: &[usize], isotopes: &[Option<usize>]) -> Vec<Role> {
2744    let beam = beams.iter().enumerate().flat_map(|(region, &n)| {
2745        (0..n).map(move |coefficient| Role::Beam {
2746            region,
2747            coefficient,
2748        })
2749    });
2750    let materials = isotopes
2751        .iter()
2752        .enumerate()
2753        .filter_map(|(region, n)| Some((region, (*n)?)))
2754        .flat_map(|(region, n)| {
2755            (0..n)
2756                .map(move |isotope| Role::Density { region, isotope })
2757                .chain([
2758                    Role::Temperature { region },
2759                    Role::ThicknessVariance { region },
2760                ])
2761        });
2762    let backgrounds = (0..isotopes.len())
2763        .flat_map(|region| (0..5).map(move |term| Role::Background { region, term }));
2764    let gammas = (0..isotopes.len()).map(|region| Role::GammaTransmission { region });
2765    let captures = (0..isotopes.len()).map(|region| Role::CaptureGammas { region });
2766    let scatters = (0..isotopes.len()).map(|region| Role::InScatter { region });
2767    let offsets = (0..isotopes.len()).map(|region| Role::TimingOffset { region });
2768    beam.chain(materials)
2769        .chain([Role::Normalization])
2770        .chain(backgrounds)
2771        .chain(gammas)
2772        .chain(captures)
2773        .chain(scatters)
2774        .chain(offsets)
2775        .chain((0..4).map(Role::TimeBackground))
2776        .chain([
2777            Role::RoomBackground,
2778            Role::SpreadShare,
2779            Role::ScatterFraction,
2780            Role::Filter,
2781            Role::T0,
2782            Role::FlightPath,
2783        ])
2784        .chain((0..11).map(Role::Pulse))
2785        .collect()
2786}
2787
2788fn material(measurement: &Measurement, region: usize) -> &Material {
2789    measurement.regions[region]
2790        .material
2791        .as_ref()
2792        .expect("a density or temperature names a region with a material")
2793}
2794
2795fn quantity(
2796    measurement: &Measurement,
2797    role: Role,
2798) -> Option<(&Value, String, RangeInclusive<f64>, String)> {
2799    let (t_low, t_high) = TEMPERATURE_BOUNDS_K;
2800    Some(match role {
2801        Role::Density { region, isotope } => {
2802            let (data, density) = &material(measurement, region).isotopes[isotope];
2803            (
2804                density,
2805                format!("density of {} in region {region}", data.isotope),
2806                0.0..=f64::INFINITY,
2807                "0 or more".into(),
2808            )
2809        }
2810        Role::Temperature { region } => (
2811            &material(measurement, region).temperature_k,
2812            format!("temperature of region {region}"),
2813            t_low..=t_high,
2814            format!("within {t_low}–{t_high} K"),
2815        ),
2816        Role::ThicknessVariance { region } => (
2817            &material(measurement, region).thickness_variance,
2818            format!("thickness variance of region {region}"),
2819            0.0..=f64::INFINITY,
2820            "0 or more".into(),
2821        ),
2822        Role::Normalization => (
2823            &measurement.normalization,
2824            "normalization".into(),
2825            f64::MIN_POSITIVE..=f64::INFINITY,
2826            "positive".into(),
2827        ),
2828        Role::Background { region, term } => (
2829            &measurement.regions[region].background[term],
2830            format!("{} of region {region}", BACKGROUND_TERMS[term]),
2831            if term == 4 { 0.0 } else { f64::NEG_INFINITY }..=f64::INFINITY,
2832            if term == 4 {
2833                "0 or more"
2834            } else {
2835                "of any sign"
2836            }
2837            .into(),
2838        ),
2839        Role::CaptureGammas { region } => (
2840            &measurement.regions[region].capture_gammas,
2841            format!("capture gammas of region {region}"),
2842            0.0..=f64::INFINITY,
2843            "0 or more".into(),
2844        ),
2845        Role::InScatter { region } => (
2846            &measurement.regions[region].in_scatter,
2847            format!("in-scatter of region {region}"),
2848            0.0..=f64::INFINITY,
2849            "0 or more".into(),
2850        ),
2851        Role::TimingOffset { region } => (
2852            &measurement.regions[region].timing_offset_us,
2853            format!("timing offset of region {region}"),
2854            f64::NEG_INFINITY..=f64::INFINITY,
2855            "any real number".into(),
2856        ),
2857        Role::GammaTransmission { region } => (
2858            &measurement.regions[region].gamma_transmission,
2859            format!("gamma transmission of region {region}"),
2860            0.0..=1.0,
2861            "within 0–1".into(),
2862        ),
2863        Role::TimeBackground(term) => {
2864            let value = &measurement.time_background[term];
2865            let first_bin = match measurement.time_edges_us.as_slice() {
2866                [first, second, ..] if second > first => Some(second - first),
2867                _ => None,
2868            };
2869            let (name, low, allowed) = match term {
2870                0 => ("C", 0.0, "0 or more".to_string()),
2871                1 => ("A", 0.0, "0 or more".to_string()),
2872                // Far below the first bin's width only A·τ shows in the counts.
2873                2 => match first_bin.filter(|_| !matches!(value, Value::Known(_))) {
2874                    Some(width) => (
2875                        "τ",
2876                        width,
2877                        format!("at least the first bin's width of {width} µs"),
2878                    ),
2879                    None => ("τ", f64::MIN_POSITIVE, "positive".to_string()),
2880                },
2881                _ => ("D", f64::NEG_INFINITY, "any real number".to_string()),
2882            };
2883            (
2884                value,
2885                format!("time background {name}"),
2886                low..=f64::INFINITY,
2887                allowed,
2888            )
2889        }
2890        Role::RoomBackground => (
2891            measurement
2892                .room_background
2893                .as_ref()
2894                .map_or(&Value::Known(0.0), |room| &room.rate),
2895            "room background ρ".into(),
2896            0.0..=f64::INFINITY,
2897            "0 or more".into(),
2898        ),
2899        Role::SpreadShare => (
2900            measurement
2901                .spread
2902                .as_ref()
2903                .map_or(&Value::Known(0.0), |spread| &spread.share),
2904            "detector spread h".into(),
2905            0.0..=1.0,
2906            "within 0–1".into(),
2907        ),
2908        Role::ScatterFraction => (
2909            measurement
2910                .environment_scatter
2911                .as_ref()
2912                .map_or(&Value::Known(0.0), |scatter| &scatter.fraction),
2913            "environment scatter fraction".into(),
2914            0.0..=1.0,
2915            "within 0–1".into(),
2916        ),
2917        Role::Filter => (
2918            measurement
2919                .filter
2920                .as_ref()
2921                .map_or(&Value::Known(0.0), |filter| &filter.areal_density),
2922            "filter areal density".into(),
2923            0.0..=f64::INFINITY,
2924            "0 or more".into(),
2925        ),
2926        Role::Beam { .. } | Role::T0 | Role::FlightPath | Role::Pulse(_) => return None,
2927    })
2928}
2929
2930fn spread_checked(spread: &Spread, regions: usize) -> Result<(), PipelineError> {
2931    let invalid = |message: String| Err(PipelineError::InvalidParameter(message));
2932    let [rows, columns] = spread.grid;
2933    if !rows
2934        .checked_mul(columns)
2935        .is_some_and(|cells| (1..=MOST_SPREAD_CELLS).contains(&cells))
2936    {
2937        return invalid(format!(
2938            "the spread's {rows}×{columns} grid must hold 1 to {MOST_SPREAD_CELLS} cells"
2939        ));
2940    }
2941    if spread.kernel.is_empty()
2942        || !spread
2943            .kernel
2944            .iter()
2945            .all(|&(w, s)| w.is_finite() && w > 0.0 && s.is_finite() && s > 0.0)
2946    {
2947        return invalid(format!(
2948            "the spread kernel needs terms of finite, positive weight and length, got {:?}",
2949            spread.kernel
2950        ));
2951    }
2952    if spread.cells.len() != regions {
2953        return invalid(format!(
2954            "the spread gives the cells of {} regions for {regions} regions",
2955            spread.cells.len()
2956        ));
2957    }
2958    let mut taken = vec![false; rows * columns];
2959    for (r, cells) in spread.cells.iter().enumerate() {
2960        if cells.is_empty() {
2961            return invalid(format!("the spread gives region {r} no cells"));
2962        }
2963        for &[row, column] in cells {
2964            if row >= rows || column >= columns {
2965                return invalid(format!(
2966                    "cell [{row}, {column}] of region {r} is off the {rows}×{columns} grid"
2967                ));
2968            }
2969            if std::mem::replace(&mut taken[row * columns + column], true) {
2970                return invalid(format!("cell [{row}, {column}] is in two regions"));
2971            }
2972        }
2973    }
2974    Ok(())
2975}
2976
2977fn in_region(region: usize, error: PipelineError) -> PipelineError {
2978    labelled(&format!("region {region}"), error)
2979}
2980
2981pub(crate) fn labelled(label: &str, error: PipelineError) -> PipelineError {
2982    match error {
2983        PipelineError::InvalidParameter(message) => {
2984            PipelineError::InvalidParameter(format!("{label}: {message}"))
2985        }
2986        PipelineError::ShapeMismatch(message) => {
2987            PipelineError::ShapeMismatch(format!("{label}: {message}"))
2988        }
2989        other => other,
2990    }
2991}
2992
2993fn finite(isotope: &ResonanceData) -> bool {
2994    isotope.awr.is_finite()
2995        && isotope.ranges.iter().all(|range| {
2996            let radii = range
2997                .ap_table
2998                .iter()
2999                .flat_map(|table| table.points.iter().flat_map(|&(e, r)| [e, r]));
3000            let external = range.r_external.iter().flat_map(|r| {
3001                [
3002                    r.j, r.e_low, r.e_up, r.r_con, r.r_lin, r.s_con, r.s_lin, r.r_quad,
3003                ]
3004            });
3005            let groups = range.l_groups.iter().flat_map(|group| {
3006                [group.awr, group.apl, group.qx].into_iter().chain(
3007                    group
3008                        .resonances
3009                        .iter()
3010                        .flat_map(|r| [r.energy, r.j, r.gn, r.gg, r.gfa, r.gfb]),
3011                )
3012            });
3013            let rml = range.r_matrix_limited.iter().flat_map(rml_values);
3014            [
3015                range.energy_low,
3016                range.energy_high,
3017                range.target_spin,
3018                range.scattering_radius,
3019            ]
3020            .into_iter()
3021            .chain(radii)
3022            .chain(external)
3023            .chain(groups)
3024            .chain(rml)
3025            .all(f64::is_finite)
3026        })
3027}
3028
3029/// Every floating-point parameter of an LRF=7 range.
3030fn rml_values(rml: &RmlRange) -> impl Iterator<Item = f64> + '_ {
3031    let pairs = rml.pairs.iter().flat_map(|p| {
3032        [
3033            p.mass_a, p.mass_b, p.charge_a, p.charge_b, p.spin_a, p.spin_b, p.q_value,
3034        ]
3035    });
3036    let groups = rml.spin_groups.iter().flat_map(|g| {
3037        let channels = g
3038            .channels
3039            .iter()
3040            .flat_map(|c| [c.channel_spin, c.boundary, c.radius_phase, c.radius_true]);
3041        let levels = g
3042            .resonances
3043            .iter()
3044            .flat_map(|r| std::iter::once(r.energy).chain(r.widths.iter().copied()));
3045        let background = g.background.iter().flat_map(|b| {
3046            [
3047                b.e_down, b.e_up, b.r_con, b.r_lin, b.r_quad, b.s_con, b.s_lin,
3048            ]
3049        });
3050        std::iter::once(g.j)
3051            .chain(channels)
3052            .chain(levels)
3053            .chain(background)
3054    });
3055    pairs.chain(groups)
3056}
3057
3058struct Lines<'a> {
3059    region: usize,
3060    isotopes: &'a [(ResonanceData, Value)],
3061    dopplers: Vec<DopplerParams>,
3062    reach_k: f64,
3063    lattice: Option<&'a PhononSpectrum>,
3064    scatters: bool,
3065}
3066
3067struct Layout {
3068    roles: Vec<Role>,
3069    regions: Vec<Place>,
3070    quantities: usize,
3071    normalization: usize,
3072    time_background: usize,
3073    room_background: usize,
3074    spread: usize,
3075    environment: usize,
3076    filter: usize,
3077    t0: usize,
3078    flight_path: usize,
3079    pulse: usize,
3080    storage_span: Option<(f64, f64)>,
3081}
3082
3083struct Place {
3084    beam: Range<usize>,
3085    densities: Range<usize>,
3086    temperature: Option<usize>,
3087    thickness: Option<usize>,
3088    background: usize,
3089    gamma: usize,
3090    capture: usize,
3091    capture_on: bool,
3092    scatter: usize,
3093    scatter_on: bool,
3094    offset: usize,
3095    pixels: f64,
3096}
3097
3098impl Layout {
3099    /// Each region's `t0 + δt`.
3100    fn starts(&self, params: &[f64]) -> Vec<f64> {
3101        self.regions
3102            .iter()
3103            .map(|place| params[self.t0] + params[place.offset])
3104            .collect()
3105    }
3106
3107    fn new(roles: Vec<Role>, pixels: &[f64], switches: &[[bool; 2]]) -> Self {
3108        let at = |wanted: Role| {
3109            roles
3110                .iter()
3111                .position(|&role| role == wanted)
3112                .expect("every region has a background and the instrument its numbers")
3113        };
3114        let span = |of: &dyn Fn(Role) -> bool| {
3115            let first = roles.iter().position(|&role| of(role));
3116            let last = roles.iter().rposition(|&role| of(role));
3117            first
3118                .zip(last)
3119                .map_or(0..0, |(first, last)| first..last + 1)
3120        };
3121        let places = (0..pixels.len())
3122            .map(|r| Place {
3123                beam: span(&|role| matches!(role, Role::Beam { region, .. } if region == r)),
3124                densities: span(
3125                    &|role| matches!(role, Role::Density { region, .. } if region == r),
3126                ),
3127                temperature: roles
3128                    .iter()
3129                    .position(|&role| role == Role::Temperature { region: r }),
3130                thickness: roles
3131                    .iter()
3132                    .position(|&role| role == Role::ThicknessVariance { region: r }),
3133                background: at(Role::Background { region: r, term: 0 }),
3134                gamma: at(Role::GammaTransmission { region: r }),
3135                capture: at(Role::CaptureGammas { region: r }),
3136                capture_on: switches[r][0],
3137                scatter: at(Role::InScatter { region: r }),
3138                scatter_on: switches[r][1],
3139                offset: at(Role::TimingOffset { region: r }),
3140                pixels: pixels[r],
3141            })
3142            .collect();
3143        Self {
3144            quantities: roles
3145                .iter()
3146                .position(|role| !matches!(role, Role::Beam { .. }))
3147                .expect("the instrument's numbers follow the beams"),
3148            normalization: at(Role::Normalization),
3149            time_background: at(Role::TimeBackground(0)),
3150            room_background: at(Role::RoomBackground),
3151            spread: at(Role::SpreadShare),
3152            environment: at(Role::ScatterFraction),
3153            filter: at(Role::Filter),
3154            t0: at(Role::T0),
3155            flight_path: at(Role::FlightPath),
3156            pulse: at(Role::Pulse(0)),
3157            storage_span: None,
3158            regions: places,
3159            roles,
3160        }
3161    }
3162}
3163
3164struct RegionsModel {
3165    grid: Arc<FlightTimeGrid>,
3166    bins: Vec<(f64, f64)>,
3167    splines: Vec<BeamSpline>,
3168    beam_origin_us: f64,
3169    absorbers: Vec<Absorber>,
3170    energies: Vec<f64>,
3171    flight_energies: Vec<f64>,
3172    shapes: [Vec<f64>; 3],
3173    charge_ratio: f64,
3174    frames: [f64; 2],
3175    layout: Arc<Layout>,
3176    clocks: RefCell<Option<Clocks>>,
3177    mixing: Option<Arc<Vec<Vec<f64>>>>,
3178    scattered: Option<Arc<Furnace>>,
3179    filter: Option<Vec<f64>>,
3180}
3181
3182/// One [`Scale`] for each distinct `t0 + δt` of the regions, and each
3183/// region's beam basis and its slope at the grid's points.
3184struct Clocks {
3185    scales: Vec<Scale>,
3186    of_region: Vec<usize>,
3187    basis: Vec<Vec<[(usize, f64); 5]>>,
3188    basis_slope: Vec<Vec<[(usize, f64); 5]>>,
3189}
3190
3191impl Clocks {
3192    fn of(&self, region: usize) -> &Scale {
3193        &self.scales[self.of_region[region]]
3194    }
3195}
3196
3197struct Absorber {
3198    isotopes: Arc<[ResonanceData]>,
3199    lattice: Option<PhononSpectrum>,
3200    cross_sections: [RefCell<Option<CrossSections>>; 3],
3201}
3202
3203/// `channel` of `isotope` at `energies` broadened at `temperature_k` by
3204/// `lattice`, or by the free gas without one.
3205fn broadened(
3206    energies: &[f64],
3207    isotope: &ResonanceData,
3208    temperature_k: f64,
3209    channel: Channel,
3210    lattice: Option<&PhononSpectrum>,
3211) -> Result<TierOneBroadening, String> {
3212    match lattice {
3213        Some(spectrum) => broaden_in_lattice(energies, isotope, temperature_k, spectrum, channel)
3214            .map_err(|e| e.to_string()),
3215        None => broaden_with_budget(
3216            energies,
3217            isotope,
3218            temperature_k,
3219            channel,
3220            QuadratureBudget::default(),
3221        )
3222        .map_err(|e| e.to_string()),
3223    }
3224}
3225
3226const CHANNELS: [Channel; 3] = [Channel::Total, Channel::Capture, Channel::Elastic];
3227const TOTAL: usize = 0;
3228const CAPTURE: usize = 1;
3229const ELASTIC: usize = 2;
3230
3231struct Beams {
3232    open: Vec<f64>,
3233    normalized: Vec<f64>,
3234    sample: Vec<f64>,
3235    per_depth: Vec<f64>,
3236    per_variance: Vec<f64>,
3237    capture: Option<Captured>,
3238    scatter: Option<Scattered>,
3239}
3240
3241/// The capture gammas' counts per grid point before the pulse, as slopes:
3242/// in `ε`, in the optical depth through the interacting fraction, per unit
3243/// capture cross section, and in the thickness variance.
3244struct Captured {
3245    per_efficiency: Vec<f64>,
3246    per_depth: Vec<f64>,
3247    share: Vec<f64>,
3248    per_variance: Vec<f64>,
3249}
3250
3251/// The in-scatter's counts per grid point before the pulse per unit `Ω`, and
3252/// each isotope's share leaving through the back face with its slopes.
3253struct Scattered {
3254    per_acceptance: Vec<f64>,
3255    shares: Vec<ForwardYield>,
3256}
3257
3258struct CrossSections {
3259    temperature_k: f64,
3260    values: Vec<Vec<f64>>,
3261    slopes: Vec<Vec<f64>>,
3262}
3263
3264struct Scale {
3265    t0_us: f64,
3266    flight_path_m: f64,
3267    pulse: IkedaCarpenterParams,
3268    rows: Rows,
3269}
3270
3271impl Clocks {
3272    /// The clocks `scales`, region `r` on `scales[of_region[r]]`, with each
3273    /// region's beam `splines[r]` read at the arrival times of its own.
3274    fn new(
3275        scales: Vec<Scale>,
3276        of_region: Vec<usize>,
3277        grid: &FlightTimeGrid,
3278        splines: &[BeamSpline],
3279        beam_origin_us: f64,
3280    ) -> Self {
3281        let (basis, basis_slope) = splines
3282            .iter()
3283            .zip(&of_region)
3284            .map(|(spline, &group)| {
3285                let scale = &scales[group];
3286                let (shift, stretch) = (
3287                    scale.t0_us - beam_origin_us,
3288                    scale.flight_path_m / grid.flight_path_m(),
3289                );
3290                let abscissae: Vec<f64> = grid
3291                    .flight_times_us()
3292                    .iter()
3293                    .map(|u| shift + stretch * u)
3294                    .collect();
3295                let basis: Vec<_> = abscissae.iter().map(|&a| spline.basis(a)).collect();
3296                let slope: Vec<_> = abscissae.iter().map(|&a| spline.basis_slope(a)).collect();
3297                (basis, slope)
3298            })
3299            .unzip();
3300        Self {
3301            scales,
3302            of_region,
3303            basis,
3304            basis_slope,
3305        }
3306    }
3307}
3308
3309fn predicted(rows: &Rows, values: &[f64]) -> Result<Vec<f64>, FittingError> {
3310    rows.predict(values)
3311        .map_err(|e| FittingError::EvaluationFailed(e.to_string()))
3312}
3313
3314pub(crate) fn starts_and_widths_us(time_edges_us: &[f64]) -> Vec<(f64, f64)> {
3315    time_edges_us
3316        .windows(2)
3317        .map(|edges| (edges[0] - time_edges_us[0], edges[1] - edges[0]))
3318        .collect()
3319}
3320
3321/// The span `W` of bins given as starts from the first edge and widths, in µs.
3322pub(crate) fn span_us(starts_and_widths_us: &[(f64, f64)]) -> f64 {
3323    starts_and_widths_us
3324        .last()
3325        .map_or(1.0, |&(start, width)| start + width)
3326}
3327
3328/// The time background's counts per pixel in each bin and their slopes in
3329/// `[C, A, τ, D]`, the linear term rising by `D` over `span_us`.
3330pub(crate) fn time_counts_per_pixel(
3331    starts_and_widths_us: &[(f64, f64)],
3332    [c, a, tau, d]: [f64; 4],
3333    span_us: f64,
3334) -> (Vec<f64>, [Vec<f64>; 4]) {
3335    let bins = starts_and_widths_us.len();
3336    let mut counts = Vec::with_capacity(bins);
3337    let mut slopes: [Vec<f64>; 4] = std::array::from_fn(|_| Vec::with_capacity(bins));
3338    for &(start, width) in starts_and_widths_us {
3339        let decay = (-start / tau).exp();
3340        let after = (-(start + width) / tau).exp();
3341        let fraction = -(-width / tau).exp_m1();
3342        let integral = decay * (tau * fraction);
3343        let ramp = width * (start + 0.5 * width) / span_us;
3344        counts.push(c * width + a * integral + d * ramp);
3345        slopes[0].push(width);
3346        slopes[1].push(integral);
3347        slopes[2].push(a * (decay * fraction + (decay * start * fraction - after * width) / tau));
3348        slopes[3].push(ramp);
3349    }
3350    (counts, slopes)
3351}
3352
3353impl RegionsModel {
3354    fn new(
3355        grid: &Arc<FlightTimeGrid>,
3356        beams: &[BeamSpline],
3357        isotopes: &[Arc<[ResonanceData]>],
3358        (charge_ratio, frames): (f64, [f64; 2]),
3359        beam_origin_us: f64,
3360        layout: &Arc<Layout>,
3361    ) -> Self {
3362        let flight_energies = grid.energies_ev();
3363        let mut energies = flight_energies.clone();
3364        let shapes = [
3365            vec![1.0; energies.len()],
3366            energies.iter().map(|e| 1.0 / e.sqrt()).collect(),
3367            energies.iter().map(|e| e.sqrt()).collect(),
3368        ];
3369        energies.reverse();
3370        Self {
3371            grid: Arc::clone(grid),
3372            bins: starts_and_widths_us(grid.time_edges_us()),
3373            splines: beams.to_vec(),
3374            beam_origin_us,
3375            absorbers: isotopes
3376                .iter()
3377                .map(|isotopes| Absorber {
3378                    isotopes: Arc::clone(isotopes),
3379                    lattice: None,
3380                    cross_sections: [RefCell::new(None), RefCell::new(None), RefCell::new(None)],
3381                })
3382                .collect(),
3383            energies,
3384            flight_energies,
3385            shapes,
3386            charge_ratio,
3387            frames,
3388            layout: Arc::clone(layout),
3389            clocks: RefCell::new(Some(Clocks::new(
3390                vec![Scale {
3391                    t0_us: grid.t0_us(),
3392                    flight_path_m: grid.flight_path_m(),
3393                    pulse: grid.pulse().params().clone(),
3394                    rows: grid.rows().clone(),
3395                }],
3396                vec![0; layout.regions.len()],
3397                grid,
3398                beams,
3399                beam_origin_us,
3400            ))),
3401            mixing: None,
3402            scattered: None,
3403            filter: None,
3404        }
3405    }
3406
3407    /// The model with the beam crossing `filter` ahead of every region.
3408    fn filtered(mut self, filter: Option<&Filter>) -> Result<Self, PipelineError> {
3409        self.filter = filter.map(|f| f.on_grid(&self.grid)).transpose()?;
3410        Ok(self)
3411    }
3412
3413    /// The model with each region's material broadened by its lattice, or by
3414    /// the free gas without one.
3415    fn lattices(mut self, lattices: &[Option<PhononSpectrum>]) -> Self {
3416        for (absorber, lattice) in self.absorbers.iter_mut().zip(lattices) {
3417            absorber.lattice = lattice.clone();
3418        }
3419        self
3420    }
3421
3422    /// The model with the spread's shares `F_rq` between the regions.
3423    fn spread(mut self, mixing: Option<Arc<Vec<Vec<f64>>>>) -> Self {
3424        self.mixing = mixing;
3425        self
3426    }
3427
3428    fn environment(mut self, scattered: Option<Arc<Furnace>>) -> Self {
3429        self.scattered = scattered;
3430        self
3431    }
3432
3433    fn at(
3434        &self,
3435        region: usize,
3436        temperature_k: f64,
3437        channel: usize,
3438    ) -> Result<std::cell::Ref<'_, CrossSections>, FittingError> {
3439        let absorber = &self.absorbers[region];
3440        let current = absorber.cross_sections[channel]
3441            .borrow()
3442            .as_ref()
3443            .is_some_and(|c| c.temperature_k.to_bits() == temperature_k.to_bits());
3444        if !current {
3445            let energies = &self.energies;
3446            let lattice = absorber.lattice.as_ref();
3447            let (values, slopes) = absorber
3448                .isotopes
3449                .par_iter()
3450                .map(|isotope| {
3451                    let broadened =
3452                        broadened(energies, isotope, temperature_k, CHANNELS[channel], lattice)
3453                            .map_err(FittingError::EvaluationFailed)?;
3454                    let (mut sigma, mut slope) = (broadened.values, broadened.derivatives);
3455                    sigma.reverse();
3456                    slope.reverse();
3457                    Ok((sigma, slope))
3458                })
3459                .collect::<Result<Vec<_>, FittingError>>()?
3460                .into_iter()
3461                .unzip();
3462            *absorber.cross_sections[channel].borrow_mut() = Some(CrossSections {
3463                temperature_k,
3464                values,
3465                slopes,
3466            });
3467        }
3468        Ok(std::cell::Ref::map(
3469            absorber.cross_sections[channel].borrow(),
3470            |c| c.as_ref().expect("computed above"),
3471        ))
3472    }
3473
3474    fn clocks(&self, params: &[f64]) -> Result<std::cell::Ref<'_, Clocks>, FittingError> {
3475        let starts = self.layout.starts(params);
3476        let flight_path_m = params[self.layout.flight_path];
3477        let pulse = laws(&params[self.layout.pulse..], self.layout.storage_span);
3478        let at = |scale: &Scale, t0_us: f64| {
3479            (scale.t0_us.to_bits(), scale.flight_path_m.to_bits())
3480                == (t0_us.to_bits(), flight_path_m.to_bits())
3481                && scale.pulse == pulse
3482        };
3483        let current = self.clocks.borrow().as_ref().is_some_and(|clocks| {
3484            starts
3485                .iter()
3486                .enumerate()
3487                .all(|(r, &start)| at(clocks.of(r), start))
3488        });
3489        if !current {
3490            let mut scales: Vec<Scale> = Vec::new();
3491            let mut of_region = Vec::with_capacity(starts.len());
3492            for start in starts {
3493                if let Some(group) = scales.iter().position(|scale| at(scale, start)) {
3494                    of_region.push(group);
3495                    continue;
3496                }
3497                let rows = self
3498                    .grid
3499                    .rows_at(start, flight_path_m, &pulse)
3500                    .map_err(|e| FittingError::EvaluationFailed(e.to_string()))?;
3501                of_region.push(scales.len());
3502                scales.push(Scale {
3503                    t0_us: start,
3504                    flight_path_m,
3505                    pulse: pulse.clone(),
3506                    rows,
3507                });
3508            }
3509            *self.clocks.borrow_mut() = Some(Clocks::new(
3510                scales,
3511                of_region,
3512                &self.grid,
3513                &self.splines,
3514                self.beam_origin_us,
3515            ));
3516        }
3517        Ok(std::cell::Ref::map(self.clocks.borrow(), |c| {
3518            c.as_ref().expect("computed above")
3519        }))
3520    }
3521
3522    fn beams(&self, params: &[f64], clocks: &Clocks, region: usize) -> Result<Beams, FittingError> {
3523        let place = &self.layout.regions[region];
3524        let densities = &params[place.densities.clone()];
3525        let sigma = place
3526            .temperature
3527            .map(|t| self.at(region, params[t], TOTAL))
3528            .transpose()?;
3529        let mut open: Vec<f64> = combined(&clocks.basis[region], &params[place.beam.clone()])
3530            .into_iter()
3531            .map(f64::exp)
3532            .collect();
3533        if let Some(sigma) = &self.filter {
3534            let density = params[self.layout.filter];
3535            for (phi, s) in open.iter_mut().zip(sigma) {
3536                *phi *= (-density * s).exp();
3537            }
3538        }
3539        let normalized: Vec<f64> = open
3540            .iter()
3541            .map(|phi| self.charge_ratio * params[self.layout.normalization] * phi)
3542            .collect();
3543        let terms = &params[place.background..place.background + 5];
3544        let exponential = self.exponential(terms[4]);
3545        let variance = place.thickness.map_or(0.0, |v| params[v]);
3546        let capture_sigma = match place.temperature {
3547            Some(t) if place.capture_on => Some(self.at(region, params[t], CAPTURE)?),
3548            _ => None,
3549        };
3550        let efficiency = params[place.capture];
3551        let n = normalized.len();
3552        let depths: Vec<f64> = (0..n)
3553            .map(|j| {
3554                sigma
3555                    .iter()
3556                    .flat_map(|sigma| densities.iter().zip(&sigma.values))
3557                    .map(|(n, sigma)| n * sigma[j])
3558                    .sum()
3559            })
3560            .collect();
3561        let elastic = match place.temperature {
3562            Some(t) if place.scatter_on => Some(self.at(region, params[t], ELASTIC)?),
3563            _ => None,
3564        };
3565        let acceptance = params[place.scatter];
3566        let mut scatter = elastic
3567            .as_ref()
3568            .map(|_| {
3569                Ok::<_, FittingError>(Scattered {
3570                    per_acceptance: Vec::with_capacity(n),
3571                    shares: self.absorbers[region]
3572                        .isotopes
3573                        .iter()
3574                        .map(|isotope| {
3575                            forward_yield(&self.flight_energies, &depths, isotope.awr)
3576                                .map_err(|e| FittingError::EvaluationFailed(e.to_string()))
3577                        })
3578                        .collect::<Result<_, _>>()?,
3579                })
3580            })
3581            .transpose()?;
3582        let (mut sample, mut per_depth, mut per_variance) = (
3583            Vec::with_capacity(n),
3584            Vec::with_capacity(n),
3585            Vec::with_capacity(n),
3586        );
3587        let mut capture = capture_sigma.as_ref().map(|_| Captured {
3588            per_efficiency: Vec::with_capacity(n),
3589            per_depth: Vec::with_capacity(n),
3590            share: Vec::with_capacity(n),
3591            per_variance: Vec::with_capacity(n),
3592        });
3593        for (j, beam) in normalized.iter().enumerate() {
3594            let depth = depths[j];
3595            let mut captured = 0.0;
3596            if let (Some(capture), Some(capture_sigma)) = (capture.as_mut(), &capture_sigma) {
3597                let absorbing: f64 = densities
3598                    .iter()
3599                    .zip(&capture_sigma.values)
3600                    .map(|(n, sigma)| n * sigma[j])
3601                    .sum();
3602                let (fraction, along_depth, along_variance) =
3603                    interacting_per_depth(depth, variance);
3604                captured = efficiency * absorbing * fraction;
3605                capture.per_efficiency.push(beam * absorbing * fraction);
3606                capture
3607                    .per_depth
3608                    .push(beam * efficiency * absorbing * along_depth);
3609                capture.share.push(beam * efficiency * fraction);
3610                capture
3611                    .per_variance
3612                    .push(beam * efficiency * absorbing * along_variance);
3613            }
3614            let background: f64 = terms
3615                .iter()
3616                .zip(&self.shapes)
3617                .map(|(b, g)| b * g[j])
3618                .sum::<f64>()
3619                + terms[3] * exponential[j];
3620            let mut scattered = 0.0;
3621            if let (Some(scatter), Some(elastic)) = (scatter.as_mut(), &elastic) {
3622                let per_acceptance: f64 = densities
3623                    .iter()
3624                    .zip(&elastic.values)
3625                    .zip(&scatter.shares)
3626                    .map(|((n, sigma), share)| n * sigma[j] * share.share[j])
3627                    .sum();
3628                scattered = acceptance * per_acceptance;
3629                scatter.per_acceptance.push(beam * per_acceptance);
3630            }
3631            let (transmission, along_depth, along_variance) = uneven_transmission(depth, variance);
3632            sample.push(beam * (transmission + background + captured + scattered));
3633            per_depth.push(beam * along_depth);
3634            per_variance.push(beam * along_variance);
3635        }
3636        Ok(Beams {
3637            open,
3638            normalized,
3639            sample,
3640            per_depth,
3641            per_variance,
3642            capture,
3643            scatter,
3644        })
3645    }
3646
3647    /// The slope of the counts of every bin of both runs of every region, in
3648    /// one resonance parameter of region `region`'s isotope `isotope`, from the
3649    /// isotope's data with the parameter moved by `+h` and by `−h`.
3650    fn resonance_slope(
3651        &self,
3652        params: &[f64],
3653        region: usize,
3654        isotope: usize,
3655        [up, down]: [&ResonanceData; 2],
3656        h: f64,
3657    ) -> Result<Vec<f64>, PipelineError> {
3658        let total = self.arriving_resonance_slope(params, region, isotope, [up, down], h)?;
3659        if let Some(shares) = &self.mixing {
3660            return Ok(mixed(shares, params[self.layout.spread], &total));
3661        }
3662        let Some(furnace) = &self.scattered else {
3663            return Ok(total);
3664        };
3665        let local = if furnace.local_photons {
3666            self.arriving_resonance_slope(
3667                &self.without_photons(params),
3668                region,
3669                isotope,
3670                [up, down],
3671                h,
3672            )?
3673        } else {
3674            total.clone()
3675        };
3676        Ok(add_scaled(
3677            total,
3678            params[self.layout.environment],
3679            furnace.change(&local, true, &self.layout.regions),
3680        ))
3681    }
3682
3683    fn arriving_resonance_slope(
3684        &self,
3685        params: &[f64],
3686        region: usize,
3687        isotope: usize,
3688        [up, down]: [&ResonanceData; 2],
3689        h: f64,
3690    ) -> Result<Vec<f64>, PipelineError> {
3691        let place = &self.layout.regions[region];
3692        let temperature = params[place.temperature.expect("a material")];
3693        let density = params[place.densities.start + isotope];
3694        let clocks = self.clocks(params)?;
3695        let scale = clocks.of(region);
3696        let beams = self.beams(params, &clocks, region)?;
3697        let slope = |channel| -> Result<Vec<f64>, PipelineError> {
3698            let lattice = self.absorbers[region].lattice.as_ref();
3699            let sigma = |data| {
3700                broadened(&self.energies, data, temperature, channel, lattice)
3701                    .map(|b| b.values)
3702                    .map_err(|e| PipelineError::Fitting(FittingError::EvaluationFailed(e)))
3703            };
3704            let (up, down) = (sigma(up)?, sigma(down)?);
3705            Ok(up
3706                .iter()
3707                .zip(&down)
3708                .rev()
3709                .map(|(u, d)| density * (u - d) / (2.0 * h))
3710                .collect())
3711        };
3712        let total = slope(Channel::Total)?;
3713        let mut column: Vec<f64> = total
3714            .iter()
3715            .zip(&beams.per_depth)
3716            .map(|(s, t)| -t * s)
3717            .collect();
3718        if let Some(capture) = &beams.capture {
3719            let captured = slope(Channel::Capture)?;
3720            for (j, c) in column.iter_mut().enumerate() {
3721                *c += capture.per_depth[j] * total[j] + capture.share[j] * captured[j];
3722            }
3723        }
3724        if let Some(scatter) = &beams.scatter {
3725            let scattered = slope(Channel::Elastic)?;
3726            let elastic = self.at(region, temperature, ELASTIC)?;
3727            let densities = &params[place.densities.clone()];
3728            for (j, c) in column.iter_mut().enumerate() {
3729                let mut through = scattered[j] * scatter.shares[isotope].share[j];
3730                for (m, share) in scatter.shares.iter().enumerate() {
3731                    let entry = share.per_entry[j] * total[j]
3732                        + share.per_exit[j]
3733                            .iter()
3734                            .map(|&(l, w)| w * total[l])
3735                            .sum::<f64>();
3736                    through += densities[m] * elastic.values[m][j] * entry;
3737                }
3738                *c += beams.normalized[j] * params[place.scatter] * through;
3739            }
3740        }
3741        let folded = predicted(&scale.rows, &column)?;
3742        let bins = folded.len();
3743        let mut arriving = vec![0.0; 2 * bins * self.layout.regions.len()];
3744        arriving[(2 * region + 1) * bins..(2 * region + 2) * bins].copy_from_slice(&folded);
3745        Ok(arriving)
3746    }
3747
3748    /// The time background per pixel that `region` records, and its slopes
3749    /// in `[C, A, τ, D]`.
3750    fn time_background(&self, params: &[f64], region: usize) -> (Vec<f64>, [Vec<f64>; 4]) {
3751        let at = self.layout.time_background;
3752        let bins = late(&self.bins, params[self.layout.regions[region].offset]);
3753        let terms = [params[at], params[at + 1], params[at + 2], params[at + 3]];
3754        time_counts_per_pixel(&bins, terms, span_us(&self.bins))
3755    }
3756
3757    fn exponential(&self, f: f64) -> Vec<f64> {
3758        self.shapes[1]
3759            .iter()
3760            .map(|root| (-f * root).exp())
3761            .collect()
3762    }
3763
3764    fn room_per_pixel(&self) -> [Vec<f64>; 2] {
3765        self.frames
3766            .map(|frames| self.bins.iter().map(|(_, width)| frames * width).collect())
3767    }
3768
3769    fn sample_time_scale(&self, params: &[f64], region: usize) -> f64 {
3770        let place = &self.layout.regions[region];
3771        self.charge_ratio * params[self.layout.normalization] * params[place.gamma] * place.pixels
3772    }
3773}
3774
3775impl RegionsModel {
3776    fn arriving(&self, params: &[f64], check_neutrons: bool) -> Result<Vec<f64>, FittingError> {
3777        let clocks = self.clocks(params)?;
3778        let [open_room, sample_room] = self.room_per_pixel();
3779        let rate = params[self.layout.room_background];
3780        if check_neutrons
3781            && let Some(NeutronSource::Measured(mean)) = self.scattered.as_ref().map(|f| &f.source)
3782            && let Some(k) = mean
3783                .iter()
3784                .zip(open_room.iter().chain(&sample_room))
3785                .position(|(m, exposure)| {
3786                    let neutrons = m - rate * exposure;
3787                    !neutrons.is_finite() || neutrons < 0.0
3788                })
3789        {
3790            let (run, bin) = (["open", "sample"][k / open_room.len()], k % open_room.len());
3791            return Err(FittingError::EvaluationFailed(format!(
3792                "invalid detector neutron counts after room subtraction in {run} bin {bin}"
3793            )));
3794        }
3795        let mut counts = Vec::new();
3796        for region in 0..self.absorbers.len() {
3797            let scale = clocks.of(region);
3798            let (background, _) = self.time_background(params, region);
3799            let Beams { open, sample, .. } = self.beams(params, &clocks, region)?;
3800            let pixels = self.layout.regions[region].pixels;
3801            let sample_scale = self.sample_time_scale(params, region);
3802            let open = predicted(&scale.rows, &open)?;
3803            let sample = predicted(&scale.rows, &sample)?;
3804            if check_neutrons {
3805                for (run, folded) in [("open", &open), ("sample", &sample)] {
3806                    if let Some(bin) = folded.iter().position(|v| !v.is_finite() || *v < 0.0) {
3807                        return Err(FittingError::EvaluationFailed(format!(
3808                            "invalid local neutron counts in region {region}, {run} bin {bin}"
3809                        )));
3810                    }
3811                }
3812            }
3813            counts.extend(
3814                open.iter()
3815                    .zip(&background)
3816                    .zip(&open_room)
3817                    .map(|((c, g), f)| c + pixels * (g + rate * f)),
3818            );
3819            counts.extend(
3820                sample
3821                    .iter()
3822                    .zip(&background)
3823                    .zip(&sample_room)
3824                    .map(|((c, g), f)| c + sample_scale * g + pixels * rate * f),
3825            );
3826        }
3827        Ok(counts)
3828    }
3829}
3830
3831/// The counts each region records, `(1 − h)·μ_r + h·Σ_q F_rq·μ_q` in every
3832/// bin of both runs, from the counts `μ` arriving in the regions' blocks in
3833/// turn.
3834fn mixed(shares: &[Vec<f64>], h: f64, arriving: &[f64]) -> Vec<f64> {
3835    let block = arriving.len() / shares.len();
3836    (0..arriving.len())
3837        .map(|i| {
3838            let (r, k) = (i / block, i % block);
3839            (1.0 - h) * arriving[i]
3840                + h * shares[r]
3841                    .iter()
3842                    .enumerate()
3843                    .map(|(q, f)| f * arriving[q * block + k])
3844                    .sum::<f64>()
3845        })
3846        .collect()
3847}
3848
3849fn add_scaled(mut total: Vec<f64>, scale: f64, delta: Vec<f64>) -> Vec<f64> {
3850    for (v, d) in total.iter_mut().zip(delta) {
3851        *v += scale * d;
3852    }
3853    total
3854}
3855
3856impl RegionsModel {
3857    fn without_photons(&self, params: &[f64]) -> Vec<f64> {
3858        let mut values = params.to_vec();
3859        for (role, value) in self.layout.roles.iter().zip(&mut values) {
3860            if role.photon_amplitude() {
3861                *value = 0.0;
3862            }
3863        }
3864        values
3865    }
3866}
3867
3868impl Role {
3869    fn photon_amplitude(&self) -> bool {
3870        matches!(
3871            self,
3872            Role::TimeBackground(0 | 1 | 3) | Role::CaptureGammas { .. }
3873        )
3874    }
3875}
3876
3877impl FitModel for RegionsModel {
3878    /// The counts each region records; under a spread or an environment
3879    /// scatter, a bin whose arriving counts are negative or not a number
3880    /// records them instead.
3881    fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
3882        let arriving = self.arriving(
3883            params,
3884            self.scattered.as_ref().is_some_and(|f| !f.local_photons),
3885        )?;
3886        let mut recorded = match (&self.mixing, &self.scattered) {
3887            (Some(shares), _) => mixed(shares, params[self.layout.spread], &arriving),
3888            (None, Some(furnace)) => {
3889                let local = if furnace.local_photons {
3890                    self.arriving(&self.without_photons(params), true)?
3891                } else {
3892                    arriving.clone()
3893                };
3894                add_scaled(
3895                    arriving.clone(),
3896                    params[self.layout.environment],
3897                    furnace.change(&local, false, &self.layout.regions),
3898                )
3899            }
3900            (None, None) => return Ok(arriving),
3901        };
3902        for (recorded, &arrived) in recorded.iter_mut().zip(&arriving) {
3903            if arrived.is_nan() || arrived < 0.0 {
3904                *recorded = arrived;
3905            }
3906        }
3907        Ok(recorded)
3908    }
3909
3910    fn analytical_jacobian(
3911        &self,
3912        params: &[f64],
3913        free_param_indices: &[usize],
3914        y_current: &[f64],
3915    ) -> Option<FlatMatrix> {
3916        let mut jacobian = self.arrival_jacobian(params, free_param_indices, y_current)?;
3917        let Some(furnace) = &self.scattered else {
3918            if let Some(shares) = &self.mixing {
3919                let arriving = self.arriving(params, false).ok()?;
3920                for (col, &index) in free_param_indices.iter().enumerate() {
3921                    let values = if index == self.layout.spread {
3922                        mixed(shares, 1.0, &arriving)
3923                            .iter()
3924                            .zip(&arriving)
3925                            .map(|(m, a)| m - a)
3926                            .collect()
3927                    } else {
3928                        let slope: Vec<_> =
3929                            (0..y_current.len()).map(|i| jacobian.get(i, col)).collect();
3930                        mixed(shares, params[self.layout.spread], &slope)
3931                    };
3932                    for (i, v) in values.into_iter().enumerate() {
3933                        *jacobian.get_mut(i, col) = v;
3934                    }
3935                }
3936            }
3937            return Some(jacobian);
3938        };
3939        let local_params = furnace.local_photons.then(|| self.without_photons(params));
3940        let local_jacobian = if let Some(p) = &local_params {
3941            Some(self.arrival_jacobian(p, free_param_indices, y_current)?)
3942        } else {
3943            None
3944        };
3945        for (col, &index) in free_param_indices.iter().enumerate() {
3946            let delta = if index == self.layout.environment {
3947                let local = self
3948                    .arriving(local_params.as_deref().unwrap_or(params), true)
3949                    .ok()?;
3950                furnace.change(&local, false, &self.layout.regions)
3951            } else {
3952                if self.layout.roles[index].photon_amplitude() {
3953                    continue;
3954                }
3955                let source = local_jacobian.as_ref().unwrap_or(&jacobian);
3956                let local: Vec<_> = (0..y_current.len()).map(|i| source.get(i, col)).collect();
3957                furnace
3958                    .change(&local, true, &self.layout.regions)
3959                    .into_iter()
3960                    .map(|v| v * params[self.layout.environment])
3961                    .collect()
3962            };
3963            for (i, d) in delta.into_iter().enumerate() {
3964                *jacobian.get_mut(i, col) += d;
3965            }
3966        }
3967        Some(jacobian)
3968    }
3969}
3970
3971impl RegionsModel {
3972    fn arrival_jacobian(
3973        &self,
3974        params: &[f64],
3975        free_param_indices: &[usize],
3976        y_current: &[f64],
3977    ) -> Option<FlatMatrix> {
3978        let layout = &*self.layout;
3979        let flight_path_m = params[layout.flight_path];
3980        let clocks = self.clocks(params).ok()?;
3981        let regions = self.absorbers.len();
3982        let beams: Vec<Beams> = (0..regions)
3983            .map(|region| self.beams(params, &clocks, region))
3984            .collect::<Result<_, _>>()
3985            .ok()?;
3986        let bins = y_current.len() / (2 * regions);
3987        let (open_rows, sample_rows) = (|r: usize| 2 * r * bins, |r: usize| (2 * r + 1) * bins);
3988        let counts = |r: usize, values: &[f64]| predicted(&clocks.of(r).rows, values).ok();
3989        let times = |beam: &[f64], slope: &[f64]| -> Vec<f64> {
3990            beam.iter().zip(slope).map(|(b, s)| b * s).collect()
3991        };
3992        let groups = clocks.scales.len();
3993        let mut arrival: Vec<Option<Rows>> = (0..groups).map(|_| None).collect();
3994        let mut pulse_slopes: Vec<Option<[Rows; 4]>> = (0..groups).map(|_| None).collect();
3995        let mut tail_slopes: Vec<Option<[Rows; 2]>> = (0..groups).map(|_| None).collect();
3996        let ones = vec![1.0; self.energies.len()];
3997        let root_energy = &self.shapes[2];
3998        let constant = || [ones.clone(), vec![0.0; ones.len()]];
3999        let [low, high] = self.layout.storage_span.map_or_else(constant, |span| {
4000            let [first, last] = [span.0, span.1].map(f64::sqrt);
4001            let share: Vec<f64> = root_energy
4002                .iter()
4003                .map(|root| (root - first) / (last - first))
4004                .collect();
4005            [share.iter().map(|s| 1.0 - s).collect(), share]
4006        });
4007        // ∂(a0·E^p + a1)/∂a0 = E^p and ∂/∂p = a0·E^p·ln E.
4008        let power = |a0: f64, exponent: f64| -> [Vec<f64>; 2] {
4009            let unit = EnergyLaw::PowerE {
4010                a0: 1.0,
4011                a1: 0.0,
4012                exponent,
4013            };
4014            let power: Vec<f64> = self.flight_energies.iter().map(|&e| unit.eval(e)).collect();
4015            let slope = power
4016                .iter()
4017                .zip(&self.flight_energies)
4018                .map(|(power, e)| a0 * power * e.ln())
4019                .collect();
4020            [power, slope]
4021        };
4022        let numbers = &params[layout.pulse..];
4023        let [alpha_power, alpha_exponent] = power(numbers[0], numbers[9]);
4024        let [beta_power, beta_exponent] = power(numbers[2], numbers[10]);
4025        let pulse_columns: [(usize, &[f64]); 11] = [
4026            (0, &alpha_power),
4027            (0, &ones),
4028            (1, &beta_power),
4029            (1, &ones),
4030            (2, &low),
4031            (3, &ones),
4032            (2, &high),
4033            (4, &ones),
4034            (5, &ones),
4035            (0, &alpha_exponent),
4036            (1, &beta_exponent),
4037        ];
4038        let backgrounds: Vec<(Vec<f64>, [Vec<f64>; 4])> = (0..regions)
4039            .map(|r| self.time_background(params, r))
4040            .collect();
4041        let scaled = |factor: f64, values: &[f64]| -> Vec<f64> {
4042            values.iter().map(|v| factor * v).collect()
4043        };
4044        let mut jacobian = FlatMatrix::zeros(y_current.len(), free_param_indices.len());
4045        for (col, &index) in free_param_indices.iter().enumerate() {
4046            let blocks: Vec<(usize, Vec<f64>)> = match layout.roles[index] {
4047                Role::Beam {
4048                    region,
4049                    coefficient,
4050                } => {
4051                    let slope = weights_of(&clocks.basis[region], coefficient);
4052                    let Beams { open, sample, .. } = &beams[region];
4053                    vec![
4054                        (open_rows(region), counts(region, &times(open, &slope))?),
4055                        (sample_rows(region), counts(region, &times(sample, &slope))?),
4056                    ]
4057                }
4058                Role::Density { region, isotope } => {
4059                    let temperature = params[layout.regions[region].temperature?];
4060                    let sigma = self.at(region, temperature, TOTAL).ok()?;
4061                    let total = &sigma.values[isotope];
4062                    let mut column: Vec<f64> = beams[region]
4063                        .per_depth
4064                        .iter()
4065                        .zip(total)
4066                        .map(|(d, s)| -d * s)
4067                        .collect();
4068                    if let Some(capture) = &beams[region].capture {
4069                        let captures = self.at(region, temperature, CAPTURE).ok()?;
4070                        for (j, c) in column.iter_mut().enumerate() {
4071                            *c += capture.per_depth[j] * total[j]
4072                                + capture.share[j] * captures.values[isotope][j];
4073                        }
4074                    }
4075                    if let Some(scatter) = &beams[region].scatter {
4076                        let place = &layout.regions[region];
4077                        let elastic = self.at(region, temperature, ELASTIC).ok()?;
4078                        let densities = &params[place.densities.clone()];
4079                        for (j, c) in column.iter_mut().enumerate() {
4080                            let mut slope =
4081                                elastic.values[isotope][j] * scatter.shares[isotope].share[j];
4082                            for (m, share) in scatter.shares.iter().enumerate() {
4083                                let through = share.per_entry[j] * total[j]
4084                                    + share.per_exit[j]
4085                                        .iter()
4086                                        .map(|&(l, w)| w * total[l])
4087                                        .sum::<f64>();
4088                                slope += densities[m] * elastic.values[m][j] * through;
4089                            }
4090                            *c += beams[region].normalized[j] * params[place.scatter] * slope;
4091                        }
4092                    }
4093                    vec![(sample_rows(region), counts(region, &column)?)]
4094                }
4095                Role::Temperature { region } => {
4096                    let place = &layout.regions[region];
4097                    let sigma = self.at(region, params[index], TOTAL).ok()?;
4098                    let densities = &params[place.densities.clone()];
4099                    let along = |slopes: &[Vec<f64>], j: usize| -> f64 {
4100                        densities
4101                            .iter()
4102                            .zip(slopes)
4103                            .map(|(n, slope)| n * slope[j])
4104                            .sum()
4105                    };
4106                    let mut column: Vec<f64> = (0..self.energies.len())
4107                        .map(|j| -beams[region].per_depth[j] * along(&sigma.slopes, j))
4108                        .collect();
4109                    if let Some(capture) = &beams[region].capture {
4110                        let captures = self.at(region, params[index], CAPTURE).ok()?;
4111                        for (j, c) in column.iter_mut().enumerate() {
4112                            *c += capture.per_depth[j] * along(&sigma.slopes, j)
4113                                + capture.share[j] * along(&captures.slopes, j);
4114                        }
4115                    }
4116                    if let Some(scatter) = &beams[region].scatter {
4117                        let elastic = self.at(region, params[index], ELASTIC).ok()?;
4118                        let depth_slopes: Vec<f64> = (0..self.energies.len())
4119                            .map(|j| along(&sigma.slopes, j))
4120                            .collect();
4121                        for (j, c) in column.iter_mut().enumerate() {
4122                            let mut slope = 0.0;
4123                            for (m, share) in scatter.shares.iter().enumerate() {
4124                                let through = share.per_entry[j] * depth_slopes[j]
4125                                    + share.per_exit[j]
4126                                        .iter()
4127                                        .map(|&(l, w)| w * depth_slopes[l])
4128                                        .sum::<f64>();
4129                                slope += densities[m]
4130                                    * (elastic.slopes[m][j] * share.share[j]
4131                                        + elastic.values[m][j] * through);
4132                            }
4133                            *c += beams[region].normalized[j] * params[place.scatter] * slope;
4134                        }
4135                    }
4136                    vec![(sample_rows(region), counts(region, &column)?)]
4137                }
4138                Role::ThicknessVariance { region } => {
4139                    let mut column = beams[region].per_variance.clone();
4140                    if let Some(capture) = &beams[region].capture {
4141                        for (c, v) in column.iter_mut().zip(&capture.per_variance) {
4142                            *c += v;
4143                        }
4144                    }
4145                    vec![(sample_rows(region), counts(region, &column)?)]
4146                }
4147                Role::CaptureGammas { region } => vec![(
4148                    sample_rows(region),
4149                    match &beams[region].capture {
4150                        Some(capture) => counts(region, &capture.per_efficiency)?,
4151                        None => vec![0.0; bins],
4152                    },
4153                )],
4154                Role::InScatter { region } => vec![(
4155                    sample_rows(region),
4156                    match &beams[region].scatter {
4157                        Some(scatter) => counts(region, &scatter.per_acceptance)?,
4158                        None => vec![0.0; bins],
4159                    },
4160                )],
4161                Role::Normalization => {
4162                    let slope = vec![1.0 / params[index]; self.energies.len()];
4163                    (0..regions)
4164                        .map(|r| {
4165                            let place = &layout.regions[r];
4166                            let gamma = self.charge_ratio * params[place.gamma] * place.pixels;
4167                            let beam = counts(r, &times(&beams[r].sample, &slope))?;
4168                            let column = beam
4169                                .iter()
4170                                .zip(&backgrounds[r].0)
4171                                .map(|(b, g)| b + gamma * g)
4172                                .collect();
4173                            Some((sample_rows(r), column))
4174                        })
4175                        .collect::<Option<_>>()?
4176                }
4177                Role::Background { region, term } => {
4178                    let at = layout.regions[region].background;
4179                    let (d, f) = (params[at + 3], params[at + 4]);
4180                    let shape: Vec<f64> = match term {
4181                        3 => self.exponential(f),
4182                        4 => self
4183                            .exponential(f)
4184                            .iter()
4185                            .zip(&self.shapes[1])
4186                            .map(|(x, root)| -d * root * x)
4187                            .collect(),
4188                        _ => self.shapes[term].clone(),
4189                    };
4190                    vec![(
4191                        sample_rows(region),
4192                        counts(region, &times(&beams[region].normalized, &shape))?,
4193                    )]
4194                }
4195                Role::GammaTransmission { region } => vec![(
4196                    sample_rows(region),
4197                    scaled(
4198                        self.charge_ratio
4199                            * params[layout.normalization]
4200                            * layout.regions[region].pixels,
4201                        &backgrounds[region].0,
4202                    ),
4203                )],
4204                Role::TimeBackground(term) => (0..regions)
4205                    .flat_map(|r| {
4206                        let slope = &backgrounds[r].1[term];
4207                        [
4208                            (open_rows(r), scaled(layout.regions[r].pixels, slope)),
4209                            (
4210                                sample_rows(r),
4211                                scaled(self.sample_time_scale(params, r), slope),
4212                            ),
4213                        ]
4214                    })
4215                    .collect(),
4216                Role::SpreadShare | Role::ScatterFraction => vec![],
4217                Role::Filter => match &self.filter {
4218                    Some(sigma) => (0..regions)
4219                        .map(|r| {
4220                            let less = |beam: &[f64]| -> Vec<f64> {
4221                                beam.iter().zip(sigma).map(|(b, s)| -b * s).collect()
4222                            };
4223                            Some([
4224                                (open_rows(r), counts(r, &less(&beams[r].open))?),
4225                                (sample_rows(r), counts(r, &less(&beams[r].sample))?),
4226                            ])
4227                        })
4228                        .collect::<Option<Vec<_>>>()?
4229                        .concat(),
4230                    None => vec![],
4231                },
4232                Role::RoomBackground => {
4233                    let [open_room, sample_room] = self.room_per_pixel();
4234                    (0..regions)
4235                        .flat_map(|r| {
4236                            let pixels = layout.regions[r].pixels;
4237                            [
4238                                (open_rows(r), scaled(pixels, &open_room)),
4239                                (sample_rows(r), scaled(pixels, &sample_room)),
4240                            ]
4241                        })
4242                        .collect()
4243                }
4244                Role::Pulse(number) => {
4245                    let (law, weight) = pulse_columns[number];
4246                    let mut blocks = Vec::with_capacity(2 * regions);
4247                    for (r, region) in beams.iter().enumerate() {
4248                        let (group, scale) = (clocks.of_region[r], clocks.of(r));
4249                        let rows = if law < 4 {
4250                            if pulse_slopes[group].is_none() {
4251                                pulse_slopes[group] = Some(
4252                                    self.grid
4253                                        .pulse_slopes_at(scale.t0_us, flight_path_m, &scale.pulse)
4254                                        .ok()?,
4255                                );
4256                            }
4257                            &pulse_slopes[group].as_ref()?[law]
4258                        } else {
4259                            if tail_slopes[group].is_none() {
4260                                tail_slopes[group] = Some(
4261                                    self.grid
4262                                        .tail_slopes_at(scale.t0_us, flight_path_m, &scale.pulse)
4263                                        .ok()?,
4264                                );
4265                            }
4266                            &tail_slopes[group].as_ref()?[law - 4]
4267                        };
4268                        for (row, beam) in [
4269                            (open_rows(r), &region.open),
4270                            (sample_rows(r), &region.sample),
4271                        ] {
4272                            blocks.push((row, predicted(rows, &times(beam, weight)).ok()?));
4273                        }
4274                    }
4275                    blocks
4276                }
4277                Role::T0 | Role::FlightPath | Role::TimingOffset { .. } => {
4278                    let only = match layout.roles[index] {
4279                        Role::TimingOffset { region } => Some(region),
4280                        _ => None,
4281                    };
4282                    let (reach, per_metre): (Vec<f64>, Option<f64>) = match layout.roles[index] {
4283                        Role::FlightPath => (
4284                            self.grid
4285                                .flight_times_us()
4286                                .iter()
4287                                .map(|u| u / self.grid.flight_path_m())
4288                                .collect(),
4289                            Some(flight_path_m),
4290                        ),
4291                        _ => (ones.clone(), None),
4292                    };
4293                    let at = layout.time_background;
4294                    let per_late = params[at + 1] / params[at + 2];
4295                    let per_drift = params[at + 3] / span_us(&self.bins);
4296                    let mut blocks = Vec::with_capacity(2 * regions);
4297                    for r in (0..regions).filter(|&r| only.is_none_or(|region| region == r)) {
4298                        let (group, scale) = (clocks.of_region[r], clocks.of(r));
4299                        if arrival[group].is_none() {
4300                            arrival[group] = Some(
4301                                self.grid
4302                                    .arrival_slopes_at(scale.t0_us, flight_path_m, &scale.pulse)
4303                                    .ok()?,
4304                            );
4305                        }
4306                        let arrival = arrival[group].as_ref()?;
4307                        let log_beam_slope = combined(
4308                            &clocks.basis_slope[r],
4309                            &params[layout.regions[r].beam.clone()],
4310                        );
4311                        for (row, beam, background) in [
4312                            (open_rows(r), &beams[r].open, layout.regions[r].pixels),
4313                            (
4314                                sample_rows(r),
4315                                &beams[r].sample,
4316                                self.sample_time_scale(params, r),
4317                            ),
4318                        ] {
4319                            let reached = times(beam, &reach);
4320                            let beam_part = counts(r, &times(&reached, &log_beam_slope))?;
4321                            let pulse_part = predicted(arrival, &reached).ok()?;
4322                            let mut column: Vec<f64> = beam_part
4323                                .iter()
4324                                .zip(&pulse_part)
4325                                .map(|(b, p)| b + p)
4326                                .collect();
4327                            if let Some(flight_path_m) = per_metre {
4328                                for (c, x) in column.iter_mut().zip(counts(r, beam)?) {
4329                                    *c += x / flight_path_m;
4330                                }
4331                            }
4332                            if only.is_some() {
4333                                let [widths, integrals, ..] = &backgrounds[r].1;
4334                                for ((c, x), w) in column.iter_mut().zip(integrals).zip(widths) {
4335                                    *c += background * (per_late * x - per_drift * w);
4336                                }
4337                            }
4338                            blocks.push((row, column));
4339                        }
4340                    }
4341                    blocks
4342                }
4343            };
4344            for (row, column) in blocks {
4345                for (offset, value) in column.into_iter().enumerate() {
4346                    *jacobian.get_mut(row + offset, col) = value;
4347                }
4348            }
4349        }
4350        Some(jacobian)
4351    }
4352}
4353
4354#[cfg(test)]
4355mod tests {
4356    use nereids_endf::resonance::test_support::synthetic_isotope;
4357
4358    use faer::Side;
4359    use faer::linalg::solvers::DenseSolveCore;
4360
4361    use super::*;
4362    use crate::open_beam::Pulse;
4363    use crate::open_beam::tests::{ALPHA, BETA, EDGES_US, FLIGHT_PATH_M, R, T0_US, grid};
4364
4365    #[test]
4366    fn a_fitted_temperature_starts_its_second_fit_hot_within_its_bounds() {
4367        let region = |temperature_k| Region {
4368            open_counts: Vec::new(),
4369            sample_counts: Vec::new(),
4370            open_live: None,
4371            sample_live: None,
4372            background: [Value::Known(0.0); 5],
4373            pixels: 1.0,
4374            gamma_transmission: Value::Known(1.0),
4375            capture_gammas: Value::Known(0.0),
4376            in_scatter: Value::Known(0.0),
4377            timing_offset_us: Value::Known(0.0),
4378            material: Some(Material {
4379                covariances: Vec::new(),
4380                library: EndfLibrary::EndfB8_0,
4381                excluded_ranges: Vec::new(),
4382                isotopes: vec![(
4383                    synthetic_isotope(72, 180, 20.0, 0.01, 0.06),
4384                    Value::Fitted(1e-4),
4385                )],
4386                temperature_k,
4387                thickness_variance: Value::Known(0.0),
4388                lattice: None,
4389            }),
4390        };
4391        let started = |temperatures: &[Value]| {
4392            let measurement = Measurement {
4393                time_edges_us: Vec::new(),
4394                charge_ratio: 1.0,
4395                normalization: Value::Known(1.0),
4396                time_background: NO_TIME_BACKGROUND,
4397                room_background: None,
4398                spread: None,
4399                environment_scatter: None,
4400                filter: None,
4401                regions: temperatures.iter().map(|&t| region(t)).collect(),
4402            };
4403            started_hot(&measurement).map(|hot| {
4404                hot.regions
4405                    .iter()
4406                    .map(|r| r.material.as_ref().expect("material").temperature_k)
4407                    .collect::<Vec<_>>()
4408            })
4409        };
4410        let within = |start| Value::Within {
4411            start,
4412            lower: 250.0,
4413            upper: 400.0,
4414        };
4415        assert_eq!(
4416            started(&[Value::Fitted(300.0), Value::Known(300.0), within(300.0)]),
4417            Some(vec![
4418                Value::Fitted(2500.0),
4419                Value::Known(300.0),
4420                within(400.0)
4421            ])
4422        );
4423        let measured = Value::Measured {
4424            value: 300.0,
4425            sd: 3.0,
4426        };
4427        assert_eq!(
4428            started(&[Value::Fitted(2500.0), within(400.0), measured]),
4429            None
4430        );
4431    }
4432
4433    #[test]
4434    fn the_jacobian_is_the_slope_of_every_region_s_counts() {
4435        for channel_fwhm_us in [None, Some(0.35)] {
4436            let lattice = channel_fwhm_us
4437                .is_none()
4438                .then(|| PhononSpectrum::debye(240.0, 200).expect("Debye"));
4439            let grid = grid(channel_fwhm_us);
4440            if channel_fwhm_us.is_some() {
4441                let rows = 2 * (grid.time_edges_us().len() - 1);
4442                let measured = (0..rows)
4443                    .map(|k| 1000.0 + 5.0 * (0.7 * k as f64).cos())
4444                    .collect();
4445                for source in [
4446                    NeutronSource::Measured(measured),
4447                    NeutronSource::AreaFractions(vec![4.0 / 15.0, 9.0 / 15.0, 2.0 / 15.0]),
4448                ] {
4449                    jacobian_against_central_differences(&grid, None, Some(source));
4450                }
4451            } else {
4452                jacobian_against_central_differences(&grid, lattice, None);
4453            }
4454        }
4455        let bins = starts_and_widths_us(&[350.0, 351.0, 400.0, 470.0]);
4456        let span = span_us(&bins);
4457        let ramp = Bypass {
4458            time: [0.0, 0.0, 1.0, 20.0],
4459            room: 0.0,
4460        };
4461        let shifted = ramp.open_counts_per_pixel(&bins, 2.0, 0.0);
4462        let (start, width) = bins[bins.len() - 1];
4463        let exact = 20.0 * width * (start - 2.0 + 0.5 * width) / span;
4464        assert!(
4465            (shifted[bins.len() - 1] / exact - 1.0).abs() <= 1e-12,
4466            "{shifted:?}"
4467        );
4468        let (_, slopes) = time_counts_per_pixel(&bins, [1.0, 2.0, f64::MIN_POSITIVE, 0.0], span);
4469        assert!(slopes.iter().flatten().all(|s| s.is_finite()), "{slopes:?}");
4470        let (counts, _) = time_counts_per_pixel(&bins, [1.0, 2.0, f64::MAX, 0.0], span);
4471        for (count, (_, width)) in counts.iter().zip(&bins) {
4472            assert!((count / (3.0 * width) - 1.0).abs() <= 1e-12, "{counts:?}");
4473        }
4474    }
4475
4476    #[test]
4477    fn a_region_records_the_time_background_its_timing_offset_late() {
4478        let grid = grid(None);
4479        let (_, u_hi) = grid.range_us();
4480        let beams = [BeamSpline::constant(347.0, u_hi, 1.0e4)];
4481        let layout = Arc::new(Layout::new(
4482            roles(&[beams[0].coefficients().len()], &[None]),
4483            &[1.0],
4484            &[[false; 2]],
4485        ));
4486        let ([c, a, tau, d], late) = ([2000.0, 30000.0, 10.0, -300.0], 0.3);
4487        let params: Vec<f64> = layout
4488            .roles
4489            .iter()
4490            .map(|role| match *role {
4491                Role::TimingOffset { .. } => late,
4492                Role::TimeBackground(term) => [c, a, tau, d][term],
4493                Role::T0 => T0_US,
4494                Role::FlightPath => FLIGHT_PATH_M,
4495                _ => 0.0,
4496            })
4497            .collect();
4498        let model = RegionsModel::new(
4499            &grid,
4500            &beams,
4501            &[Arc::new([])],
4502            (1.2, [0.0; 2]),
4503            T0_US,
4504            &layout,
4505        );
4506        let (recorded, _) = model.time_background(&params, 0);
4507        let edges = grid.time_edges_us();
4508        let span = edges[edges.len() - 1] - edges[0];
4509        let rate = |t: f64| {
4510            c + d * (t - late - edges[0]) / span + a * (-(t - late - edges[0]) / tau).exp()
4511        };
4512        for (k, counts) in recorded.iter().enumerate() {
4513            let h = (edges[k + 1] - edges[k]) / 64.0;
4514            let simpson: f64 = (0..64)
4515                .map(|i| edges[k] + h * f64::from(i))
4516                .map(|t| h / 6.0 * (rate(t) + 4.0 * rate(t + 0.5 * h) + rate(t + h)))
4517                .sum();
4518            assert!(
4519                (counts / simpson - 1.0).abs() <= 1e-12,
4520                "{k}: {counts} {simpson}"
4521            );
4522        }
4523    }
4524
4525    #[test]
4526    fn under_a_spread_a_negative_arriving_count_is_recorded_as_it_arrives() {
4527        let grid = grid(None);
4528        let (_, u_hi) = grid.range_us();
4529        let beams = [
4530            BeamSpline::constant(347.0, u_hi, 1.0e5),
4531            BeamSpline::constant(347.0, u_hi, 1.0e4),
4532        ];
4533        let layout = Arc::new(Layout::new(
4534            roles(&[beams[0].coefficients().len(); 2], &[None, None]),
4535            &[400.0, 1.0],
4536            &[[false; 2]; 2],
4537        ));
4538        let params: Vec<f64> = layout
4539            .roles
4540            .iter()
4541            .enumerate()
4542            .map(|(i, role)| match *role {
4543                Role::Beam { region, .. } => [12.0, 9.0][region] + 0.3 * (i as f64).sin(),
4544                Role::Background { region, term } => {
4545                    [[0.0; 5], [-1.5, 0.0, 0.0, 0.0, 4.0]][region][term]
4546                }
4547                Role::GammaTransmission { .. } => 1.0,
4548                Role::Normalization => 0.93,
4549                Role::TimeBackground(term) => [50.0, 300.0, 40.0, -20.0][term],
4550                Role::SpreadShare => 0.5,
4551                Role::T0 => T0_US,
4552                Role::FlightPath => FLIGHT_PATH_M,
4553                Role::Pulse(n) => [0.37, 0.06, 0.01, 0.24, 0.16, 0.3, 0.0, 0.0, 1.0, 0.5, 0.5][n],
4554                _ => 0.0,
4555            })
4556            .collect();
4557        let model = RegionsModel::new(
4558            &grid,
4559            &beams,
4560            &[Arc::new([]), Arc::new([])],
4561            (1.2, [3.0e4, 2.5e4]),
4562            T0_US,
4563            &layout,
4564        )
4565        .spread(Some(Arc::new(vec![vec![0.9, 0.1], vec![0.1, 0.9]])));
4566        let arriving = model.arriving(&params, false).expect("arriving");
4567        let recorded = model.evaluate(&params).expect("recorded");
4568        let negative: Vec<usize> = (0..arriving.len()).filter(|&k| arriving[k] < 0.0).collect();
4569        assert!(!negative.is_empty());
4570        for k in negative {
4571            assert_eq!(recorded[k], arriving[k], "{k}");
4572        }
4573    }
4574
4575    #[test]
4576    fn a_resonance_slope_is_the_slope_of_the_sample_counts() {
4577        let grid = grid(None);
4578        let (_, u_hi) = grid.range_us();
4579        let beams = [
4580            BeamSpline::constant(347.0, u_hi, 1.0e4),
4581            BeamSpline::constant(347.0, u_hi, 2.0e4),
4582        ];
4583        let layout = Arc::new(Layout::new(
4584            roles(&[beams[0].coefficients().len(); 2], &[Some(1), None]),
4585            &[4.0, 9.0],
4586            &[[true; 2], [false; 2]],
4587        ));
4588        let params: Vec<f64> = layout
4589            .roles
4590            .iter()
4591            .enumerate()
4592            .map(|(i, role)| match *role {
4593                Role::Beam { .. } => 9.0 + 0.3 * (i as f64).sin(),
4594                Role::Density { .. } => 3.0e-4,
4595                Role::Temperature { .. } => 300.0,
4596                Role::ThicknessVariance { .. } => 0.02,
4597                Role::Normalization => 0.93,
4598                Role::Background { term, .. } => [0.05, 0.5, -0.01, 0.03, 4.0][term],
4599                Role::GammaTransmission { region } => [0.8, 1.0][region],
4600                Role::CaptureGammas { region } => [0.05, 0.0][region],
4601                Role::InScatter { region } => [0.3, 0.0][region],
4602                Role::TimingOffset { .. } => 0.02,
4603                Role::TimeBackground(term) => [50.0, 300.0, 40.0, -20.0][term],
4604                Role::RoomBackground => 2.0e-3,
4605                Role::SpreadShare => 0.15,
4606                Role::ScatterFraction => 0.25,
4607                Role::Filter => 0.0,
4608                Role::T0 => T0_US + 0.05,
4609                Role::FlightPath => FLIGHT_PATH_M + 0.003,
4610                Role::Pulse(n) => [0.37, 0.06, 0.01, 0.24, 0.16, 0.3, 0.0, 0.0, 1.0, 0.5, 0.5][n],
4611            })
4612            .collect();
4613        let data = synthetic_isotope(72, 180, 20.0, 0.01, 0.06);
4614        let model = |data: &ResonanceData, furnace: Option<&Arc<Furnace>>| {
4615            let isotopes: [Arc<[ResonanceData]>; 2] = [Arc::new([data.clone()]), Arc::new([])];
4616            let model = RegionsModel::new(
4617                &grid,
4618                &beams,
4619                &isotopes,
4620                (1.2, [3.0e4, 2.5e4]),
4621                T0_US,
4622                &layout,
4623            );
4624            match furnace {
4625                Some(f) => model.environment(Some(f.clone())),
4626                None => model.spread(Some(Arc::new(vec![vec![0.9, 0.1], vec![0.2, 0.8]]))),
4627            }
4628        };
4629        let h = 1e-4 * data.ranges[0].l_groups[0].resonances[0].gg;
4630        let moved = |by: f64| {
4631            let mut copy = data.clone();
4632            copy.ranges[0].l_groups[0].resonances[0].gg += by;
4633            copy
4634        };
4635        let (up, down) = (moved(h), moved(-h));
4636        let bins = grid.time_edges_us().len() - 1;
4637        let measured = vec![2000.0; 2 * bins];
4638        for source in [
4639            None,
4640            Some(NeutronSource::AreaFractions(vec![4.0 / 13.0, 9.0 / 13.0])),
4641            Some(NeutronSource::Measured(measured)),
4642        ] {
4643            let furnace = source.map(|source| {
4644                Arc::new(Furnace {
4645                    source,
4646                    local_photons: true,
4647                })
4648            });
4649            let slope = model(&data, furnace.as_ref())
4650                .resonance_slope(&params, 0, 0, [&up, &down], h)
4651                .expect("slope");
4652            let counts = |data| {
4653                model(data, furnace.as_ref())
4654                    .evaluate(&params)
4655                    .expect("counts")
4656            };
4657            let differences: Vec<f64> = counts(&up)
4658                .iter()
4659                .zip(&counts(&down))
4660                .map(|(u, d)| (u - d) / (2.0 * h))
4661                .collect();
4662            let column = differences.iter().fold(0.0_f64, |m, s| m.max(s.abs()));
4663            for (k, (&analytic, &difference)) in slope.iter().zip(&differences).enumerate() {
4664                assert!(
4665                    (analytic - difference).abs() <= 1e-6 * column,
4666                    "{k}: {analytic} vs {difference}"
4667                );
4668            }
4669        }
4670    }
4671
4672    fn jacobian_against_central_differences(
4673        grid: &Arc<FlightTimeGrid>,
4674        lattice: Option<PhononSpectrum>,
4675        source: Option<NeutronSource>,
4676    ) {
4677        let (_, u_hi) = grid.range_us();
4678        let coarse = BeamSpline::constant(347.0, u_hi, 1.0e4);
4679        let beams = [coarse.refined().refined(), coarse.clone(), coarse.refined()];
4680        let isotopes: [Arc<[ResonanceData]>; 3] = [
4681            Arc::new([
4682                synthetic_isotope(72, 180, 20.0, 0.01, 0.06),
4683                synthetic_isotope(74, 182, 20.3, 0.01, 0.06),
4684            ]),
4685            Arc::new([]),
4686            Arc::new([synthetic_isotope(74, 184, 20.6, 0.01, 0.06)]),
4687        ];
4688        let sizes: Vec<usize> = beams.iter().map(|b| b.coefficients().len()).collect();
4689        let mut layout = Layout::new(
4690            roles(&sizes, &[Some(2), None, Some(1)]),
4691            &[4.0, 9.0, 2.0],
4692            &[[true, true], [false, false], [true, true]],
4693        );
4694        layout.storage_span = Some(grid.pulse().energy_span_ev());
4695        let layout = Arc::new(layout);
4696        let params: Vec<f64> = layout
4697            .roles
4698            .iter()
4699            .enumerate()
4700            .map(|(i, role)| match *role {
4701                Role::Beam { .. } => 9.0 + 0.3 * (i as f64).sin(),
4702                Role::Density { region, isotope } => {
4703                    [[3.0e-4, 5.0e-4], [0.0; 2], [4.0e-4, 0.0]][region][isotope]
4704                }
4705                Role::Temperature { region } => [300.0, 0.0, 250.0][region],
4706                Role::ThicknessVariance { region } => [0.02, 0.0, 0.05][region],
4707                Role::Normalization => 0.93,
4708                Role::Background { region, term } => [
4709                    [0.05, 0.5, -0.01, 0.03, 4.0],
4710                    [0.02, 0.1, 0.003, -0.01, 2.0],
4711                    [0.04, -0.2, 0.005, 0.02, 6.0],
4712                ][region][term],
4713                Role::GammaTransmission { region } => [0.8, 1.0, 0.6][region],
4714                Role::CaptureGammas { region } => [0.05, 0.03, 0.02][region],
4715                Role::InScatter { region } => [0.3, 0.2, 0.4][region],
4716                Role::TimingOffset { region } => [0.03, 0.03, -0.02][region],
4717                Role::TimeBackground(term) => [50.0, 300.0, 40.0, -20.0][term],
4718                Role::RoomBackground => 2.0e-3,
4719                Role::SpreadShare => 0.15,
4720                Role::ScatterFraction => 0.12,
4721                Role::Filter => 2.0e-4,
4722                Role::T0 => T0_US + 0.05,
4723                Role::FlightPath => FLIGHT_PATH_M + 0.003,
4724                Role::Pulse(n) => [
4725                    0.37, 0.06, 0.01, 0.24, 0.16, 0.3, 0.25, 0.1, 1.5, 0.42, 0.58,
4726                ][n],
4727            })
4728            .collect();
4729        let model = RegionsModel::new(
4730            grid,
4731            &beams,
4732            &isotopes,
4733            (1.2, [3.0e4, 2.5e4]),
4734            T0_US,
4735            &layout,
4736        )
4737        .lattices(&[lattice, None, None])
4738        .filtered(Some(&Filter {
4739            isotopes: vec![(synthetic_isotope(48, 113, 19.8, 0.01, 0.06), 1.0)],
4740            areal_density: Value::Fitted(2.0e-4),
4741            temperature_k: 295.0,
4742        }))
4743        .expect("filter")
4744        .spread(source.is_none().then(|| {
4745            Arc::new(vec![
4746                vec![0.8, 0.1, 0.05],
4747                vec![0.1, 0.7, 0.1],
4748                vec![0.05, 0.15, 0.8],
4749            ])
4750        }))
4751        .environment(source.map(|source| {
4752            Arc::new(Furnace {
4753                source,
4754                local_photons: true,
4755            })
4756        }));
4757        let live: Vec<f64> = (0..model.evaluate(&params).expect("counts").len())
4758            .map(|k| 0.9 + 0.1 * (0.3 * k as f64).sin())
4759            .collect();
4760        let model = Recorded { model, live: &live };
4761        let mut elsewhere = params.clone();
4762        for t in layout
4763            .regions
4764            .iter()
4765            .filter_map(|region| region.temperature)
4766        {
4767            elsewhere[t] -= 50.0;
4768        }
4769        elsewhere[layout.t0] = T0_US - 0.05;
4770        elsewhere[layout.flight_path] = FLIGHT_PATH_M - 0.003;
4771        elsewhere[layout.pulse + 4] = 0.2;
4772        model.evaluate(&elsewhere).expect("counts");
4773        let counts = model.evaluate(&params).expect("counts");
4774        let indices: Vec<usize> = (0..params.len()).collect();
4775        let jacobian = model
4776            .analytical_jacobian(&params, &indices, &counts)
4777            .expect("jacobian");
4778        let middle_us = grid.flight_times_us()[grid.flight_times_us().len() / 2];
4779        for index in indices {
4780            let h = if index == layout.flight_path {
4781                params[index] * 1e-4 * params[layout.t0] / middle_us
4782            } else {
4783                1e-4 * params[index].abs()
4784            };
4785            let shifted = |d: f64| {
4786                let mut p = params.clone();
4787                p[index] += d;
4788                model.evaluate(&p).expect("counts")
4789            };
4790            let (up, down) = (shifted(h), shifted(-h));
4791            let slopes: Vec<f64> = up
4792                .iter()
4793                .zip(&down)
4794                .map(|(u, d)| (u - d) / (2.0 * h))
4795                .collect();
4796            let column = slopes.iter().fold(0.0_f64, |m, s| m.max(s.abs()));
4797            for (row, &slope) in slopes.iter().enumerate() {
4798                let analytic = jacobian.get(row, index);
4799                assert!(
4800                    (analytic - slope).abs() <= 1e-6 * column,
4801                    "{index} {row}: {analytic} vs {slope}"
4802                );
4803            }
4804        }
4805    }
4806
4807    #[test]
4808    fn each_region_s_terms_rebuild_the_joint_covariance() {
4809        let grid = Arc::new(grid(None).halved().expect("grid").halved().expect("grid"));
4810        let (_, u_hi) = grid.range_us();
4811        let beam = BeamSpline::constant(347.0, u_hi, 1.0e4).refined();
4812        let beams = [beam.clone(), beam.clone(), beam];
4813        let materials = [
4814            Some(synthetic_isotope(72, 180, 20.0, 0.01, 0.06)),
4815            Some(synthetic_isotope(74, 182, 24.0, 0.01, 0.06)),
4816            None,
4817        ];
4818        let isotopes: Vec<Arc<[ResonanceData]>> = materials
4819            .iter()
4820            .map(|m| m.iter().cloned().collect())
4821            .collect();
4822        let shape: Vec<Option<usize>> = materials.iter().map(|m| m.as_ref().map(|_| 1)).collect();
4823        let sizes: Vec<usize> = beams.iter().map(|b| b.coefficients().len()).collect();
4824        let layout = Arc::new(Layout::new(
4825            roles(&sizes, &shape),
4826            &[1.0; 3],
4827            &[[false; 2]; 3],
4828        ));
4829        let truth: Vec<f64> = layout
4830            .roles
4831            .iter()
4832            .map(|role| match *role {
4833                Role::Beam {
4834                    region,
4835                    coefficient,
4836                } => beams[region].coefficients()[coefficient],
4837                Role::Density { region, .. } => [5.0e-4, 4.0e-4, 0.0][region],
4838                Role::Temperature { .. } => 300.0,
4839                Role::ThicknessVariance { .. } => 0.0,
4840                Role::Normalization => 0.93,
4841                Role::Background { region, term } => [
4842                    [0.05, 0.0, 0.0, 0.0, 0.0],
4843                    [0.05, 0.0, 0.0, 0.0, 0.0],
4844                    [0.0; 5],
4845                ][region][term],
4846                Role::GammaTransmission { .. } => 1.0,
4847                Role::CaptureGammas { .. } => 0.0,
4848                Role::InScatter { .. } => 0.0,
4849                Role::TimingOffset { .. } => 0.0,
4850                Role::SpreadShare => 0.0,
4851                Role::ScatterFraction => 0.0,
4852                Role::Filter => 0.0,
4853                Role::TimeBackground(term) => [0.0, 0.0, 1.0, 0.0][term],
4854                Role::RoomBackground => 0.0,
4855                Role::T0 => T0_US,
4856                Role::FlightPath => FLIGHT_PATH_M,
4857                Role::Pulse(n) => [0.35, 0.05, 0.0, 0.25, 0.15, 0.0, 0.0, 0.0, 1.0, 0.5, 0.5][n],
4858            })
4859            .collect();
4860        let model = RegionsModel::new(&grid, &beams, &isotopes, (1.2, [0.0; 2]), T0_US, &layout);
4861        let bins = model.evaluate(&truth).expect("counts").len() / 6;
4862        let live: Vec<f64> = (0..6 * bins)
4863            .map(|k| 0.9 + 0.1 * (0.3 * k as f64).sin())
4864            .collect();
4865        let counts: Vec<f64> = Recorded { model, live: &live }
4866            .evaluate(&truth)
4867            .expect("counts")
4868            .iter()
4869            .enumerate()
4870            .map(|(k, mu)| (mu + 3.0 * mu.sqrt() * (1.7 * k as f64).sin()).round())
4871            .collect();
4872        let measurement = Measurement {
4873            time_edges_us: EDGES_US.map(f64::from).collect(),
4874            charge_ratio: 1.2,
4875            normalization: Value::Fitted(1.0),
4876            time_background: NO_TIME_BACKGROUND,
4877            room_background: None,
4878            spread: None,
4879            environment_scatter: None,
4880            filter: None,
4881            regions: materials
4882                .into_iter()
4883                .enumerate()
4884                .map(|(r, material)| Region {
4885                    open_counts: counts[2 * r * bins..(2 * r + 1) * bins].to_vec(),
4886                    sample_counts: counts[(2 * r + 1) * bins..(2 * r + 2) * bins].to_vec(),
4887                    open_live: Some(live[2 * r * bins..(2 * r + 1) * bins].to_vec()),
4888                    sample_live: Some(live[(2 * r + 1) * bins..(2 * r + 2) * bins].to_vec()),
4889                    background: match material {
4890                        Some(_) => [
4891                            Value::Fitted(0.02),
4892                            Value::Known(0.0),
4893                            Value::Known(0.0),
4894                            Value::Known(0.0),
4895                            Value::Known(0.0),
4896                        ],
4897                        None => [Value::Known(0.0); 5],
4898                    },
4899                    pixels: 1.0,
4900                    gamma_transmission: Value::Known(1.0),
4901                    capture_gammas: Value::Known(0.0),
4902                    in_scatter: Value::Known(0.0),
4903                    timing_offset_us: Value::Known(0.0),
4904                    material: material.map(|data| Material {
4905                        covariances: Vec::new(),
4906                        library: EndfLibrary::EndfB8_0,
4907                        excluded_ranges: Vec::new(),
4908                        isotopes: vec![(data, Value::Fitted(3.0e-4))],
4909                        temperature_k: Value::Fitted(350.0),
4910                        thickness_variance: Value::Known(0.0),
4911                        lattice: None,
4912                    }),
4913                })
4914                .collect(),
4915        };
4916        let calibration = Calibration {
4917            t0_us: Value::Fitted(T0_US),
4918            flight_path_m: Value::Fitted(FLIGHT_PATH_M),
4919            pulse: Pulse {
4920                alpha: [Value::Known(0.35), Value::Known(0.05)],
4921                beta: [Value::Known(0.0), Value::Known(0.25)],
4922                exponents: [Value::Known(0.5); 2],
4923                r: Value::Known(0.15),
4924                fwhm_squared_us2: Value::Known(0.0),
4925                r_high: None,
4926                detector_tail: None,
4927                energy_span_ev: (1.0, 200.0),
4928                n_tau: 256,
4929                line_span_ev: None,
4930                prior: None,
4931            },
4932        };
4933        let open = starting_bypass(&measurement).expect("numbers");
4934        let (fit, answer) = fit_counts_answer(
4935            &measurement,
4936            &calibration,
4937            BeamStarts::OpenFitsAt(open, None, vec![0.0; measurement.regions.len()]),
4938            None,
4939        )
4940        .expect("fit");
4941        assert!(fit.converged);
4942        let covariance = fit.covariance.as_ref().expect("covariance");
4943        let fitted: Vec<Role> = quantities(&measurement, &calibration)
4944            .filter(|(_, value)| !matches!(value, Value::Known(_)))
4945            .map(|(role, _)| role)
4946            .collect();
4947        let at = |role: Role| fitted.iter().position(|&r| r == role).expect("fitted");
4948        let close = |actual: f64, a: Role, b: Role| {
4949            let (i, j) = (at(a), at(b));
4950            let expected = covariance.get(i, j);
4951            let scale = (covariance.get(i, i) * covariance.get(j, j)).sqrt();
4952            assert!(
4953                (actual - expected).abs() <= 1e-8 * scale,
4954                "{a:?} {b:?}: {actual} vs {expected}"
4955            );
4956        };
4957        let shared = [Role::Normalization, Role::T0, Role::FlightPath];
4958        let terms: Vec<RegionTerms> = (0..3)
4959            .map(|r| answer.region_terms(r, &shared).expect("terms"))
4960            .collect();
4961        let k = shared.len();
4962        let joint = Mat::from_fn(k, k, |i, j| {
4963            terms.iter().map(|t| t.information.get(i, j)).sum::<f64>()
4964        })
4965        .llt(Side::Lower)
4966        .expect("positive definite")
4967        .inverse();
4968        for i in 0..k {
4969            for j in 0..k {
4970                close(joint[(i, j)], shared[i], shared[j]);
4971            }
4972        }
4973        let carried = |t: &RegionTerms, a: usize, j: usize| {
4974            (0..k)
4975                .map(|i| t.sensitivity.get(a, i) * joint[(i, j)])
4976                .sum::<f64>()
4977        };
4978        for (p, tp) in terms.iter().enumerate() {
4979            for (a, &ra) in tp.quantities.iter().enumerate() {
4980                for (j, &rs) in shared.iter().enumerate() {
4981                    close(carried(tp, a, j), ra, rs);
4982                }
4983                for (q, tq) in terms.iter().enumerate() {
4984                    for (b, &rb) in tq.quantities.iter().enumerate() {
4985                        let common: f64 = (0..k)
4986                            .map(|j| carried(tp, a, j) * tq.sensitivity.get(b, j))
4987                            .sum();
4988                        let own = if p == q { tp.covariance.get(a, b) } else { 0.0 };
4989                        close(own + common, ra, rb);
4990                    }
4991                }
4992            }
4993        }
4994        let leverage: f64 = (0..k)
4995            .flat_map(|i| (0..k).map(move |j| (i, j)))
4996            .map(|(i, j)| terms[0].counted_information.get(i, j) * joint[(i, j)])
4997            .sum();
4998        let value = |role: Role| {
4999            answer.params[answer
5000                .layout
5001                .roles
5002                .iter()
5003                .position(|&r| r == role)
5004                .expect("a shared role")]
5005        };
5006        let alone = Measurement {
5007            normalization: Value::Known(value(Role::Normalization)),
5008            regions: vec![measurement.regions[0].clone()],
5009            ..measurement.clone()
5010        };
5011        let held = Calibration {
5012            t0_us: Value::Known(value(Role::T0)),
5013            flight_path_m: Value::Known(value(Role::FlightPath)),
5014            ..calibration.clone()
5015        };
5016        let joined = &fit.regions[0];
5017        let starts = Starts {
5018            excluded: vec![joined.excluded_bins.clone()],
5019            beams: vec![BeamStart {
5020                beam: joined.beam.clone(),
5021                overdispersion: joined.overdispersion[0],
5022                at_limit: joined.beam_at_limit,
5023            }],
5024            origin_us: answer.beam_origin_us,
5025            bound: BOUND,
5026            shared_leverage: Some(vec![leverage]),
5027        };
5028        let (region, _) =
5029            fit_counts_answer(&alone, &held, BeamStarts::Given(&starts), None).expect("fit");
5030        let [Some(phi), Some(expected)] =
5031            [&region.regions[0], joined].map(|fit| fit.overdispersion[1])
5032        else {
5033            panic!("a sample overdispersion");
5034        };
5035        assert!((phi / expected - 1.0).abs() <= 1e-4, "{phi} vs {expected}");
5036        let gradient: Vec<f64> = (0..k)
5037            .map(|i| terms.iter().map(|t| t.gradient[i]).sum())
5038            .collect();
5039        let decrement: f64 = (0..k)
5040            .flat_map(|i| (0..k).map(move |j| (i, j)))
5041            .map(|(i, j)| 0.5 * gradient[i] * joint[(i, j)] * gradient[j])
5042            .sum();
5043        assert!(decrement <= 1e-6, "{decrement}");
5044        let mut nudged = answer;
5045        let roles = nudged.layout.roles.clone();
5046        for (i, &role) in roles.iter().enumerate() {
5047            if matches!(
5048                role,
5049                Role::Density { region: 0, .. } | Role::Temperature { region: 0 }
5050            ) {
5051                nudged.params[i] += covariance.get(at(role), at(role)).sqrt();
5052            }
5053        }
5054        let nudged_terms: Vec<RegionTerms> = (0..3)
5055            .map(|r| nudged.region_terms(r, &shared).expect("terms"))
5056            .collect();
5057        let gradient: Vec<f64> = (0..k)
5058            .map(|i| nudged_terms.iter().map(|t| t.gradient[i]).sum())
5059            .collect();
5060        let decrement: f64 = (0..k)
5061            .flat_map(|i| (0..k).map(move |j| (i, j)))
5062            .map(|(i, j)| 0.5 * gradient[i] * joint[(i, j)] * gradient[j])
5063            .sum();
5064        assert!(decrement <= 1e-2, "{decrement}");
5065
5066        let drifting = Measurement {
5067            time_background: [
5068                Value::Fitted(50.0),
5069                Value::Known(0.0),
5070                Value::Known(1.0),
5071                Value::Known(0.0),
5072            ],
5073            room_background: None,
5074            spread: None,
5075            environment_scatter: None,
5076            filter: None,
5077            ..measurement
5078        };
5079        for (most_passes, settled) in [(1, false), (2, true)] {
5080            let fit = fit_settled(&drifting, &calibration, most_passes).expect("fit");
5081            assert_eq!(fit.converged, settled);
5082            assert_eq!(
5083                fit.unconverged.as_deref(),
5084                (!settled).then_some(
5085                    "the open-beam fits' time and room backgrounds did not settle in 1 fits"
5086                )
5087            );
5088            assert_eq!(fit.covariance.is_some(), settled);
5089            assert_eq!(fit.unbounded.is_some(), settled);
5090            assert_eq!(fit.measured_pulls.is_some(), settled);
5091        }
5092    }
5093
5094    #[test]
5095    fn a_map_under_a_pulse_calibration_is_the_joint_fit() {
5096        let grid = Arc::new(grid(None).halved().expect("grid").halved().expect("grid"));
5097        let (_, u_hi) = grid.range_us();
5098        let beam = BeamSpline::constant(347.0, u_hi, 1.0e4).refined();
5099        let beams = [beam.clone(), beam];
5100        let hafnium = synthetic_isotope(72, 180, 20.0, 0.01, 0.06);
5101        let isotopes: Vec<Arc<[ResonanceData]>> = vec![Arc::new([hafnium.clone()]), Arc::new([])];
5102        let sizes: Vec<usize> = beams.iter().map(|b| b.coefficients().len()).collect();
5103        let layout = Arc::new(Layout::new(
5104            roles(&sizes, &[Some(1), None]),
5105            &[1.0; 2],
5106            &[[false; 2]; 2],
5107        ));
5108        let truth: Vec<f64> = layout
5109            .roles
5110            .iter()
5111            .map(|role| match *role {
5112                Role::Beam {
5113                    region,
5114                    coefficient,
5115                } => beams[region].coefficients()[coefficient],
5116                Role::Density { .. } => 5.0e-4,
5117                Role::Temperature { .. } => 300.0,
5118                Role::ThicknessVariance { .. } => 0.0,
5119                Role::Normalization => 0.93,
5120                Role::Background { region, term } => {
5121                    [[0.05, 0.0, 0.0, 0.0, 0.0], [0.0; 5]][region][term]
5122                }
5123                Role::GammaTransmission { .. } => 1.0,
5124                Role::CaptureGammas { .. } => 0.0,
5125                Role::InScatter { .. } => 0.0,
5126                Role::TimingOffset { .. } => 0.0,
5127                Role::SpreadShare => 0.0,
5128                Role::ScatterFraction => 0.0,
5129                Role::Filter => 0.0,
5130                Role::TimeBackground(term) => [0.0, 0.0, 1.0, 0.0][term],
5131                Role::RoomBackground => 0.0,
5132                Role::T0 => T0_US,
5133                Role::FlightPath => FLIGHT_PATH_M,
5134                Role::Pulse(n) => [0.35, 0.05, 0.0, 0.25, 0.15, 0.0, 0.0, 0.0, 1.0, 0.5, 0.5][n],
5135            })
5136            .collect();
5137        let counts: Vec<f64> =
5138            RegionsModel::new(&grid, &beams, &isotopes, (1.2, [0.0; 2]), T0_US, &layout)
5139                .evaluate(&truth)
5140                .expect("counts")
5141                .iter()
5142                .map(|c| c.round())
5143                .collect();
5144        let bins = counts.len() / 4;
5145        let run =
5146            |r: usize, run: usize| counts[(2 * r + run) * bins..(2 * r + run + 1) * bins].to_vec();
5147        let cube = |which: usize| {
5148            ndarray::Array3::from_shape_fn((bins, 2, 1), |(k, y, _)| run(y, which)[k])
5149        };
5150        let (open, sample) = (cube(0), cube(1));
5151        let sample_pixel = ndarray::Array2::from_shape_fn((2, 1), |(y, _)| y == 0);
5152        let empty_pixel = ndarray::Array2::from_shape_fn((2, 1), |(y, _)| y == 1);
5153        let none = ndarray::Array2::from_elem((2, 1), false);
5154        let material = Material {
5155            covariances: Vec::new(),
5156            library: EndfLibrary::EndfB8_0,
5157            excluded_ranges: Vec::new(),
5158            isotopes: vec![(hafnium, Value::Fitted(3.0e-4))],
5159            temperature_k: Value::Fitted(350.0),
5160            thickness_variance: Value::Known(0.0),
5161            lattice: None,
5162        };
5163        let background = [
5164            Value::Fitted(0.02),
5165            Value::Known(0.0),
5166            Value::Known(0.0),
5167            Value::Known(0.0),
5168            Value::Known(0.0),
5169        ];
5170        let map = crate::counts_map::MapMeasurement {
5171            time_edges_us: EDGES_US.map(f64::from).collect(),
5172            charge_ratio: 1.2,
5173            normalization: Value::Fitted(1.0),
5174            time_background: NO_TIME_BACKGROUND,
5175            room_background: None,
5176            open_counts: open.view(),
5177            sample_counts: sample.view(),
5178            open_live: None,
5179            sample_live: None,
5180            excluded: none.view(),
5181            sample: sample_pixel.view(),
5182            empty: empty_pixel.view(),
5183            binning: 1,
5184            material: material.clone(),
5185            background,
5186            gamma_transmission: Value::Known(1.0),
5187            capture_gammas: Value::Known(0.0),
5188            in_scatter: Value::Known(0.0),
5189            empty_background: [Value::Known(0.0); 5],
5190        };
5191        let calibration = Calibration {
5192            t0_us: Value::Measured {
5193                value: T0_US,
5194                sd: 0.01,
5195            },
5196            flight_path_m: Value::Fitted(FLIGHT_PATH_M),
5197            pulse: Pulse {
5198                alpha: [Value::Fitted(0.35), Value::Fitted(0.05)],
5199                beta: [Value::Known(0.0), Value::Known(0.25)],
5200                exponents: [Value::Known(0.5); 2],
5201                r: Value::Known(0.15),
5202                fwhm_squared_us2: Value::Known(0.0),
5203                r_high: None,
5204                detector_tail: None,
5205                energy_span_ev: (1.0, 200.0),
5206                n_tau: 256,
5207                line_span_ev: None,
5208                prior: Some(crate::pulse_calibration::PulsePrior {
5209                    numbers: vec![0, 1],
5210                    mean: vec![0.36, 0.05],
5211                    covariance: FlatMatrix {
5212                        data: vec![1.0e-4, -2.0e-5, -2.0e-5, 1.0e-5],
5213                        nrows: 2,
5214                        ncols: 2,
5215                    },
5216                }),
5217            },
5218        };
5219        let result = crate::counts_map::fit_map(&map, &calibration).expect("map");
5220        assert!(result.converged);
5221        let region = |r: usize, material: Option<Material>, background| Region {
5222            open_counts: run(r, 0),
5223            sample_counts: run(r, 1),
5224            open_live: None,
5225            sample_live: None,
5226            background,
5227            pixels: 1.0,
5228            gamma_transmission: Value::Known(1.0),
5229            capture_gammas: Value::Known(0.0),
5230            in_scatter: Value::Known(0.0),
5231            timing_offset_us: Value::Known(0.0),
5232            material,
5233        };
5234        let measurement = Measurement {
5235            time_edges_us: map.time_edges_us.clone(),
5236            charge_ratio: 1.2,
5237            normalization: map.normalization,
5238            time_background: NO_TIME_BACKGROUND,
5239            room_background: None,
5240            spread: None,
5241            environment_scatter: None,
5242            filter: None,
5243            regions: vec![
5244                region(0, Some(material), background),
5245                region(1, None, [Value::Known(0.0); 5]),
5246            ],
5247        };
5248        let joint = fit_counts(&measurement, &calibration).expect("joint fit");
5249        assert!(joint.converged);
5250        let mut carrying = measurement.clone();
5251        carrying.regions[0]
5252            .material
5253            .as_mut()
5254            .expect("a material")
5255            .covariances = vec![(
5256            0,
5257            ResonanceCovariance {
5258                resonances: vec![[0, 0, 0]],
5259                covariance: [1e-6, 0.0, 0.0, 0.0, 1e-10, 0.0, 0.0, 0.0, 1e-8].into(),
5260            },
5261        )];
5262        assert!(matches!(
5263            fit_counts(&carrying, &calibration),
5264            Err(PipelineError::InvalidParameter(_))
5265        ));
5266        let covariance = joint.covariance.as_ref().expect("covariance");
5267        let fitted: Vec<Role> = quantities(&measurement, &calibration)
5268            .filter(|(_, value)| !matches!(value, Value::Known(_)))
5269            .map(|(role, _)| role)
5270            .collect();
5271        let at = |role: Role| fitted.iter().position(|&r| r == role).expect("fitted");
5272        let close = |actual: f64, a: Role, b: Role| {
5273            let (i, j) = (at(a), at(b));
5274            let scale = (covariance.get(i, i) * covariance.get(j, j)).sqrt();
5275            assert!(
5276                (actual - covariance.get(i, j)).abs() <= 1e-3 * scale,
5277                "{a:?} {b:?}: {actual} vs {}",
5278                covariance.get(i, j)
5279            );
5280        };
5281        let shared = [
5282            Role::Normalization,
5283            Role::T0,
5284            Role::FlightPath,
5285            Role::Pulse(0),
5286            Role::Pulse(1),
5287        ];
5288        let map_shared = result.shared_covariance.as_ref().expect("covariance");
5289        for (s, &a) in shared.iter().enumerate() {
5290            for (t, &b) in shared.iter().enumerate() {
5291                close(map_shared.get(s, t), a, b);
5292            }
5293        }
5294        let own = [
5295            Role::Density {
5296                region: 0,
5297                isotope: 0,
5298            },
5299            Role::Temperature { region: 0 },
5300            Role::Background { region: 0, term: 0 },
5301        ];
5302        let patch = result.covariances.covariance[[0, 0]]
5303            .as_ref()
5304            .expect("covariance");
5305        for (s, &a) in own.iter().enumerate() {
5306            for (t, &b) in own.iter().enumerate() {
5307                close(patch.get(s, t), a, b);
5308            }
5309        }
5310        let gaps = [
5311            (result.alpha[0] - joint.alpha[0])
5312                / covariance
5313                    .get(at(Role::Pulse(0)), at(Role::Pulse(0)))
5314                    .sqrt(),
5315            (result.t0_us - joint.t0_us) / covariance.get(at(Role::T0), at(Role::T0)).sqrt(),
5316            (result.densities[0][[0, 0]] - joint.regions[0].densities[0])
5317                / covariance.get(at(own[0]), at(own[0])).sqrt(),
5318        ];
5319        assert!(gaps.iter().all(|g| g.abs() <= 0.01), "{gaps:?}");
5320        let [Some(map_test), Some(joint_test)] =
5321            [result.pulse_consistency, joint.pulse_consistency]
5322        else {
5323            panic!("a pulse consistency");
5324        };
5325        assert_eq!(map_test.dof, joint_test.dof);
5326        assert!(
5327            (map_test.q - joint_test.q).abs() <= 1e-3 * joint_test.q,
5328            "{map_test:?} vs {joint_test:?}"
5329        );
5330    }
5331
5332    #[test]
5333    fn the_background_lags_sammy_s_by_the_pulse_s_mean_delay() {
5334        let grid = grid(None);
5335        let (_, u_hi) = grid.range_us();
5336        let first_edge_us = f64::from(*EDGES_US.start());
5337        let beam = BeamSpline::constant(first_edge_us - T0_US, u_hi, 1.0e4);
5338        let isotopes: Arc<[ResonanceData]> = Arc::new([
5339            synthetic_isotope(72, 180, 20.0, 0.01, 0.06),
5340            synthetic_isotope(74, 182, 20.3, 0.01, 0.06),
5341        ]);
5342        let (charge_ratio, normalization) = (1.2, 0.93);
5343        let layout = Arc::new(Layout::new(
5344            roles(&[beam.coefficients().len()], &[Some(2)]),
5345            &[1.0],
5346            &[[false; 2]],
5347        ));
5348        let model = RegionsModel::new(
5349            &grid,
5350            std::slice::from_ref(&beam),
5351            &[isotopes],
5352            (charge_ratio, [0.0; 2]),
5353            T0_US,
5354            &layout,
5355        );
5356        let counts = |background: [f64; 5]| {
5357            let params: Vec<f64> = beam
5358                .coefficients()
5359                .iter()
5360                .copied()
5361                .chain([3.0e-4, 5.0e-4, 300.0, 0.0, normalization])
5362                .chain(background)
5363                .chain([1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0])
5364                .chain([T0_US, FLIGHT_PATH_M])
5365                .chain([0.35, 0.05, 0.0, 0.25, 0.15, 0.0, 0.0, 0.0, 1.0, 0.5, 0.5])
5366                .collect();
5367            model.evaluate(&params).expect("counts")
5368        };
5369        let [b0, b1, b2] = [0.05, 0.5, -0.01];
5370        let (with, without) = (counts([b0, b1, b2, 0.0, 0.0]), counts([0.0; 5]));
5371        let bins = with.len() / 2;
5372        let clock = TOF_FACTOR * FLIGHT_PATH_M;
5373        for k in 0..bins {
5374            let u = first_edge_us + 0.5 + k as f64 - T0_US;
5375            let root_e = clock / u;
5376            let b = b0 + b1 / root_e + b2 * root_e;
5377            let slope = b1 / clock - b2 * clock / (u * u);
5378            let curvature = 2.0 * b2 * clock / u.powi(3);
5379            let energy = root_e * root_e;
5380            let (alpha, beta, r) = (ALPHA.eval(energy), BETA.eval(energy), R.eval(energy));
5381            let mean = 3.0 / alpha + r / beta;
5382            let square = mean * mean + 3.0 / (alpha * alpha) + r * (2.0 - r) / (beta * beta);
5383            let lagged = (with[bins + k] - without[bins + k]) / (charge_ratio * normalization);
5384            let residual = lagged / with[k] - b + slope * mean;
5385            let tolerance = 0.5 * slope.abs() + 0.5 * curvature.abs() * square;
5386            assert!(
5387                residual.abs() <= tolerance,
5388                "{k}: {residual} vs {tolerance}"
5389            );
5390        }
5391    }
5392
5393    #[test]
5394    fn a_range_leaves_out_every_bin_its_energies_arrive_in() {
5395        // R rises from 0 to 1 over 13-15 eV, so 14.2 eV can arrive after 13.6 eV.
5396        let pulse = |beta: f64| {
5397            [
5398                0.0, 25.0, 0.0, 0.5, 0.0, beta, 0.0, 0.0, 1.0, 0.0, 1.0, 0.5, 0.5,
5399            ]
5400        };
5401        let material = Material {
5402            covariances: Vec::new(),
5403            isotopes: vec![(
5404                synthetic_isotope(73, 181, 13.9, 0.01, 0.06),
5405                Value::Known(1e-4),
5406            )],
5407            temperature_k: Value::Known(300.0),
5408            library: EndfLibrary::EndfB8_1,
5409            excluded_ranges: vec![ExcludedRange {
5410                energy_ev: (13.6, 14.2),
5411                reason: "misplaced".into(),
5412            }],
5413            thickness_variance: Value::Known(0.0),
5414            lattice: None,
5415        };
5416        let bins = |edges: &[f64], beta: f64| {
5417            excluded_bins(edges, Some(&material), &pulse(beta), Some((13.0, 15.0)))
5418        };
5419        // Here the energies arrive between 526.877 and 546.501 µs.
5420        let edges: Vec<f64> = (500..=560).map(f64::from).collect();
5421        assert_eq!(bins(&edges, 0.01), (26..=46).collect::<Vec<usize>>());
5422        // With this β the arrival time has its minimum, 506.785921 µs, inside the range.
5423        assert_eq!(bins(&[506.784921, 506.786155], 0.0287), [0]);
5424    }
5425}
5426
5427/// Check 2: the counts the model predicts at fixed numbers against an independent fold of
5428/// SAMMY's transmission (`tests/data/sammy-ta181/counts_reference.py`).
5429#[cfg(test)]
5430mod counts_check {
5431    use std::collections::HashMap;
5432
5433    use nereids_core::constants::tof_to_energy;
5434    use nereids_endf::parser::parse_endf_file2;
5435    use nereids_physics::ikeda_carpenter::{DEFAULT_N_TAU, DetectorPulse};
5436
5437    use super::*;
5438
5439    /// `value` is above `bound`, or either is NaN.
5440    fn exceeds(value: f64, bound: f64) -> bool {
5441        !matches!(
5442            value.partial_cmp(&bound),
5443            Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal)
5444        )
5445    }
5446
5447    /// The reference files, relative to this crate.
5448    const DATA: &str = "../../tests/data/sammy-ta181";
5449    /// `[α0, α1, β0, β1, R, h², R_high, f, τ_D, p_α, p_β]`, as the reference.
5450    const NUMBERS: [f64; 11] = [0.5, 1.0, 0.01, 0.04, 0.3, 0.1225, 0.1, 0.1, 2.0, 0.5, 0.5];
5451    /// Energies in eV over which the pulse laws hold.
5452    const SPAN_EV: (f64, f64) = (0.3, 1000.0);
5453    const FLIGHT_PATH: f64 = 25.0;
5454    const DENSITY: f64 = 7.04e-4;
5455    /// Bin-centre energies in eV of the scored bins.
5456    const SCORED_BINS_EV: (f64, f64) = (0.5, 197.517_35);
5457    /// The scored resonances.
5458    const SCORED_EV: (f64, f64) = (0.5, 200.0);
5459    const LINE_4_28_EV: f64 = 4.280_412;
5460    /// Columns of the reference sample counts: T, then T − 1, T − ½, T, T + ½, T + 1 K.
5461    const TEMPERATURES: [(f64, [usize; 5], f64); 2] = [
5462        (300.0, [2, 3, 4, 5, 6], 0.05),
5463        (1100.0, [7, 8, 9, 10, 11], 0.2),
5464    ];
5465
5466    fn read(name: &str) -> String {
5467        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5468            .join(DATA)
5469            .join(name);
5470        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
5471    }
5472
5473    /// The rows of `name` that are not blank or comments.
5474    fn table(name: &str) -> Vec<Vec<f64>> {
5475        read(name)
5476            .lines()
5477            .map(str::trim)
5478            .filter(|l| !l.is_empty() && !l.starts_with('#'))
5479            .map(|l| {
5480                l.split_whitespace()
5481                    .map(|x| x.parse().unwrap_or_else(|e| panic!("{name}: {x}: {e}")))
5482                    .collect()
5483            })
5484            .collect()
5485    }
5486
5487    /// `p1b_counts_eps.txt`: the reference's error bound per measured run.
5488    fn eps() -> HashMap<String, f64> {
5489        read("p1b_counts_eps.txt")
5490            .lines()
5491            .filter(|l| !l.trim().is_empty() && !l.starts_with('#'))
5492            .map(|l| {
5493                let mut it = l.split_whitespace();
5494                let key = it.next().expect("key").to_owned();
5495                (key, it.next().expect("value").parse().expect("number"))
5496            })
5497            .collect()
5498    }
5499
5500    /// The scored bins' edges in µs and centre energies in eV, in time order.
5501    fn scored_bins() -> (Vec<f64>, Vec<f64>) {
5502        let edge = |j: usize| (112 + 16 * j) as f64 / 100.0;
5503        let centre = |j: usize| tof_to_energy(0.5 * (edge(j) + edge(j + 1)), FLIGHT_PATH);
5504        let kept: Vec<usize> = (0..)
5505            .take_while(|&j| centre(j) >= SCORED_BINS_EV.0)
5506            .filter(|&j| centre(j) <= SCORED_BINS_EV.1)
5507            .collect();
5508        (
5509            (kept[0]..=kept[kept.len() - 1] + 1).map(edge).collect(),
5510            kept.into_iter().map(centre).collect(),
5511        )
5512    }
5513
5514    /// Each scored resonance's bins: centre energy in (low, high], the lowest window
5515    /// closed below, edges at the midpoints to the neighbours in the whole File 2 list.
5516    fn windows(data: &ResonanceData, centres: &[f64]) -> Vec<(f64, Vec<usize>)> {
5517        let mut energies: Vec<f64> = data
5518            .ranges
5519            .iter()
5520            .flat_map(|r| &r.l_groups)
5521            .flat_map(|g| &g.resonances)
5522            .map(|r| r.energy)
5523            .collect();
5524        energies.sort_by(f64::total_cmp);
5525        energies.dedup();
5526        (0..energies.len())
5527            .filter(|&i| (SCORED_EV.0..=SCORED_EV.1).contains(&energies[i]))
5528            .map(|i| {
5529                let low = if i == 0 {
5530                    SCORED_EV.0
5531                } else {
5532                    (0.5 * (energies[i - 1] + energies[i])).max(SCORED_EV.0)
5533                };
5534                let high = energies
5535                    .get(i + 1)
5536                    .map_or(SCORED_EV.1, |n| (0.5 * (energies[i] + n)).min(SCORED_EV.1));
5537                let members = (0..centres.len())
5538                    .filter(|&k| {
5539                        let e = centres[k];
5540                        e <= high && (e > low || (low == SCORED_EV.0 && e == low))
5541                    })
5542                    .collect();
5543                (energies[i], members)
5544            })
5545            .filter(|(_, k): &(f64, Vec<usize>)| !k.is_empty())
5546            .collect()
5547    }
5548
5549    /// The model on `grid`, its layout and the numbers, with one region per temperature
5550    /// of [`TEMPERATURES`].
5551    ///
5552    /// The regions share one clock, so a Jacobian computes the grid's pulse slopes once.
5553    fn model_at(
5554        grid: &Arc<FlightTimeGrid>,
5555        ta: &ResonanceData,
5556    ) -> (RegionsModel, Arc<Layout>, Vec<f64>) {
5557        let (low, high) = grid.range_us();
5558        let spline = BeamSpline::constant(low, high, 1.0);
5559        let n = spline.intervals();
5560        let h = (high.ln() - low.ln()) / n as f64;
5561        // ln φ = ln 1e4 − 0.8 (x − ln 100), x = ln u: linear, so a cubic B-spline holds it
5562        // exactly with coefficient i at x_low + (i − 1)h.
5563        let coefficients: Vec<f64> = (0..n + 3)
5564            .map(|i| 1e4_f64.ln() - 0.8 * (low.ln() + (i as f64 - 1.0) * h - 100_f64.ln()))
5565            .collect();
5566        let beam = spline.with_coefficients(&coefficients);
5567        let mut layout = Layout::new(
5568            roles(&[coefficients.len(); 2], &[Some(1), Some(1)]),
5569            &[1.0, 1.0],
5570            &[[false, false]; 2],
5571        );
5572        layout.storage_span = Some(SPAN_EV);
5573        let layout = Arc::new(layout);
5574        let params = layout
5575            .roles
5576            .iter()
5577            .map(|role| match *role {
5578                Role::Beam { coefficient, .. } => coefficients[coefficient],
5579                Role::Density { .. } => DENSITY,
5580                Role::Temperature { region } => TEMPERATURES[region].0,
5581                Role::Normalization | Role::GammaTransmission { .. } => 1.0,
5582                // The time background's decay constant; its amplitudes stay 0.
5583                Role::TimeBackground(2) => 1.0,
5584                Role::FlightPath => FLIGHT_PATH,
5585                Role::Pulse(k) => NUMBERS[k],
5586                _ => 0.0,
5587            })
5588            .collect();
5589        let isotopes: [Arc<[ResonanceData]>; 2] = [Arc::new([ta.clone()]), Arc::new([ta.clone()])];
5590        let model = RegionsModel::new(
5591            grid,
5592            &[beam.clone(), beam],
5593            &isotopes,
5594            (1.0, [1.0, 1.0]),
5595            0.0,
5596            &layout,
5597        );
5598        (model, layout, params)
5599    }
5600
5601    #[test]
5602    #[ignore = "slow; runs nightly"]
5603    fn check2_counts_match_the_independent_fold() {
5604        let ta = parse_endf_file2(&read("Ta-181-mf2.endf")).expect("Ta-181-mf2.endf");
5605        let (edges, centres) = scored_bins();
5606        let bins = centres.len();
5607        let reference = table("p1b_counts.txt");
5608        let jacobian_ref = table("p1b_jacobian.txt");
5609        assert_eq!(reference.len(), bins, "one reference row per bin");
5610        assert_eq!(jacobian_ref.len(), bins, "one derivative row per bin");
5611        for (row, e) in jacobian_ref.iter().zip(&centres) {
5612            assert!(
5613                row.len() == 40 && row.iter().all(|x| x.is_finite()),
5614                "a derivative row at {e} eV is not 40 finite values"
5615            );
5616            assert!(
5617                (row[0] / e - 1.0).abs() <= 1e-11,
5618                "derivative row {} is not the centre {e}",
5619                row[0]
5620            );
5621        }
5622        for (row, e) in reference.iter().zip(&centres) {
5623            assert!(
5624                row.len() == 12 && row.iter().all(|x| x.is_finite()),
5625                "a count row at {e} eV is not 12 finite values"
5626            );
5627            assert!(
5628                (row[0] / e - 1.0).abs() <= 1e-11,
5629                "{} is not the centre {e}",
5630                row[0]
5631            );
5632        }
5633        let eps = eps();
5634        let windows = windows(&ta, &centres);
5635        assert_eq!(windows.iter().map(|(_, k)| k.len()).sum::<usize>(), bins);
5636        assert!(
5637            windows
5638                .iter()
5639                .any(|(resonance, k)| *resonance == LINE_4_28_EV && !k.is_empty()),
5640            "check 2 scores the {LINE_4_28_EV} eV window"
5641        );
5642        let mut failures = Vec::new();
5643        let mut unjudged = Vec::new();
5644        // Failures where the reference's grid error is not measured: not attributed to NEREIDS.
5645        let mut undecided = Vec::new();
5646
5647        // Decided from the reference alone, before NEREIDS runs.
5648        let around = |kelvin: f64| -> Option<[f64; 5]> {
5649            let found =
5650                [-1.0, -0.5, 0.0, 0.5, 1.0].map(|d| eps.get(&format!("{}", kelvin + d)).copied());
5651            match found {
5652                [Some(a), Some(b), Some(c), Some(d), Some(e)] => Some([a, b, c, d, e]),
5653                _ => None,
5654            }
5655        };
5656        let mut judged = Vec::new();
5657        for &(kelvin, cols, limit) in &TEMPERATURES {
5658            let e5 = around(kelvin).unwrap_or([0.0; 5]);
5659            let mut per_window = Vec::new();
5660            for (resonance, k) in &windows {
5661                let d: Vec<f64> = k
5662                    .iter()
5663                    .map(|&i| 0.5 * (reference[i][cols[4]] - reference[i][cols[0]]))
5664                    .collect();
5665                // For a cubic in T the ±1 K difference's step error is 4/3 of its change from ±½ K.
5666                // The reference's error enters both differences.
5667                let reference_error = 0.5 * (e5[0] + e5[4]) + e5[1] + e5[3];
5668                let step = 4.0 / 3.0
5669                    * (k.iter()
5670                        .zip(&d)
5671                        .map(|(&i, d)| (d - (reference[i][cols[3]] - reference[i][cols[1]])).abs())
5672                        .fold(0.0_f64, f64::max)
5673                        + reference_error);
5674                let max_d = d.iter().fold(0.0_f64, |m, x| m.max(x.abs()));
5675                let rms = (d.iter().map(|x| x * x).sum::<f64>() / d.len() as f64).sqrt();
5676                let marks = [
5677                    rms > 0.0 && e5[2] / rms <= 0.1 * limit,
5678                    max_d > 0.0 && e5[2] <= 0.01 * max_d,
5679                    max_d > 0.0 && 0.5 * (e5[0] + e5[4]) + step <= 0.001 * max_d,
5680                ];
5681                if marks.contains(&false) {
5682                    let note = format!("check 2, {resonance} eV at {kelvin} K: marks {marks:?}");
5683                    if *resonance == LINE_4_28_EV {
5684                        failures.push(format!("{note}: the 4.280412 eV window must be judged"));
5685                    } else {
5686                        unjudged.push(note);
5687                    }
5688                }
5689                per_window.push(marks);
5690            }
5691            judged.push(per_window);
5692        }
5693
5694        let span = SPAN_EV;
5695        let pulse =
5696            DetectorPulse::new(laws(&NUMBERS, Some(span)), span, DEFAULT_N_TAU).expect("pulse");
5697        let mut grid =
5698            Arc::new(FlightTimeGrid::new(&edges, 0.0, FLIGHT_PATH, &pulse).expect("grid"));
5699        let peak = reference.iter().fold(0.0_f64, |m, r| m.max(r[1]));
5700        if exceeds(eps["open"], 1e-7 * peak) {
5701            failures.push(format!(
5702                "check 2: the reference's open error {:.3e}",
5703                eps["open"]
5704            ));
5705        }
5706        // Halve NEREIDS's grid until no count moves by 1e-7 of the open peak.
5707        // Open then sample counts, per temperature.
5708        let evaluate = |grid: &Arc<FlightTimeGrid>| -> Vec<Vec<f64>> {
5709            let (model, _, params) = model_at(grid, &ta);
5710            let y = model.evaluate(&params).expect("counts");
5711            y.chunks(2 * bins).map(<[f64]>::to_vec).collect()
5712        };
5713        let mut counts = evaluate(&grid);
5714        let mut open_eps = f64::NAN;
5715        let mut previous = Arc::clone(&grid);
5716        // At the point cap NEREIDS's own error is held to the full mark instead of a tenth.
5717        let mut share = 0.1;
5718        for halving in 1..=6 {
5719            let finer = match grid.halved() {
5720                Ok(finer) => Arc::new(finer),
5721                Err(
5722                    e @ nereids_physics::flight_time_grid::FlightTimeGridError::TooManyPoints {
5723                        ..
5724                    },
5725                ) => {
5726                    eprintln!(
5727                        "check 2: halving {halving} stopped: {e}; NEREIDS's error held to the full mark"
5728                    );
5729                    if halving == 1 {
5730                        failures.push(format!("check 2: NEREIDS's grid cannot be halved: {e}"));
5731                    }
5732                    share = 1.0;
5733                    break;
5734                }
5735                Err(e) => panic!("halved: {e}"),
5736            };
5737            let refined = evaluate(&finer);
5738            let nereids_eps = counts
5739                .iter()
5740                .flatten()
5741                .zip(refined.iter().flatten())
5742                .map(|(a, b)| (a - b).abs())
5743                .fold(0.0_f64, f64::max);
5744            open_eps = counts
5745                .iter()
5746                .zip(&refined)
5747                .flat_map(|(a, b)| a[..bins].iter().zip(&b[..bins]))
5748                .map(|(a, b)| (a - b).abs())
5749                .fold(0.0_f64, f64::max);
5750            eprintln!(
5751                "check 2: halving {halving}, largest change {nereids_eps:.3e}, open {open_eps:.3e} \
5752                 (peak {peak:.4e})"
5753            );
5754            previous = std::mem::replace(&mut grid, finer);
5755            counts = refined;
5756            if nereids_eps <= 1e-7 * peak {
5757                break;
5758            }
5759        }
5760        // The open counts' mark; the sample counts' own marks are judged per window below.
5761        if exceeds(open_eps, share * 1e-6 * peak) {
5762            failures.push(format!(
5763                "check 2: NEREIDS's grid moves the open counts by {open_eps:.3e}"
5764            ));
5765        }
5766
5767        // Open counts, the same reference at every temperature.
5768        let open_diff = counts
5769            .iter()
5770            .flat_map(|run| run[..bins].iter().enumerate())
5771            .map(|(j, &o)| (o - reference[j][1]).abs())
5772            .fold(0.0_f64, |m, x| {
5773                if x.is_nan() || m.is_nan() {
5774                    f64::NAN
5775                } else {
5776                    m.max(x)
5777                }
5778            });
5779        eprintln!(
5780            "check 2: open max|O_N − O_ref| = {open_diff:.3e}, limit {:.3e}",
5781            1e-6 * peak
5782        );
5783        if exceeds(open_diff, 1e-6 * peak) {
5784            failures.push(format!("check 2: open counts differ by {open_diff:.3e}"));
5785        }
5786
5787        // The counts and derivatives on the accepted grid and on the grid before it.
5788        // Columns: the 11 pulse numbers, t0, L, then each region's temperature.
5789        let solve = |grid: &Arc<FlightTimeGrid>| {
5790            let (model, layout, params) = model_at(grid, &ta);
5791            let mut free: Vec<usize> = (0..11).map(|n| layout.pulse + n).collect();
5792            free.extend([layout.t0, layout.flight_path]);
5793            free.extend(
5794                layout
5795                    .regions
5796                    .iter()
5797                    .map(|r| r.temperature.expect("a material")),
5798            );
5799            let y = model.evaluate(&params).expect("counts");
5800            let jac = model
5801                .analytical_jacobian(&params, &free, &y)
5802                .expect("jacobian");
5803            (y, jac)
5804        };
5805        let (y_all, jac) = solve(&grid);
5806        let (y_coarse_all, jac_coarse) = solve(&previous);
5807        assert_eq!(y_all.len(), 2 * TEMPERATURES.len() * bins);
5808        for (t, &(kelvin, cols, limit)) in TEMPERATURES.iter().enumerate() {
5809            // This temperature's region: open rows from `base`, sample rows after them.
5810            let base = 2 * t * bins;
5811            let y = &y_all[base..base + 2 * bins];
5812            let y_coarse = &y_coarse_all[base..base + 2 * bins];
5813            let at = |jac: &FlatMatrix, row: usize, column: usize| jac.get(base + row, column);
5814            let sample: Vec<f64> = y[bins..2 * bins].to_vec();
5815            let slope: Vec<f64> = (0..bins).map(|j| at(&jac, bins + j, 13 + t)).collect();
5816            let sample_change: Vec<f64> = (0..bins)
5817                .map(|j| (y[bins + j] - y_coarse[bins + j]).abs())
5818                .collect();
5819            let slope_change: Vec<f64> = (0..bins)
5820                .map(|j| (at(&jac, bins + j, 13 + t) - at(&jac_coarse, bins + j, 13 + t)).abs())
5821                .collect();
5822            let coarse_slope = (0..bins).map(|j| at(&jac_coarse, bins + j, 13 + t));
5823            if y.iter()
5824                .chain(&slope)
5825                .chain(y_coarse)
5826                .copied()
5827                .chain(coarse_slope)
5828                .any(|x| !x.is_finite())
5829            {
5830                failures.push(format!(
5831                    "check 2 at {kelvin} K: a count or slope is not finite"
5832                ));
5833            }
5834            let measured = around(kelvin).is_some();
5835            let e_t = around(kelvin).map_or(0.0, |e| e[2]);
5836            let verdict =
5837                |note: String, failures: &mut Vec<String>, undecided: &mut Vec<String>| {
5838                    if measured {
5839                        failures.push(note);
5840                    } else {
5841                        undecided.push(format!(
5842                            "{note} (the reference's grid error here is not measured; measure it \
5843                         before attributing this to NEREIDS)"
5844                        ));
5845                    }
5846                };
5847            for ((resonance, k), marks) in windows.iter().zip(&judged[t]) {
5848                let d: Vec<f64> = k
5849                    .iter()
5850                    .map(|&i| 0.5 * (reference[i][cols[4]] - reference[i][cols[0]]))
5851                    .collect();
5852                let r: Vec<f64> = k
5853                    .iter()
5854                    .map(|&i| sample[i] - reference[i][cols[2]])
5855                    .collect();
5856                let max_d = d.iter().fold(0.0_f64, |m, x| m.max(x.abs()));
5857                let bias = r.iter().zip(&d).map(|(a, b)| a * b).sum::<f64>()
5858                    / d.iter().map(|x| x * x).sum::<f64>();
5859                let max_r = r.iter().fold(0.0_f64, |m, x| m.max(x.abs()));
5860                let max_slope = k
5861                    .iter()
5862                    .zip(&d)
5863                    .map(|(&i, d)| (slope[i] - d).abs())
5864                    .fold(0.0_f64, f64::max);
5865                let label = format!("check 2, {resonance} eV at {kelvin} K");
5866                // NEREIDS's own error: at most `share` of each mark.
5867                let change: Vec<f64> = k.iter().map(|&i| sample_change[i]).collect();
5868                let max_change = change.iter().fold(0.0_f64, |m, x| m.max(*x));
5869                let max_slope_change = k.iter().fold(0.0_f64, |m, &i| m.max(slope_change[i]));
5870                let change_bias = change.iter().zip(&d).map(|(a, b)| a * b.abs()).sum::<f64>()
5871                    / d.iter().map(|x| x * x).sum::<f64>();
5872                if marks[0] && exceeds(change_bias, share * limit) {
5873                    failures.push(format!(
5874                        "{label}: NEREIDS's grid moves b by {change_bias:.3e} K"
5875                    ));
5876                }
5877                if marks[1] && exceeds(max_change, share * 0.1 * max_d) {
5878                    failures.push(format!(
5879                        "{label}: NEREIDS's grid moves S by {max_change:.3e}"
5880                    ));
5881                }
5882                if marks[2] && exceeds(max_slope_change, share * 0.01 * max_d) {
5883                    failures.push(format!(
5884                        "{label}: NEREIDS's grid moves dS/dT by {max_slope_change:.3e}"
5885                    ));
5886                }
5887                eprintln!(
5888                    "{label}: b = {bias:+.4} K, max|r| = {max_r:.3e} (bound {:.3e}), \
5889                     max|D_N − D| = {max_slope:.3e} (bound {:.3e}), judged {marks:?}",
5890                    0.1 * max_d + e_t,
5891                    0.01 * max_d
5892                );
5893                if marks[0] && exceeds(bias.abs(), limit) {
5894                    verdict(
5895                        format!("{label}: (i) |b| = {:.4} K", bias.abs()),
5896                        &mut failures,
5897                        &mut undecided,
5898                    );
5899                }
5900                if marks[1] && exceeds(max_r, 0.1 * max_d + e_t) {
5901                    verdict(
5902                        format!("{label}: (ii) max|r| = {max_r:.3e}"),
5903                        &mut failures,
5904                        &mut undecided,
5905                    );
5906                }
5907                if marks[2] && exceeds(max_slope, 0.01 * max_d) {
5908                    verdict(
5909                        format!("{label}: (iii) max|D_N − D| = {max_slope:.3e}"),
5910                        &mut failures,
5911                        &mut undecided,
5912                    );
5913                }
5914            }
5915            // Derivatives with respect to the 11 pulse numbers, t0 and L.
5916            for column in 0..13 {
5917                for (run, offset, ref_col) in [
5918                    ("open", 0, 1 + column),
5919                    ("sample", bins, 14 + 13 * t + column),
5920                ] {
5921                    // Both runs enter one fit, so a number's derivatives share the larger scale.
5922                    let largest = [1 + column, 14 + 13 * t + column]
5923                        .into_iter()
5924                        .flat_map(|c| jacobian_ref.iter().map(move |row| row[c].abs()))
5925                        .fold(0.0_f64, f64::max);
5926                    let worst = (0..bins)
5927                        .map(|j| (at(&jac, offset + j, column) - jacobian_ref[j][ref_col]).abs())
5928                        .fold(0.0_f64, |m, x| {
5929                            if x.is_nan() || m.is_nan() {
5930                                f64::NAN
5931                            } else {
5932                                m.max(x)
5933                            }
5934                        });
5935                    let moved = (0..bins)
5936                        .map(|j| {
5937                            (at(&jac, offset + j, column) - at(&jac_coarse, offset + j, column))
5938                                .abs()
5939                        })
5940                        .fold(0.0_f64, |m, x| {
5941                            if x.is_nan() || m.is_nan() {
5942                                f64::NAN
5943                            } else {
5944                                m.max(x)
5945                            }
5946                        });
5947                    if exceeds(moved, share * 1e-2 * largest) {
5948                        failures.push(format!(
5949                            "check 2, ∂{run}/∂p{column} at {kelvin} K: NEREIDS's grid moves it by {moved:.3e}"
5950                        ));
5951                    }
5952                    eprintln!(
5953                        "check 2, ∂{run}/∂p{column} at {kelvin} K: max diff {worst:.3e} of {largest:.3e}"
5954                    );
5955                    if exceeds(worst, 0.01 * largest) {
5956                        let note = format!(
5957                            "check 2, ∂{run}/∂p{column} at {kelvin} K: {worst:.3e} exceeds 1% of {largest:.3e}"
5958                        );
5959                        // The reference checks only the open derivatives on its halved grid.
5960                        if run == "open" {
5961                            failures.push(note);
5962                        } else {
5963                            undecided.push(format!(
5964                                "{note} (the reference's grid error is not measured for sample \
5965                                 derivatives; measure it before attributing this to NEREIDS)"
5966                            ));
5967                        }
5968                    }
5969                }
5970            }
5971        }
5972        eprintln!(
5973            "{} marks not judged:\n{}",
5974            unjudged.len(),
5975            unjudged.join("\n")
5976        );
5977        eprintln!("{} undecided:\n{}", undecided.len(), undecided.join("\n"));
5978        assert!(failures.is_empty(), "{}", failures.join("\n"));
5979        assert!(undecided.is_empty(), "{}", undecided.join("\n"));
5980    }
5981}