Skip to main content

nereids_pipeline/
counts_map.rs

1//! Maps of a material's areal densities and temperature over the detector,
2//! fitted as one counts fit whose regions are patches of pixels.
3
4use std::sync::RwLock;
5
6use faer::linalg::solvers::DenseSolveCore;
7use faer::{Mat, Side};
8use ndarray::{Array2, ArrayView2, ArrayView3, s};
9use nereids_fitting::error::FittingError;
10use nereids_fitting::lm::FlatMatrix;
11use nereids_fitting::poisson::{
12    InformationInverse, NEWTON_DECREMENT_TOL, Prior, half_deviance, information_inverse,
13};
14use nereids_fitting::statistics::{Consistency, consistency};
15use rayon::prelude::*;
16
17use crate::counts_fit::TEMPERATURE_BOUNDS_K;
18use crate::counts_fit::{
19    BACKGROUND_TERMS, BeamStart, BeamStarts, Bypass, MOST_PASSES, Material, Measurement, Region,
20    RegionFit, RegionTerms, Role, RoomBackground, SHARED, Starts, Value, checked, excluded_bins,
21    fit_counts_answer, labelled, open_frames, shared_parameters, starting_bypass,
22    starts_and_widths_us,
23};
24use crate::error::PipelineError;
25use crate::open_beam::{BOUND, Calibration, PULSE_NUMBERS, Pulse, open_beam_with_intervals, whole};
26
27const MOST_STEPS: usize = 20;
28
29const MOST_HALVINGS: i32 = 10;
30
31/// The counts of every pixel of an open-beam run and a sample run recorded in
32/// the same time bins, which pixels to fit, and the material behind the
33/// sample.
34#[derive(Debug, Clone)]
35pub struct MapMeasurement<'a> {
36    /// Time-bin edges in µs.
37    pub time_edges_us: Vec<f64>,
38    /// `c_q`, the sample run's proton charge over the open-beam run's.
39    pub charge_ratio: f64,
40    /// `a`, the normalization of the sample run, the same in every pixel.
41    pub normalization: Value,
42    /// `[C, A, τ, D]` of the time background per pixel, as
43    /// [`Measurement::time_background`], the same in every pixel;
44    /// [`NO_TIME_BACKGROUND`](crate::counts_fit::NO_TIME_BACKGROUND) gives
45    /// none.
46    pub time_background: [Value; 4],
47    /// Counts that follow each run's duration, as
48    /// [`Measurement::room_background`], the same in every pixel.
49    pub room_background: Option<RoomBackground>,
50    /// Raw counts of the open-beam run, in (time bin, row, column).
51    pub open_counts: ArrayView3<'a, f64>,
52    /// Raw counts of the sample run, in (time bin, row, column).
53    pub sample_counts: ArrayView3<'a, f64>,
54    /// The fraction of the open-beam run's neutrons arriving in each bin that
55    /// each pixel records, in (time bin, row, column), in (0, 1]; `None`
56    /// records every one.
57    pub open_live: Option<ArrayView3<'a, f64>>,
58    /// The fraction of the sample run's neutrons arriving in each bin that
59    /// each pixel records, in (time bin, row, column), in (0, 1]; `None`
60    /// records every one.
61    pub sample_live: Option<ArrayView3<'a, f64>>,
62    /// Pixels left out of both runs, in (row, column).
63    pub excluded: ArrayView2<'a, bool>,
64    /// Pixels behind the sample, in (row, column).
65    pub sample: ArrayView2<'a, bool>,
66    /// Pixels the beam reaches through nothing and the sample scatters no
67    /// neutrons into, in (row, column).
68    pub empty: ArrayView2<'a, bool>,
69    /// The side of a square patch, in pixels.
70    pub binning: usize,
71    /// The material behind the sample: its isotopes' densities and its
72    /// temperature, known, fitted or within bounds, in every patch.
73    pub material: Material,
74    /// `[b0, b1, b2, d, f]` of the background of every patch behind the
75    /// sample, as [`Region::background`], known, fitted or within bounds.
76    pub background: [Value; 5],
77    /// The fraction of the time background that reaches the pixels behind the
78    /// sample in the sample run, as [`Region::gamma_transmission`], known,
79    /// fitted or within bounds in every patch; the empty pixels take 1.
80    pub gamma_transmission: Value,
81    /// The capture gammas' `ε` of every patch behind the sample, as
82    /// [`Region::capture_gammas`], known, fitted or within bounds; the empty
83    /// pixels hold no sample and record none.
84    pub capture_gammas: Value,
85    /// The in-scatter's `Ω` of every patch behind the sample, as
86    /// [`Region::in_scatter`], known, fitted or within bounds; the empty
87    /// pixels hold no sample and record none.
88    pub in_scatter: Value,
89    /// `[b0, b1, b2, d, f]` of the background of the empty pixels.
90    pub empty_background: [Value; 5],
91}
92
93impl MapMeasurement<'_> {
94    /// Each patch's kind, in (patch row, patch column); patch `(i, j)` holds
95    /// the pixels from `(i·binning, j·binning)` up to the next patch or the
96    /// image's edge.
97    ///
98    /// # Errors
99    /// [`PipelineError::ShapeMismatch`] unless both runs' counts have one time
100    /// bin per pair of edges and the same rows and columns as the three
101    /// masks, and each live fraction array has their shape;
102    /// [`PipelineError::InvalidParameter`] if `binning` is 0.
103    pub fn patches(&self) -> Result<Array2<Patch>, PipelineError> {
104        let bins = self.time_edges_us.len().saturating_sub(1);
105        let (time_bins, height, width) = self.open_counts.dim();
106        if self.sample_counts.dim() != self.open_counts.dim() || time_bins != bins {
107            return Err(PipelineError::ShapeMismatch(format!(
108                "open-beam counts of shape {:?} and sample counts of shape {:?} for {bins} \
109                 time bins",
110                self.open_counts.dim(),
111                self.sample_counts.dim()
112            )));
113        }
114        for (run, live) in [("open-beam", self.open_live), ("sample", self.sample_live)] {
115            if let Some(live) = live.filter(|live| live.dim() != self.open_counts.dim()) {
116                return Err(PipelineError::ShapeMismatch(format!(
117                    "{run} live fractions of shape {:?} for counts of shape {:?}",
118                    live.dim(),
119                    self.open_counts.dim()
120                )));
121            }
122        }
123        for (name, mask) in [
124            ("excluded", self.excluded),
125            ("sample", self.sample),
126            ("empty", self.empty),
127        ] {
128            if mask.dim() != (height, width) {
129                return Err(PipelineError::ShapeMismatch(format!(
130                    "the {name} mask has shape {:?} for {height}×{width} pixels",
131                    mask.dim()
132                )));
133            }
134        }
135        let b = self.binning;
136        if b == 0 {
137            return Err(PipelineError::InvalidParameter(
138                "a patch is at least one pixel wide".into(),
139            ));
140        }
141        Ok(Array2::from_shape_fn(
142            (height.div_ceil(b), width.div_ceil(b)),
143            |patch| {
144                let pixels = self.pixels(patch);
145                let behind = pixels.iter().filter(|&&pixel| self.sample[pixel]).count();
146                match (behind, pixels.len() - behind) {
147                    (0, _) => Patch::Outside,
148                    (_, 0) => Patch::Sample,
149                    _ => Patch::Mixed,
150                }
151            },
152        ))
153    }
154
155    fn pixels(&self, (i, j): (usize, usize)) -> Vec<(usize, usize)> {
156        let (height, width) = self.excluded.dim();
157        let b = self.binning;
158        (i * b..height.min((i + 1) * b))
159            .flat_map(|y| (j * b..width.min((j + 1) * b)).map(move |x| (y, x)))
160            .filter(|&pixel| !self.excluded[pixel])
161            .collect()
162    }
163
164    /// Each run's live fractions of a set of pixels, by [`region_live`].
165    fn region_lives(
166        &self,
167        pixels: &[(usize, usize)],
168    ) -> Result<[Option<Vec<f64>>; 2], PipelineError> {
169        let cells: Vec<[usize; 2]> = pixels.iter().map(|&(y, x)| [y, x]).collect();
170        let one = |counts, live: Option<ArrayView3<'_, f64>>| {
171            live.map(|live| region_live(counts, live, &cells))
172                .transpose()
173        };
174        Ok([
175            one(self.open_counts, self.open_live)?,
176            one(self.sample_counts, self.sample_live)?,
177        ])
178    }
179}
180
181/// A region's live fraction in each bin, its counts over their arrivals: `Σ C / Σ (C / L)`.
182///
183/// A bin with no counts in the region takes the mean `L` of its pixels.
184///
185/// # Arguments
186/// * `counts` — Raw counts in (time bin, row, column), finite and 0 or more.
187/// * `live` — Live fractions of `counts` in (0, 1], the same shape.
188/// * `cells` — The region's pixels as `[row, column]`, at least one, each once.
189///
190/// # Errors
191/// [`PipelineError::ShapeMismatch`] if the shapes differ or a cell is outside
192/// them; [`PipelineError::InvalidParameter`] if `cells` or the bins are empty,
193/// a cell repeats, a region count is not finite and 0 or more or its live
194/// fraction not in (0, 1], or the counts overflow the sums.
195pub fn region_live(
196    counts: ArrayView3<'_, f64>,
197    live: ArrayView3<'_, f64>,
198    cells: &[[usize; 2]],
199) -> Result<Vec<f64>, PipelineError> {
200    if counts.shape() != live.shape() {
201        return Err(PipelineError::ShapeMismatch(format!(
202            "counts {:?} and live fractions {:?}",
203            counts.shape(),
204            live.shape()
205        )));
206    }
207    if cells.is_empty() || counts.is_empty() {
208        return Err(PipelineError::InvalidParameter(
209            "a region needs a pixel and a bin".into(),
210        ));
211    }
212    let (rows, columns) = (counts.shape()[1], counts.shape()[2]);
213    if let Some(cell) = cells.iter().find(|[r, c]| *r >= rows || *c >= columns) {
214        return Err(PipelineError::ShapeMismatch(format!(
215            "cell {cell:?} is outside the {rows} × {columns} image"
216        )));
217    }
218    let mut sorted = cells.to_vec();
219    sorted.sort_unstable();
220    if let Some(w) = sorted.windows(2).find(|w| w[0] == w[1]) {
221        return Err(PipelineError::InvalidParameter(format!(
222            "cell {:?} is in the region twice",
223            w[0]
224        )));
225    }
226    (0..counts.shape()[0])
227        .map(|k| {
228            let (mut recorded, mut arrived, mut sum) = (0.0, 0.0, 0.0);
229            for &[r, c] in cells {
230                let (n, l) = (counts[[k, r, c]], live[[k, r, c]]);
231                if !(n.is_finite() && n >= 0.0 && l > 0.0 && l <= 1.0) {
232                    return Err(PipelineError::InvalidParameter(format!(
233                        "bin {k}, pixel ({r}, {c}): count {n} and live fraction {l}"
234                    )));
235                }
236                recorded += n;
237                arrived += n / l;
238                sum += l;
239            }
240            let l = if recorded > 0.0 {
241                recorded / arrived
242            } else {
243                sum / cells.len() as f64
244            };
245            if l > 0.0 && l <= 1.0 {
246                Ok(l)
247            } else {
248                Err(PipelineError::InvalidParameter(format!(
249                    "bin {k}: the region's live fraction {l} is out of range; its counts overflow"
250                )))
251            }
252        })
253        .collect()
254}
255
256/// What the pixels of a patch that are not excluded lie behind.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum Patch {
259    /// The sample, every one: the patch is fitted.
260    Sample,
261    /// The sample and something else: the patch is not fitted.
262    Mixed,
263    /// Not the sample, or every pixel is excluded.
264    Outside,
265}
266
267/// The fitted map, one value per patch.
268#[derive(Debug, Clone)]
269pub struct CountsMap<'a> {
270    measurement: MapMeasurement<'a>,
271    /// Each patch's kind, as [`MapMeasurement::patches`].
272    pub patches: Array2<Patch>,
273    /// Each [`Patch::Sample`]'s fit, the shared quantities held at the map's
274    /// answer; `None` where the patch is not fitted or [`Self::failed`].
275    pub fits: Array2<Option<RegionFit>>,
276    /// Why the fit of a [`Patch::Sample`] left out of the shared quantities at
277    /// the end failed: an error, no convergence, or a fitted temperature at
278    /// 1 K or 5000 K, at the shared values it was last fitted at, marked when
279    /// those are a halved step not taken.  `None` where the patch is not left
280    /// out or not fitted.
281    pub failed: Array2<Option<String>>,
282    /// The empty pixels' fit; `None` when every one is excluded, or when their
283    /// refit at the map's shared values fails, which ends the map
284    /// unconverged.
285    pub empty: Option<RegionFit>,
286    /// Each isotope's areal density in atoms/barn, in the material's order:
287    /// the known one, or the fitted one; NaN where the patch has no fit.
288    pub densities: Vec<Array2<f64>>,
289    /// Standard deviation of each density, from [`PatchCovariances::covariance`]; NaN
290    /// where the density is known, held on a bound or not determined by the
291    /// counts, alone or through a shared quantity, where the patch has no fit,
292    /// or where the map did not converge.
293    pub density_sd: Vec<Array2<f64>>,
294    /// The temperature in K: the known one, or the fitted one; NaN where the
295    /// patch has no fit.
296    pub temperature_k: Array2<f64>,
297    /// Standard deviation of the temperature in K, as [`Self::density_sd`].
298    pub temperature_sd_k: Array2<f64>,
299    /// Each patch's [`RegionFit::overdispersion`] of the open-beam run, then
300    /// of the sample run; NaN where it is `None` or the patch has no fit.
301    pub overdispersion: [Array2<f64>; 2],
302    /// Whether the map converged, the patch did not fail, and the counts
303    /// determine each of its fitted densities and its fitted temperature: each
304    /// has a finite standard deviation or, for a density, is 0.  Whether the
305    /// model describes the patch's counts is its [`Self::overdispersion`];
306    /// neither says whether the values are right.
307    pub identified: Array2<bool>,
308    /// The normalization `a`: the known one, or the fitted one.
309    pub normalization: f64,
310    /// The time background's `[C, A, τ, D]`, each the known or the fitted one.
311    pub time_background: [f64; 4],
312    /// The room background's `ρ`: the known one, the fitted one, or 0 without
313    /// one.
314    pub room_background: f64,
315    /// The timing offset `t0` in µs: the known one, or the fitted one.
316    pub t0_us: f64,
317    /// The flight path in m: the known one, or the fitted one.
318    pub flight_path_m: f64,
319    /// The pulse's `[α₀, α₁]`, each the known or the fitted one.
320    pub alpha: [f64; 2],
321    /// The pulse's `[β₀, β₁]`, each the known or the fitted one.
322    pub beta: [f64; 2],
323    /// The pulse's `[p_α, p_β]`, each the known or the fitted one.
324    pub exponents: [f64; 2],
325    /// The pulse's `R`: the known one, or the fitted one.
326    pub r: f64,
327    /// The square of the pulse's triangle FWHM, `h²` in µs²: the known one, or
328    /// the fitted one.
329    pub fwhm_squared_us2: f64,
330    /// The pulse's `R_high`, the known or the fitted one; `None` without one.
331    pub r_high: Option<f64>,
332    /// The detector tail's `[f, τ_D]`, each the known or the fitted one;
333    /// `None` without one.
334    pub detector_tail: Option<[f64; 2]>,
335    /// The fitted shared quantities, among the normalization, the time
336    /// background's `C`, `A`, `τ` and `D`, the room background's `ρ`, `t0`, flight
337    /// path, `α₀`, `α₁`, `β₀`, `β₁`, `R`, `h²`, `R_high`, `f` and `τ_D`, in that
338    /// order.
339    pub shared: Vec<&'static str>,
340    /// Covariance of [`Self::shared`]: the inverse of the information on them
341    /// of every patch that did not fail and of the empty pixels, each with
342    /// its own quantities and beam profiled out, plus `1/sd²` for each measured
343    /// shared quantity and the pulse calibration's prior.  The row and column
344    /// of one on a bound or not determined by the counts are NaN, and the rest
345    /// are conditional on one on a bound held there.  `None` when the map did
346    /// not converge.
347    pub shared_covariance: Option<FlatMatrix>,
348    /// For each measured one of [`Self::shared`], in that order, its value
349    /// without the bounds less its measurement over `√(sd² − variance)`, the
350    /// variance also without the bounds, as
351    /// [`CountsFit::measured_pulls`](crate::counts_fit::CountsFit::measured_pulls).
352    /// `None` when the map did not converge, or when the fit of a patch or of
353    /// the empty pixels gives no Gaussian without its bounds.
354    pub measured_pulls: Option<Vec<f64>>,
355    /// Whether the counts accept the pulse's calibration, as
356    /// [`CountsFit::pulse_consistency`](crate::counts_fit::CountsFit::pulse_consistency),
357    /// from [`Self::shared`] and the quantities of every patch not
358    /// [`Self::failed`], without their bounds.  `None` without a calibration,
359    /// when [`Self::measured_pulls`] is, or when [`consistency`] gives none.
360    pub pulse_consistency: Option<Consistency>,
361    /// A patch's fitted quantities: each fitted density, in the material's
362    /// order, the temperature and the thickness variance if fitted, each fitted
363    /// background term, and the gamma transmission, capture gammas and
364    /// in-scatter if fitted.
365    pub quantities: Vec<String>,
366    /// Each patch's covariance of [`Self::quantities`] and their joint
367    /// covariance across patches.
368    pub covariances: PatchCovariances,
369    /// Each fit's half Poisson deviance over the overdispersion it weighted
370    /// each run with, summed over the patches with a fit and the empty pixels,
371    /// outside the sample runs' [`RegionFit::excluded_bins`].
372    pub deviance: f64,
373    /// Whether the Newton decrement of the shared quantities fell below
374    /// [`NEWTON_DECREMENT_TOL`] at an answer whose window bins are those the
375    /// patches left out.
376    pub converged: bool,
377    /// Why the map did not converge: the empty pixels' failure, the step
378    /// limit, or a step none of whose halvings lowered the objective.  `None`
379    /// when it converged.
380    pub unconverged: Option<String>,
381    /// Newton steps tried on the shared quantities, those not taken included.
382    pub steps: usize,
383}
384
385impl CountsMap<'_> {
386    /// For each patch row in turn, for the open-beam run, then the sample
387    /// run, the signed deviance residual `sign(y − μ)·√(2(y·ln(y/μ) + μ − y))`
388    /// of each patch's counts `y` in the measurement the map was fitted to and
389    /// its fit's predicted counts `μ` in each bin, in (time bin, patch
390    /// column): `−√(2μ)` where `y` is 0, NaN where the patch has no fit.
391    /// Their squares over twice the overdispersion each run was weighted
392    /// with, summed outside the sample runs' [`RegionFit::excluded_bins`] over
393    /// every patch row with the empty pixels' alike, are [`Self::deviance`].
394    pub fn residual_rows(&self) -> impl Iterator<Item = [Array2<f64>; 2]> + '_ {
395        let map = &self.measurement;
396        let bins = map.open_counts.dim().0;
397        let width = self.patches.ncols();
398        (0..self.patches.nrows()).map(move |i| {
399            let mut row = [
400                Array2::from_elem((bins, width), f64::NAN),
401                Array2::from_elem((bins, width), f64::NAN),
402            ];
403            for j in 0..width {
404                let Some(fit) = &self.fits[[i, j]] else {
405                    continue;
406                };
407                let counts =
408                    summed(map, &map.pixels((i, j))).expect("the fit summed this patch's counts");
409                for (run, residuals) in row.iter_mut().enumerate() {
410                    for (k, (&y, &mu)) in counts[run].iter().zip(&fit.predicted[run]).enumerate() {
411                        residuals[[k, j]] = (2.0 * half_deviance(y, mu)).sqrt().copysign(y - mu);
412                    }
413                }
414            }
415            row
416        })
417    }
418
419    fn unsettled(mut self, reason: String) -> Self {
420        self.converged = false;
421        self.unconverged = Some(reason);
422        self.shared_covariance = None;
423        self.covariances.carried = None;
424        self.measured_pulls = None;
425        self.pulse_consistency = None;
426        self.covariances.covariance.fill(None);
427        for sd in self
428            .density_sd
429            .iter_mut()
430            .chain([&mut self.temperature_sd_k])
431        {
432            sd.fill(f64::NAN);
433        }
434        self.identified.fill(false);
435        self
436    }
437}
438
439/// Each patch's covariance of a map's [`CountsMap::quantities`], their
440/// change with the shared quantities, and the shared quantities' covariance
441/// that joins the patches.
442#[derive(Debug, Clone)]
443pub struct PatchCovariances {
444    /// Each patch's covariance of [`CountsMap::quantities`], the shared
445    /// quantities' uncertainty included; the row and column of one held on a
446    /// bound, or not determined by the counts, alone or through a shared
447    /// quantity, are NaN.  `None` where the patch has no fit or the map has no
448    /// shared covariance.
449    pub covariance: Array2<Option<FlatMatrix>>,
450    /// Each patch's change of [`CountsMap::quantities`] per unit change of each
451    /// of [`CountsMap::shared`] at fixed counts, `−F_oo⁻¹ F_os` of its
452    /// information; the row of a quantity held on a bound or not determined by
453    /// the counts is NaN.  `None` where the patch has no fit.
454    pub sensitivity: Array2<Option<FlatMatrix>>,
455    carried: Option<FlatMatrix>,
456}
457
458impl PatchCovariances {
459    /// The covariance of patch `a`'s [`CountsMap::quantities`] with a different
460    /// patch `b`'s, which only the shared quantities carry, `G_a C_ss G_bᵀ` over
461    /// those not held on a bound; for `a` = `b`, the part of
462    /// [`Self::covariance`] they carry.  `None` where either patch is outside
463    /// the grid or has no [`Self::sensitivity`], or the map has no
464    /// [`CountsMap::shared_covariance`].
465    pub fn cross_covariance(&self, a: (usize, usize), b: (usize, usize)) -> Option<FlatMatrix> {
466        let left = self.sensitivity.get(a)?.as_ref()?;
467        let right = self.sensitivity.get(b)?.as_ref()?;
468        let shared = self.carried.as_ref()?;
469        let k = shared.nrows;
470        let undetermined = |patch: (usize, usize), i: usize| {
471            self.covariance[patch]
472                .as_ref()
473                .is_none_or(|covariance| covariance.get(i, i).is_nan())
474        };
475        let mut cross = FlatMatrix::zeros(left.nrows, right.nrows);
476        for i in 0..left.nrows {
477            for j in 0..right.nrows {
478                *cross.get_mut(i, j) = if undetermined(a, i) || undetermined(b, j) {
479                    f64::NAN
480                } else {
481                    (0..k)
482                        .flat_map(|s| (0..k).map(move |t| (s, t)))
483                        .map(|(s, t)| left.get(i, s) * shared.get(s, t) * right.get(j, t))
484                        .sum()
485                };
486            }
487        }
488        Some(cross)
489    }
490}
491
492/// Fit `map.material` in each patch of `binning`×`binning` pixels whose
493/// pixels not excluded all lie behind the sample, and the empty pixels not
494/// excluded as one region with no material, as one counts fit whose regions
495/// share the normalization, the time and room backgrounds per pixel, `t0`,
496/// the flight path and the pulse: one clock, one flight path, one moderator, one proton
497/// beam, and a detector efficiency that changes between the runs alike in
498/// every pixel.  A region's counts are the sums over its pixels; each has its
499/// own beam, background and gamma transmission, and its time and room
500/// backgrounds are those per pixel times its pixels.  The empty pixels pin the normalization
501/// when their `b0` is known.
502///
503/// Each region's open-beam fit, which starts its beam and weights its
504/// open-beam run, takes the time and room backgrounds' starting numbers as
505/// known; the map is fitted again with them at its fitted numbers, up to twenty times,
506/// until those change the counts the open-beam fits took as known by
507/// `Σ_r Σ_k (ΔO_rk)²/O_rk` at most [`BOUND`] over every region's open-beam
508/// bins, as [`fit_counts`](crate::counts_fit::fit_counts) does; from the
509/// third time on each region keeps the beam intervals its second open-beam
510/// fit chose.  A map that has not settled after twenty is unconverged.
511///
512/// The fit is the joint one of [`fit_counts`](crate::counts_fit::fit_counts),
513/// found region by region.  With the shared quantities held, each region is
514/// fitted alone, in parallel, leaving out the bins of its material's windows
515/// at the shared values the steps last stopped at, first the map's starting
516/// ones, and gives its information and slope on them
517/// with its own quantities and beam profiled out; their sum, with the
518/// calibration's prior and each measured shared quantity's, sets a Newton
519/// step on the shared quantities, clamped
520/// to their bounds, with one on a bound its slope pushes out of held there.
521/// From its second fit on, a region keeps the beam intervals of its first,
522/// starts from its last answer, and counts in its sample run's
523/// overdispersion the leverage the shared quantities have on its bins, as
524/// the joint fit does.  The steps stop when their Newton decrement falls
525/// below [`NEWTON_DECREMENT_TOL`] at fits that counted that leverage and left
526/// out the window bins of the values they stop at; refitting the regions
527/// with new window bins counts as a step.  A
528/// step that raises the regions' summed deviance plus those priors'
529/// penalty, each run weighted with the overdispersion of the step
530/// before, or at which a fitted patch fails, is halved, up to ten times;
531/// twenty steps, a step that cannot fall, or a failure of the empty pixels at
532/// the smallest halving of a step or at their refit at the current values end
533/// the map unconverged.  The shared information and each region's
534/// information on its own quantities are inverted as [`information_inverse`]
535/// inverts them, the shared one scaled to its diagonal before the regions'
536/// own quantities are profiled out, with the rounding of one region's bins:
537/// the steps take every direction the information spans, and a quantity
538/// along a direction it does not determine, or moving along one through the
539/// shared quantities, has a NaN covariance.  Each of the map's regions holds
540/// its grid's spread to its share of the map's counts times [`BOUND`], so
541/// their summed spread is within the `BOUND` the joint fit holds it to.
542///
543/// A patch whose fit fails, does not converge, or ends at a fitted
544/// temperature of 1 K or 5000 K, at the starting shared values, at the
545/// smallest halving of a step none of whose halvings is taken, or at a refit
546/// at the current values, adds nothing to the shared quantities; it is fitted again after every step taken and
547/// adds to them again once it fits.  A patch left out at the end is
548/// [`CountsMap::failed`].
549///
550/// A patch has one density per isotope and one temperature: where its
551/// pixels differ, these are the uniform fit of the patch's summed counts,
552/// which differs from the pixels' beam-weighted means.
553///
554/// The map holds, for each patch, its summed counts and its fits at the
555/// current and the trial shared values, so its memory is up to several
556/// times that of the counts it is given; each region's grid gets finer as
557/// the number of regions grows.
558///
559/// # Errors
560/// Everything [`MapMeasurement::patches`] refuses;
561/// [`PipelineError::InvalidParameter`] if a pixel is both behind the sample
562/// and empty, a density, the temperature, the thickness variance, a
563/// background term, the gamma transmission, the capture gammas or the
564/// in-scatter of the sample's patches is [`Value::Measured`], which would
565/// count its measurement once per patch, a term of the empty pixels' background is
566/// [`Value::Measured`], the material carries resonance covariances, which a
567/// map does not yet carry, a count of a pixel summed into a region is not a
568/// whole non-negative number, or no patch is fitted; every refusal of
569/// [`fit_counts`](crate::counts_fit::fit_counts) for the material, the
570/// backgrounds, the shared quantities and the pulse's calibration;
571/// [`PipelineError::Fitting`] if the pulse's calibration has a covariance
572/// that cannot be inverted or an eigendecomposition fails;
573/// [`PipelineError::ShapeMismatch`] or [`PipelineError::InvalidParameter`] for
574/// live fractions `fit_counts` refuses; [`PipelineError::FlightTimeGrid`] if
575/// the grid refuses the time edges at the starting shared values.
576/// [`PipelineError::InvalidParameter`] naming the first failing patch and its
577/// error when no patch fits at the starting shared values, or naming the
578/// empty pixels when their fit fails there; [`PipelineError::InvalidParameter`]
579/// with the last patch's reason when every patch is left out later.
580pub fn fit_map<'a>(
581    map: &MapMeasurement<'a>,
582    calibration: &Calibration,
583) -> Result<CountsMap<'a>, PipelineError> {
584    map.patches()?;
585    let mut open = starting_bypass(&Measurement {
586        time_edges_us: Vec::new(),
587        charge_ratio: map.charge_ratio,
588        normalization: map.normalization,
589        time_background: map.time_background,
590        room_background: map.room_background,
591        spread: None,
592        environment_scatter: None,
593        filter: None,
594        regions: Vec::new(),
595    })?;
596    let bins = starts_and_widths_us(&map.time_edges_us);
597    let frames = open_frames(map.room_background.as_ref());
598    let empty_pixels: Vec<(usize, usize)> = map
599        .empty
600        .indexed_iter()
601        .filter(|&(pixel, &e)| e && !map.excluded[pixel])
602        .map(|(pixel, _)| pixel)
603        .collect();
604    let mut intervals: Option<Vec<Option<usize>>> = None;
605    for passes in 1..=MOST_PASSES {
606        let result = fit_map_from(map, calibration, open, intervals.as_deref())?;
607        let fitted = Bypass {
608            time: result.time_background,
609            room: result.room_background,
610        };
611        let used = open.open_counts_per_pixel(&bins, 0.0, frames);
612        let now = fitted.open_counts_per_pixel(&bins, 0.0, frames);
613        let regions = || {
614            result
615                .fits
616                .indexed_iter()
617                .filter_map(|(patch, fit)| Some((fit.as_ref()?, map.pixels(patch))))
618                .chain(result.empty.as_ref().map(|fit| (fit, empty_pixels.clone())))
619        };
620        let mut spread = 0.0;
621        for (fit, pixels) in regions() {
622            let [live, _] = map.region_lives(&pixels)?;
623            for (k, &mu) in fit.predicted[0]
624                .iter()
625                .enumerate()
626                .filter(|(_, mu)| **mu > 0.0)
627            {
628                let live = live.as_ref().map_or(1.0, |live| live[k]);
629                spread += (live * pixels.len() as f64 * (now[k] - used[k])).powi(2) / mu;
630            }
631        }
632        if !result.converged || spread <= BOUND {
633            return Ok(result);
634        }
635        if passes == MOST_PASSES {
636            return Ok(result.unsettled(format!(
637                "the open-beam fits' time and room backgrounds did not settle in {MOST_PASSES} \
638                 fits"
639            )));
640        }
641        if passes >= 2 {
642            intervals.get_or_insert_with(|| {
643                result
644                    .patches
645                    .indexed_iter()
646                    .filter(|&(_, &kind)| kind == Patch::Sample)
647                    .map(|(patch, _)| result.fits[patch].as_ref().map(|f| f.beam.intervals()))
648                    .chain(
649                        (!empty_pixels.is_empty())
650                            .then(|| result.empty.as_ref().map(|f| f.beam.intervals())),
651                    )
652                    .collect()
653            });
654        }
655        open = fitted;
656    }
657    unreachable!("the passes end at MOST_PASSES")
658}
659
660fn fit_map_from<'a>(
661    map: &MapMeasurement<'a>,
662    calibration: &Calibration,
663    open: Bypass,
664    intervals: Option<&[Option<usize>]>,
665) -> Result<CountsMap<'a>, PipelineError> {
666    let invalid = |message: String| Err(PipelineError::InvalidParameter(message));
667    let patches = map.patches()?;
668    if map.sample.iter().zip(&map.empty).any(|(&s, &e)| s && e) {
669        return invalid("a pixel is both behind the sample and empty".into());
670    }
671    let material = &map.material;
672    if material
673        .isotopes
674        .iter()
675        .map(|(_, density)| density)
676        .chain([&material.temperature_k, &material.thickness_variance])
677        .chain(&map.background)
678        .chain([
679            &map.gamma_transmission,
680            &map.capture_gammas,
681            &map.in_scatter,
682        ])
683        .any(|value| matches!(value, Value::Measured { .. }))
684    {
685        return invalid(
686            "a measured density, temperature, thickness variance, background, gamma \
687             transmission, capture gammas or in-scatter of the sample's patches would count its \
688             measurement once per patch; give it known, fitted or within bounds"
689                .into(),
690        );
691    }
692    if !material.covariances.is_empty() {
693        return invalid("a map does not yet carry the resonance parameters' covariance".into());
694    }
695    if map
696        .empty_background
697        .iter()
698        .any(|value| matches!(value, Value::Measured { .. }))
699    {
700        return invalid(
701            "a measured background of the empty pixels is not supported by the map's region by \
702             region fit; give it known, fitted or within bounds"
703                .into(),
704        );
705    }
706    let fitted_patches: Vec<(usize, usize)> = patches
707        .indexed_iter()
708        .filter(|&(_, &kind)| kind == Patch::Sample)
709        .map(|(patch, _)| patch)
710        .collect();
711    if fitted_patches.is_empty() {
712        let b = map.binning;
713        return invalid(format!(
714            "no patch of {b}×{b} pixels has all its pixels not excluded behind the sample"
715        ));
716    }
717    let empty: Vec<(usize, usize)> = map
718        .empty
719        .indexed_iter()
720        .filter(|&(pixel, &e)| e && !map.excluded[pixel])
721        .map(|(pixel, _)| pixel)
722        .collect();
723    let region =
724        |pixels: &[(usize, usize)], background, gamma_transmission, material: Option<Material>| {
725            let [open_counts, sample_counts] = summed(map, pixels)?;
726            let [open_live, sample_live] = map.region_lives(pixels)?;
727            Ok::<_, PipelineError>(Region {
728                open_counts,
729                sample_counts,
730                open_live,
731                sample_live,
732                background,
733                pixels: pixels.len() as f64,
734                gamma_transmission,
735                capture_gammas: if material.is_some() {
736                    map.capture_gammas
737                } else {
738                    Value::Known(0.0)
739                },
740                in_scatter: if material.is_some() {
741                    map.in_scatter
742                } else {
743                    Value::Known(0.0)
744                },
745                timing_offset_us: Value::Known(0.0),
746                material,
747            })
748        };
749    let mut regions = fitted_patches
750        .iter()
751        .map(|&patch| {
752            region(
753                &map.pixels(patch),
754                map.background,
755                map.gamma_transmission,
756                Some(material.clone()),
757            )
758        })
759        .collect::<Result<Vec<Region>, PipelineError>>()?;
760    if !empty.is_empty() {
761        regions.push(region(
762            &empty,
763            map.empty_background,
764            Value::Known(1.0),
765            None,
766        )?);
767    }
768    let measurement = |normalization, time_background, room_background, regions| Measurement {
769        time_edges_us: map.time_edges_us.clone(),
770        charge_ratio: map.charge_ratio,
771        normalization,
772        time_background,
773        room_background,
774        spread: None,
775        environment_scatter: None,
776        filter: None,
777        regions,
778    };
779
780    let template = |background, gamma_transmission, material: Option<Material>| Region {
781        open_counts: Vec::new(),
782        sample_counts: Vec::new(),
783        open_live: None,
784        sample_live: None,
785        background,
786        pixels: 1.0,
787        gamma_transmission,
788        capture_gammas: if material.is_some() {
789            map.capture_gammas
790        } else {
791            Value::Known(0.0)
792        },
793        in_scatter: if material.is_some() {
794            map.in_scatter
795        } else {
796            Value::Known(0.0)
797        },
798        timing_offset_us: Value::Known(0.0),
799        material,
800    };
801    checked(
802        &measurement(
803            map.normalization,
804            map.time_background,
805            map.room_background,
806            std::iter::once(template(
807                map.background,
808                map.gamma_transmission,
809                Some(material.clone()),
810            ))
811            .chain(
812                (!empty.is_empty())
813                    .then(|| template(map.empty_background, Value::Known(1.0), None)),
814            )
815            .collect(),
816        ),
817        calibration,
818    )?;
819    let parameters = shared_parameters(
820        &measurement(
821            map.normalization,
822            map.time_background,
823            map.room_background,
824            vec![],
825        ),
826        calibration,
827    )?;
828    let at = |role: Role| {
829        SHARED
830            .iter()
831            .position(|&shared| shared == role)
832            .expect("a shared role")
833    };
834    let (time_background, room, t0) = (
835        at(Role::TimeBackground(0)),
836        at(Role::RoomBackground),
837        at(Role::T0),
838    );
839    let instrument = t0..SHARED.len();
840    let fitted: Vec<usize> = (0..SHARED.len())
841        .filter(|&i| !parameters[i].1.fixed)
842        .collect();
843    let roles: Vec<Role> = fitted.iter().map(|&i| SHARED[i]).collect();
844    let k = fitted.len();
845    let mut prior = Mat::<f64>::zeros(k, k);
846    let mut center = vec![0.0; k];
847    for (a, &i) in fitted.iter().enumerate() {
848        if let Value::Measured { value, sd } = parameters[i].0 {
849            prior[(a, a)] = 1.0 / (sd * sd);
850            center[a] = value;
851        }
852    }
853    let mut calibrated = None;
854    if let Some(pulse) = &calibration.pulse.prior {
855        let at: Vec<usize> = pulse
856            .numbers
857            .iter()
858            .map(|&n| fitted.iter().position(|&i| SHARED[i] == Role::Pulse(n)))
859            .collect::<Option<_>>()
860            .expect("a calibrated number is fitted");
861        let numbers = Prior::correlated(&at, &pulse.mean, &pulse.covariance)?;
862        let inverse = Mat::from_fn(at.len(), at.len(), |a, b| pulse.covariance.get(a, b))
863            .llt(Side::Lower)
864            .map_err(|e| FittingError::EvaluationFailed(format!("{e:?}")))?
865            .inverse();
866        for (a, &i) in at.iter().enumerate() {
867            center[i] = pulse.mean[a];
868            for (b, &j) in at.iter().enumerate() {
869                prior[(i, j)] = inverse[(a, b)];
870            }
871        }
872        calibrated = Some((numbers, at));
873    }
874    let penalty = |values: &[f64]| -> (f64, Vec<f64>) {
875        let offset: Vec<f64> = (0..k).map(|a| values[fitted[a]] - center[a]).collect();
876        let slope: Vec<f64> = (0..k)
877            .map(|a| (0..k).map(|b| prior[(a, b)] * offset[b]).sum())
878            .collect();
879        (
880            0.5 * offset.iter().zip(&slope).map(|(o, s)| o * s).sum::<f64>(),
881            slope,
882        )
883    };
884
885    let mut values: Vec<f64> = parameters.iter().map(|(_, p)| p.value).collect();
886    let origin_us = values[t0];
887    let open_per_pixel = open.open_counts_per_pixel(
888        &starts_and_widths_us(&map.time_edges_us),
889        0.0,
890        open_frames(map.room_background.as_ref()),
891    );
892    let bins = map.open_counts.dim().0;
893    let (t_low, t_high) = TEMPERATURE_BOUNDS_K;
894    let fitted_temperature = !matches!(material.temperature_k, Value::Known(_));
895    let labels: Vec<String> = fitted_patches
896        .iter()
897        .map(|patch| format!("patch {patch:?}"))
898        .chain((!empty.is_empty()).then(|| "the empty pixels".to_string()))
899        .collect();
900    let patch_count = fitted_patches.len();
901    let held_at = |values: &[f64]| {
902        let known = |i: usize| Value::Known(values[t0 + i]);
903        Calibration {
904            t0_us: known(0),
905            flight_path_m: known(1),
906            pulse: Pulse {
907                alpha: [known(2), known(3)],
908                beta: [known(4), known(5)],
909                exponents: [known(11), known(12)],
910                r: known(6),
911                fwhm_squared_us2: known(7),
912                r_high: calibration.pulse.r_high.map(|_| known(8)),
913                detector_tail: calibration
914                    .pulse
915                    .detector_tail
916                    .map(|_| [known(9), known(10)]),
917                prior: None,
918                ..calibration.pulse.clone()
919            },
920        }
921    };
922    let starting = held_at(&values);
923    let excluded_at = |values: &[f64]| -> Vec<Vec<usize>> {
924        regions
925            .iter()
926            .map(|region| {
927                excluded_bins(
928                    &map.time_edges_us,
929                    region.material.as_ref(),
930                    &values[instrument.clone()],
931                    calibration.pulse.storage_span(),
932                )
933            })
934            .collect()
935    };
936    let excluded = RwLock::new(excluded_at(&values));
937    let counted_in =
938        |region: &Region| -> f64 { region.open_counts.iter().chain(&region.sample_counts).sum() };
939    let all_counts: f64 = regions.iter().map(counted_in).sum();
940    let budgets: Vec<f64> = regions
941        .iter()
942        .map(|region| BOUND * counted_in(region) / all_counts)
943        .collect();
944    let fit_region = |r: usize,
945                      values: &[f64],
946                      previous: Option<&RegionFit>,
947                      shared_leverage: Option<f64>|
948     -> Swept {
949        let held = held_at(values);
950        let label = &labels[r];
951        let one = measurement(
952            Value::Known(values[at(Role::Normalization)]),
953            std::array::from_fn(|i| Value::Known(values[time_background + i])),
954            map.room_background.map(|room_background| RoomBackground {
955                rate: Value::Known(values[room]),
956                ..room_background
957            }),
958            vec![restarted(&regions[r], previous)],
959        );
960        let beam = match previous {
961            Some(fit) => BeamStart {
962                beam: fit.beam.clone(),
963                overdispersion: fit.overdispersion[0],
964                at_limit: fit.beam_at_limit,
965            },
966            None => {
967                let known: Vec<f64> = open_per_pixel
968                    .iter()
969                    .map(|g| regions[r].pixels * g)
970                    .collect();
971                open_beam_with_intervals(
972                    &map.time_edges_us,
973                    &regions[r].open_counts,
974                    &starting,
975                    regions[r].open_live.as_deref(),
976                    Some(&known),
977                    intervals.and_then(|chosen| chosen[r]),
978                    None,
979                )
980                .map_err(|e| named(label, e))?
981                .into()
982            }
983        };
984        let starts = Starts {
985            beams: vec![beam],
986            origin_us,
987            shared_leverage: shared_leverage.map(|extra| vec![extra]),
988            bound: budgets[r],
989            excluded: vec![excluded.read().expect("the bin lists")[r].clone()],
990        };
991        let (fit, answer) = fit_counts_answer(&one, &held, BeamStarts::Given(&starts), None)
992            .map_err(|e| named(label, e))?;
993        let region_fit = fit.regions.into_iter().next().expect("one region");
994        let edge = fitted_temperature
995            && region_fit
996                .temperature_k
997                .is_some_and(|t| t == t_low || t == t_high);
998        if edge {
999            return Err(PipelineError::InvalidParameter(format!(
1000                "{label}: its temperature ended at {t_low} K or {t_high} K"
1001            )));
1002        }
1003        if !fit.converged {
1004            return Err(PipelineError::InvalidParameter(format!(
1005                "{label}: its fit did not converge"
1006            )));
1007        }
1008        let mut terms = answer
1009            .region_terms(0, &roles)
1010            .map_err(|e| named(label, e))?;
1011        if fit.unbounded.is_none() {
1012            terms.unbounded = None;
1013        }
1014        Ok(Inner {
1015            fit: region_fit,
1016            deviance: fit.deviance,
1017            terms,
1018        })
1019    };
1020    let sweep = |values: &[f64],
1021                 previous: &[Option<RegionFit>],
1022                 leverage: &[Option<f64>],
1023                 failures: &[Option<String>],
1024                 failed: bool|
1025     -> Vec<Option<Swept>> {
1026        (0..regions.len())
1027            .into_par_iter()
1028            .map(|r| {
1029                (failures[r].is_some() == failed)
1030                    .then(|| fit_region(r, values, previous[r].as_ref(), leverage[r]))
1031            })
1032            .collect()
1033    };
1034    let objective = |inner: &[Option<Inner>], weights: &[Option<Inner>]| -> f64 {
1035        inner
1036            .iter()
1037            .zip(weights)
1038            .zip(&regions)
1039            .filter_map(|((inner, weights), region)| {
1040                Some((inner.as_ref()?, weights.as_ref()?, region))
1041            })
1042            .map(|(inner, weights, region)| {
1043                [&region.open_counts, &region.sample_counts]
1044                    .into_iter()
1045                    .zip(&inner.fit.predicted)
1046                    .enumerate()
1047                    .map(|(run, (counts, predicted))| {
1048                        counts
1049                            .iter()
1050                            .zip(predicted)
1051                            .enumerate()
1052                            .filter(|(k, _)| run == 0 || !inner.fit.excluded_bins.contains(k))
1053                            .map(|(_, (&y, &mu))| half_deviance(y, mu))
1054                            .sum::<f64>()
1055                            / weight(&weights.fit, run)
1056                    })
1057                    .sum::<f64>()
1058            })
1059            .sum()
1060    };
1061
1062    let mut failures: Vec<Option<String>> = vec![None; regions.len()];
1063    let mut leverage: Vec<Option<f64>> = vec![None; regions.len()];
1064    let mut previous: Vec<Option<RegionFit>> = vec![None; regions.len()];
1065    let mut inner: Vec<Option<Inner>> = Vec::with_capacity(regions.len());
1066    let mut first_failure = None;
1067    for (r, swept) in sweep(&values, &previous, &leverage, &failures, false)
1068        .into_iter()
1069        .enumerate()
1070    {
1071        match swept.expect("every region is fitted at the start") {
1072            Ok(one) => inner.push(Some(one)),
1073            Err(error) if r >= patch_count => return Err(error),
1074            Err(error) => {
1075                failures[r] = Some(error.to_string());
1076                first_failure.get_or_insert(error);
1077                inner.push(None);
1078            }
1079        }
1080    }
1081    if inner[..patch_count].iter().all(Option::is_none) {
1082        return Err(first_failure.expect("a patch failed"));
1083    }
1084    let absorb = |swept: Vec<Option<Swept>>,
1085                  inner: &mut [Option<Inner>],
1086                  failures: &mut [Option<String>]| {
1087        let mut joined = false;
1088        for (r, one) in swept.into_iter().enumerate() {
1089            match one {
1090                Some(Ok(one)) => {
1091                    joined |= failures[r].is_some();
1092                    failures[r] = None;
1093                    inner[r] = Some(one);
1094                }
1095                Some(Err(error)) => {
1096                    failures[r] = Some(error.to_string());
1097                    inner[r] = None;
1098                }
1099                None => {}
1100            }
1101        }
1102        joined
1103    };
1104    let none_left = |failures: &[Option<String>]| {
1105        let reason = failures[..patch_count].iter().flatten().last();
1106        invalid(format!(
1107            "every patch of the map failed; the last: {}",
1108            reason.map_or("", String::as_str)
1109        ))
1110    };
1111    let counted = 2 * bins;
1112    let inverse_over = |total: &Mat<f64>, diagonal: &[f64], set: &[usize]| {
1113        let mut block = FlatMatrix::zeros(set.len(), set.len());
1114        for (a, &i) in set.iter().enumerate() {
1115            for (b, &j) in set.iter().enumerate() {
1116                *block.get_mut(a, b) = total[(i, j)];
1117            }
1118        }
1119        let diagonal: Vec<f64> = set.iter().map(|&i| diagonal[i]).collect();
1120        information_inverse(&block, &diagonal, counted)
1121    };
1122    let mut steps = 0;
1123    let mut converged = false;
1124    let mut unconverged = None;
1125    let mut weighted = false;
1126    let information = loop {
1127        for (kept, inner) in previous.iter_mut().zip(&inner) {
1128            if let Some(inner) = inner {
1129                *kept = Some(inner.fit.clone());
1130            }
1131        }
1132        let (_, prior_slope) = penalty(&values);
1133        let mut gradient = prior_slope;
1134        let mut total = prior.clone();
1135        let mut diagonal: Vec<f64> = (0..k).map(|a| prior[(a, a)]).collect();
1136        for terms in inner.iter().flatten().map(|inner| &inner.terms) {
1137            for a in 0..k {
1138                gradient[a] += terms.gradient[a];
1139                diagonal[a] += terms.diagonal[a];
1140                for b in 0..k {
1141                    total[(a, b)] += terms.information.get(a, b);
1142                }
1143            }
1144        }
1145        let free: Vec<usize> = (0..k)
1146            .filter(|&a| {
1147                let (value, parameter) = (values[fitted[a]], &parameters[fitted[a]].1);
1148                !(value == parameter.lower && gradient[a] > 0.0
1149                    || value == parameter.upper && gradient[a] < 0.0)
1150            })
1151            .collect();
1152        let off_bounds: Vec<usize> = (0..k)
1153            .filter(|&a| {
1154                let (value, parameter) = (values[fitted[a]], &parameters[fitted[a]].1);
1155                value != parameter.lower && value != parameter.upper
1156            })
1157            .collect();
1158        let spread = inverse_over(&total, &diagonal, &off_bounds)?.spanned;
1159        for (shared_leverage, inner) in leverage.iter_mut().zip(&inner) {
1160            if let Some(Inner { terms, .. }) = inner {
1161                *shared_leverage = Some(
1162                    (0..off_bounds.len())
1163                        .flat_map(|a| (0..off_bounds.len()).map(move |b| (a, b)))
1164                        .map(|(a, b)| {
1165                            terms.counted_information.get(off_bounds[a], off_bounds[b])
1166                                * spread.get(a, b)
1167                        })
1168                        .sum(),
1169                );
1170            }
1171        }
1172        let covariance = inverse_over(&total, &diagonal, &free)?.spanned;
1173        let step: Vec<f64> = (0..free.len())
1174            .map(|a| {
1175                -(0..free.len())
1176                    .map(|b| covariance.get(a, b) * gradient[free[b]])
1177                    .sum::<f64>()
1178            })
1179            .collect();
1180        let decrement: f64 = -0.5
1181            * (0..free.len())
1182                .map(|a| gradient[free[a]] * step[a])
1183                .sum::<f64>();
1184        if decrement < NEWTON_DECREMENT_TOL {
1185            let at_answer = excluded_at(&values);
1186            if weighted && at_answer != *excluded.read().expect("the bin lists") {
1187                if steps == MOST_STEPS {
1188                    unconverged = Some(format!("{MOST_STEPS} Newton steps did not converge"));
1189                    break None;
1190                }
1191                steps += 1;
1192                *excluded.write().expect("the bin lists") = at_answer;
1193                let retried = sweep(&values, &previous, &leverage, &failures, true);
1194                if absorb(retried, &mut inner, &mut failures) {
1195                    weighted = false;
1196                    continue;
1197                }
1198            } else if weighted {
1199                converged = true;
1200                let mut unbounded = Some((prior.clone(), penalty(&values).1));
1201                for terms in inner.iter().flatten().map(|inner| &inner.terms) {
1202                    match (&mut unbounded, &terms.unbounded) {
1203                        (Some((total, slope)), Some((information, region_slope))) => {
1204                            for a in 0..k {
1205                                slope[a] += region_slope[a];
1206                                for b in 0..k {
1207                                    total[(a, b)] += information.get(a, b);
1208                                }
1209                            }
1210                        }
1211                        _ => unbounded = None,
1212                    }
1213                }
1214                break Some((total, diagonal, unbounded));
1215            }
1216            weighted = true;
1217            let swept = sweep(&values, &previous, &leverage, &failures, false);
1218            absorb(swept, &mut inner, &mut failures);
1219            if let Some(reason) = failures[patch_count..].iter().flatten().next() {
1220                unconverged = Some(reason.clone());
1221                break None;
1222            }
1223            if inner[..patch_count].iter().all(Option::is_none) {
1224                return none_left(&failures);
1225            }
1226            continue;
1227        }
1228        if steps == MOST_STEPS {
1229            unconverged = Some(format!("{MOST_STEPS} Newton steps did not converge"));
1230            break None;
1231        }
1232        steps += 1;
1233        let before = objective(&inner, &inner) + penalty(&values).0;
1234        let mut lost: Vec<(usize, String)> = Vec::new();
1235        let accepted = (0..=MOST_HALVINGS).find_map(|halving| {
1236            let mut trial = values.clone();
1237            for (a, &f) in free.iter().enumerate() {
1238                let parameter = &parameters[fitted[f]].1;
1239                trial[fitted[f]] = (values[fitted[f]] + step[a] / f64::powi(2.0, halving))
1240                    .clamp(parameter.lower, parameter.upper);
1241            }
1242            let swept = sweep(&trial, &previous, &leverage, &failures, false);
1243            lost = swept
1244                .iter()
1245                .enumerate()
1246                .filter_map(|(r, one)| match one {
1247                    Some(Err(error)) => Some((r, error.to_string())),
1248                    _ => None,
1249                })
1250                .collect();
1251            if !lost.is_empty() {
1252                return None;
1253            }
1254            let candidate: Vec<Option<Inner>> = swept
1255                .into_iter()
1256                .map(|one| one.and_then(Result::ok))
1257                .collect();
1258            (objective(&candidate, &inner) + penalty(&trial).0 <= before)
1259                .then_some((trial, candidate))
1260        });
1261        match accepted {
1262            Some((trial, candidate)) => {
1263                values = trial;
1264                inner = candidate;
1265                let retried = sweep(&values, &previous, &leverage, &failures, true);
1266                weighted = !absorb(retried, &mut inner, &mut failures);
1267            }
1268            None if !lost.is_empty() && lost.iter().all(|&(r, _)| r < patch_count) => {
1269                for (r, reason) in lost {
1270                    failures[r] = Some(format!("{reason} (at a halved step not taken)"));
1271                    inner[r] = None;
1272                }
1273                weighted = false;
1274                if inner[..patch_count].iter().all(Option::is_none) {
1275                    return none_left(&failures);
1276                }
1277            }
1278            None => {
1279                let empty_first = lost
1280                    .iter()
1281                    .position(|&(r, _)| r >= patch_count)
1282                    .unwrap_or(0);
1283                unconverged = Some(lost.into_iter().nth(empty_first).map_or_else(
1284                    || "no halving of a Newton step lowered the objective".to_string(),
1285                    |(_, reason)| reason,
1286                ));
1287                break None;
1288            }
1289        }
1290    };
1291
1292    let interior: Vec<usize> = (0..k)
1293        .filter(|&a| {
1294            let (value, parameter) = (values[fitted[a]], &parameters[fitted[a]].1);
1295            value != parameter.lower && value != parameter.upper
1296        })
1297        .collect();
1298    let embedded = |set: &[usize], inverse: &InformationInverse| {
1299        let mut covariance = FlatMatrix::zeros(k, k);
1300        covariance.data.fill(f64::NAN);
1301        for (a, &i) in set.iter().enumerate() {
1302            for (b, &j) in set.iter().enumerate() {
1303                if inverse.resolved[a] && inverse.resolved[b] {
1304                    *covariance.get_mut(i, j) = inverse.determined.get(a, b);
1305                }
1306            }
1307        }
1308        covariance
1309    };
1310    let interior_inverse = match &information {
1311        Some((total, diagonal, _)) => Some(inverse_over(total, diagonal, &interior)?),
1312        None => None,
1313    };
1314    let shared_covariance = interior_inverse
1315        .as_ref()
1316        .map(|inverse| embedded(&interior, inverse));
1317    let propagated = interior_inverse
1318        .as_ref()
1319        .map(|inverse| propagated(k, &interior, inverse));
1320    let null: Vec<Vec<f64>> = interior_inverse
1321        .iter()
1322        .flat_map(|inverse| &inverse.undetermined)
1323        .map(|direction| {
1324            let mut along = vec![0.0; k];
1325            for (a, &i) in interior.iter().enumerate() {
1326                along[i] = direction[a];
1327            }
1328            along
1329        })
1330        .collect();
1331    let every: Vec<usize> = (0..k).collect();
1332    let unbounded = match &information {
1333        Some((_, diagonal, Some((total, gradient)))) => {
1334            let inverse = inverse_over(total, diagonal, &every)?;
1335            let mean: Vec<f64> = (0..k)
1336                .map(|a| {
1337                    if inverse.resolved[a] {
1338                        values[fitted[a]]
1339                            - (0..k)
1340                                .map(|b| inverse.determined.get(a, b) * gradient[b])
1341                                .sum::<f64>()
1342                    } else {
1343                        f64::NAN
1344                    }
1345                })
1346                .collect();
1347            Some((mean, embedded(&every, &inverse)))
1348        }
1349        _ => None,
1350    };
1351    let pulse_consistency = match (&calibrated, &unbounded) {
1352        (Some((numbers, at)), Some((mean, inverse))) => {
1353            let mut posterior = FlatMatrix::zeros(at.len(), at.len());
1354            for (a, &i) in at.iter().enumerate() {
1355                for (b, &j) in at.iter().enumerate() {
1356                    *posterior.get_mut(a, b) = inverse.get(i, j);
1357                }
1358            }
1359            let estimate: Vec<f64> = at.iter().map(|&i| mean[i]).collect();
1360            consistency(numbers, &estimate, &posterior)?
1361        }
1362        _ => None,
1363    };
1364    let measured_pulls = unbounded.as_ref().map(|(mean, inverse)| {
1365        (0..k)
1366            .filter_map(|a| match parameters[fitted[a]].0 {
1367                Value::Measured { value, sd } => {
1368                    Some((mean[a] - value) / (sd * sd - inverse.get(a, a)).sqrt())
1369                }
1370                _ => None,
1371            })
1372            .collect()
1373    });
1374    let template: Vec<(Role, String)> = material
1375        .isotopes
1376        .iter()
1377        .enumerate()
1378        .filter(|(_, (_, density))| !matches!(density, Value::Known(_)))
1379        .map(|(isotope, (data, _))| {
1380            (
1381                Role::Density { region: 0, isotope },
1382                format!("density of {}", data.isotope),
1383            )
1384        })
1385        .chain(
1386            (!matches!(material.temperature_k, Value::Known(_)))
1387                .then(|| (Role::Temperature { region: 0 }, "temperature".to_string())),
1388        )
1389        .chain(
1390            (!matches!(material.thickness_variance, Value::Known(_))).then(|| {
1391                (
1392                    Role::ThicknessVariance { region: 0 },
1393                    "thickness variance".to_string(),
1394                )
1395            }),
1396        )
1397        .chain(
1398            map.background
1399                .iter()
1400                .enumerate()
1401                .filter(|(_, value)| !matches!(value, Value::Known(_)))
1402                .map(|(term, _)| {
1403                    (
1404                        Role::Background { region: 0, term },
1405                        BACKGROUND_TERMS[term].to_string(),
1406                    )
1407                }),
1408        )
1409        .chain(
1410            (!matches!(map.gamma_transmission, Value::Known(_))).then(|| {
1411                (
1412                    Role::GammaTransmission { region: 0 },
1413                    "gamma transmission".to_string(),
1414                )
1415            }),
1416        )
1417        .chain((!matches!(map.capture_gammas, Value::Known(_))).then(|| {
1418            (
1419                Role::CaptureGammas { region: 0 },
1420                "capture gammas".to_string(),
1421            )
1422        }))
1423        .chain(
1424            (!matches!(map.in_scatter, Value::Known(_)))
1425                .then(|| (Role::InScatter { region: 0 }, "in-scatter".to_string())),
1426        )
1427        .collect();
1428    let q = template.len();
1429
1430    let (rows, cols) = patches.dim();
1431    let blank = Array2::from_elem((rows, cols), f64::NAN);
1432    let isotopes = material.isotopes.len();
1433    let mut densities = vec![blank.clone(); isotopes];
1434    let mut density_sd = vec![blank.clone(); isotopes];
1435    let mut temperature_k = blank.clone();
1436    let mut temperature_sd_k = blank.clone();
1437    let mut overdispersion = [blank.clone(), blank];
1438    let mut identified = Array2::from_elem((rows, cols), false);
1439    let mut failed = Array2::from_elem((rows, cols), None);
1440    let mut fits = Array2::from_elem((rows, cols), None);
1441    let mut covariance = Array2::from_elem((rows, cols), None);
1442    let mut sensitivity = Array2::from_elem((rows, cols), None);
1443    for (r, &patch) in fitted_patches.iter().enumerate() {
1444        let Some(Inner { fit, terms, .. }) = &inner[r] else {
1445            failed[patch] = failures[r].clone();
1446            continue;
1447        };
1448        let rows_of: Vec<Option<usize>> = template
1449            .iter()
1450            .map(|(role, _)| terms.quantities.iter().position(|q| q == role))
1451            .collect();
1452        let mut slopes = FlatMatrix::zeros(q, k);
1453        for (a, row) in rows_of.iter().enumerate() {
1454            for s in 0..k {
1455                *slopes.get_mut(a, s) = row.map_or(f64::NAN, |i| terms.sensitivity.get(i, s));
1456            }
1457        }
1458        let marginal = propagated.as_ref().map(|shared| {
1459            let mut marginal = FlatMatrix::zeros(q, q);
1460            for (a, row_a) in rows_of.iter().enumerate() {
1461                for (b, row_b) in rows_of.iter().enumerate() {
1462                    *marginal.get_mut(a, b) = match (row_a, row_b) {
1463                        (Some(i), Some(j)) => marginal_entry(
1464                            &terms.covariance,
1465                            &terms.sensitivity,
1466                            shared,
1467                            &null,
1468                            (*i, *j),
1469                        ),
1470                        _ => f64::NAN,
1471                    };
1472                }
1473            }
1474            marginal
1475        });
1476        let sd = |role: Role| {
1477            template
1478                .iter()
1479                .position(|(r, _)| *r == role)
1480                .zip(marginal.as_ref())
1481                .map_or(f64::NAN, |(a, marginal)| marginal.get(a, a).sqrt())
1482        };
1483        for (m, &density) in fit.densities.iter().enumerate() {
1484            densities[m][patch] = density;
1485            density_sd[m][patch] = sd(Role::Density {
1486                region: 0,
1487                isotope: m,
1488            });
1489        }
1490        temperature_k[patch] = fit.temperature_k.unwrap_or(f64::NAN);
1491        temperature_sd_k[patch] = sd(Role::Temperature { region: 0 });
1492        for (run, phi) in overdispersion.iter_mut().zip(fit.overdispersion) {
1493            run[patch] = phi.unwrap_or(f64::NAN);
1494        }
1495        identified[patch] = converged
1496            && template.iter().all(|&(role, _)| match role {
1497                Role::Density { isotope, .. } => {
1498                    sd(role).is_finite() || fit.densities[isotope] == 0.0
1499                }
1500                Role::Temperature { .. } => sd(role).is_finite(),
1501                _ => true,
1502            });
1503        fits[patch] = Some(fit.clone());
1504        covariance[patch] = marginal;
1505        sensitivity[patch] = Some(slopes);
1506    }
1507
1508    Ok(CountsMap {
1509        measurement: map.clone(),
1510        patches,
1511        fits,
1512        failed,
1513        empty: (!empty.is_empty())
1514            .then(|| inner.last().and_then(|i| i.as_ref().map(|i| i.fit.clone())))
1515            .flatten(),
1516        densities,
1517        density_sd,
1518        temperature_k,
1519        temperature_sd_k,
1520        overdispersion,
1521        identified,
1522        normalization: values[at(Role::Normalization)],
1523        time_background: std::array::from_fn(|i| values[time_background + i]),
1524        room_background: values[room],
1525        t0_us: values[t0],
1526        flight_path_m: values[t0 + 1],
1527        alpha: [values[t0 + 2], values[t0 + 3]],
1528        beta: [values[t0 + 4], values[t0 + 5]],
1529        exponents: [values[t0 + 11], values[t0 + 12]],
1530        r: values[t0 + 6],
1531        fwhm_squared_us2: values[t0 + 7],
1532        r_high: calibration.pulse.r_high.map(|_| values[t0 + 8]),
1533        detector_tail: calibration
1534            .pulse
1535            .detector_tail
1536            .map(|_| [values[t0 + 9], values[t0 + 10]]),
1537        shared: fitted
1538            .iter()
1539            .map(|&i| {
1540                [
1541                    "normalization",
1542                    "time background C",
1543                    "time background A",
1544                    "time background τ",
1545                    "time background D",
1546                    "room background ρ",
1547                    "t0",
1548                    "flight path",
1549                ]
1550                .into_iter()
1551                .chain(PULSE_NUMBERS)
1552                .nth(i)
1553                .expect("a shared quantity")
1554            })
1555            .collect(),
1556        shared_covariance,
1557        measured_pulls,
1558        pulse_consistency,
1559        quantities: template.into_iter().map(|(_, name)| name).collect(),
1560        covariances: PatchCovariances {
1561            covariance,
1562            sensitivity,
1563            carried: propagated,
1564        },
1565        deviance: inner.iter().flatten().map(|i| i.deviance).sum(),
1566        converged,
1567        unconverged,
1568        steps,
1569    })
1570}
1571
1572type Swept = Result<Inner, PipelineError>;
1573
1574struct Inner {
1575    fit: RegionFit,
1576    deviance: f64,
1577    terms: RegionTerms,
1578}
1579
1580fn propagated(k: usize, interior: &[usize], inverse: &InformationInverse) -> FlatMatrix {
1581    let mut propagated = FlatMatrix::zeros(k, k);
1582    for (a, &i) in interior.iter().enumerate() {
1583        for (b, &j) in interior.iter().enumerate() {
1584            *propagated.get_mut(i, j) = inverse.determined.get(a, b);
1585        }
1586    }
1587    propagated
1588}
1589
1590fn marginal_entry(
1591    covariance: &FlatMatrix,
1592    sensitivity: &FlatMatrix,
1593    shared: &FlatMatrix,
1594    null: &[Vec<f64>],
1595    (i, j): (usize, usize),
1596) -> f64 {
1597    let coupled = |i: usize| moves_along(|s| sensitivity.get(i, s), null);
1598    if coupled(i) || coupled(j) {
1599        return f64::NAN;
1600    }
1601    let k = shared.nrows;
1602    covariance.get(i, j)
1603        + (0..k)
1604            .flat_map(|s| (0..k).map(move |t| (s, t)))
1605            .map(|(s, t)| sensitivity.get(i, s) * shared.get(s, t) * sensitivity.get(j, t))
1606            .sum::<f64>()
1607}
1608
1609fn moves_along(sensitivity: impl Fn(usize) -> f64, null: &[Vec<f64>]) -> bool {
1610    null.iter().any(|direction| {
1611        let terms: Vec<f64> = direction
1612            .iter()
1613            .enumerate()
1614            .map(|(s, &v)| sensitivity(s) * v)
1615            .collect();
1616        let magnitude: f64 = terms.iter().map(|t| t.abs()).sum();
1617        terms.iter().sum::<f64>().abs() > f64::EPSILON.sqrt() * magnitude
1618    })
1619}
1620
1621fn named(label: &str, error: PipelineError) -> PipelineError {
1622    match error {
1623        PipelineError::InvalidParameter(_) | PipelineError::ShapeMismatch(_) => {
1624            labelled(label, error)
1625        }
1626        other => PipelineError::InvalidParameter(format!("{label}: {other}")),
1627    }
1628}
1629
1630fn weight(fit: &RegionFit, run: usize) -> f64 {
1631    fit.overdispersion[run]
1632        .or(fit.overdispersion[0])
1633        .unwrap_or(1.0)
1634}
1635
1636fn restarted(region: &Region, previous: Option<&RegionFit>) -> Region {
1637    let mut region = region.clone();
1638    let Some(fit) = previous else {
1639        return region;
1640    };
1641    if let Some(material) = &mut region.material {
1642        for ((_, density), &at) in material.isotopes.iter_mut().zip(&fit.densities) {
1643            *density = restart(*density, at);
1644        }
1645        if let Some(t) = fit.temperature_k {
1646            material.temperature_k = restart(material.temperature_k, t);
1647        }
1648        if let Some(v) = fit.thickness_variance {
1649            material.thickness_variance = restart(material.thickness_variance, v);
1650        }
1651    }
1652    for (term, &at) in region.background.iter_mut().zip(&fit.background) {
1653        *term = restart(*term, at);
1654    }
1655    region.gamma_transmission = restart(region.gamma_transmission, fit.gamma_transmission);
1656    region.capture_gammas = restart(region.capture_gammas, fit.capture_gammas);
1657    region.in_scatter = restart(region.in_scatter, fit.in_scatter);
1658    region
1659}
1660
1661fn restart(value: Value, at: f64) -> Value {
1662    match value {
1663        Value::Fitted(_) => Value::Fitted(at),
1664        Value::Within { lower, upper, .. } => Value::Within {
1665            start: at,
1666            lower,
1667            upper,
1668        },
1669        Value::Known(_) | Value::Measured { .. } => value,
1670    }
1671}
1672
1673fn summed(
1674    map: &MapMeasurement<'_>,
1675    pixels: &[(usize, usize)],
1676) -> Result<[Vec<f64>; 2], PipelineError> {
1677    let bins = map.open_counts.dim().0;
1678    let mut sums = [vec![0.0; bins], vec![0.0; bins]];
1679    for ((run, counts), sum) in [
1680        ("open-beam", map.open_counts),
1681        ("sample", map.sample_counts),
1682    ]
1683    .into_iter()
1684    .zip(&mut sums)
1685    {
1686        for &(y, x) in pixels {
1687            for (k, (&count, total)) in counts
1688                .slice(s![.., y, x])
1689                .iter()
1690                .zip(sum.iter_mut())
1691                .enumerate()
1692            {
1693                if !whole(count) {
1694                    return Err(PipelineError::InvalidParameter(format!(
1695                        "{run} counts must be whole non-negative numbers, got {count} in bin \
1696                         {k} of pixel ({y}, {x})"
1697                    )));
1698                }
1699                *total += count;
1700            }
1701        }
1702    }
1703    Ok(sums)
1704}
1705
1706#[cfg(test)]
1707mod tests {
1708    use super::*;
1709
1710    #[test]
1711    fn a_patch_quantity_has_the_joint_fits_variance_under_an_oblique_shared_degeneracy() {
1712        let own = [1.0, 2.0, 0.0, 1.0, 3.0];
1713        let first = [1.0, 0.0, 1.0, 2.0, 1.0];
1714        for (column, resolved) in [(own, true), (first, false)] {
1715            let jacobian: Vec<[f64; 3]> = (0..5)
1716                .map(|row| [column[row], first[row], 2.0 * first[row]])
1717                .collect();
1718            let information =
1719                |a: usize, b: usize| -> f64 { jacobian.iter().map(|row| row[a] * row[b]).sum() };
1720            let joint = FlatMatrix {
1721                data: (0..9).map(|e| information(e / 3, e % 3)).collect(),
1722                nrows: 3,
1723                ncols: 3,
1724            };
1725            let diagonal: Vec<f64> = (0..3).map(|a| information(a, a)).collect();
1726            let oracle = information_inverse(&joint, &diagonal, 5).unwrap();
1727            let sensitivity = FlatMatrix {
1728                data: (1..3)
1729                    .map(|s| -information(0, s) / information(0, 0))
1730                    .collect(),
1731                nrows: 1,
1732                ncols: 2,
1733            };
1734            let profiled = FlatMatrix {
1735                data: (0..4)
1736                    .map(|e| {
1737                        let (s, t) = (1 + e / 2, 1 + e % 2);
1738                        information(s, t)
1739                            - information(s, 0) * information(0, t) / information(0, 0)
1740                    })
1741                    .collect(),
1742                nrows: 2,
1743                ncols: 2,
1744            };
1745            let shared = information_inverse(&profiled, &diagonal[1..], 5).unwrap();
1746            let own_covariance = FlatMatrix {
1747                data: vec![1.0 / information(0, 0)],
1748                nrows: 1,
1749                ncols: 1,
1750            };
1751            let variance = marginal_entry(
1752                &own_covariance,
1753                &sensitivity,
1754                &propagated(2, &[0, 1], &shared),
1755                &shared.undetermined,
1756                (0, 0),
1757            );
1758            assert_eq!(oracle.resolved[0], resolved);
1759            if resolved {
1760                let expected = oracle.determined.get(0, 0);
1761                assert!(
1762                    (variance / expected - 1.0).abs() <= 1e-9,
1763                    "{variance} vs {expected}"
1764                );
1765            } else {
1766                assert!(variance.is_nan(), "{variance}");
1767            }
1768        }
1769    }
1770
1771    #[test]
1772    fn a_quantity_moves_along_a_null_direction_unless_its_slopes_cancel_on_it() {
1773        let null = vec![vec![1.0, -2.0]];
1774        assert!(moves_along(|s| [1.0, 0.0][s], &null));
1775        assert!(!moves_along(|s| [2.0, 1.0][s], &null));
1776        assert!(!moves_along(|_| 0.0, &null));
1777    }
1778}