Skip to main content

nereids_fitting/
poisson.rs

1//! Poisson-likelihood fitting of counts.
2//!
3//! Minimizes half the Poisson deviance plus a Gaussian prior on each block
4//! `θₚ` of measured parameters,
5//!
6//! ```text
7//! D(θ) = Σᵢ [μᵢ(θ) − yᵢ + yᵢ ln(yᵢ / μᵢ(θ))] + ½ Σₚ (θₚ − mₚ)ᵀ Cₚ⁻¹ (θₚ − mₚ)
8//! ```
9//!
10//! within box bounds, by projected Levenberg–Marquardt steps in the Fisher
11//! metric, for models with an analytical Jacobian.  A prior adds `Cₚ⁻¹` to the
12//! information, as SAMMY's Bayes update `M′⁻¹ = M⁻¹ + GᵀV⁻¹G` adds the data to
13//! a prior covariance `M` (SAMMY manual, `docs/tex/fitting-procedure.tex`,
14//! eq. `bayes-eq-m-prime`).
15
16use faer::dyn_stack::{MemBuffer, MemStack};
17use faer::linalg::svd::{ComputeSvdVectors, svd, svd_scratch};
18use faer::{Mat, Par, Side};
19
20use crate::error::FittingError;
21use crate::lm::{FitModel, FlatMatrix};
22use crate::parameters::{FitParameter, ParameterSet};
23
24/// Configuration for the Poisson solvers.
25#[derive(Debug, Clone)]
26pub struct PoissonConfig {
27    /// Maximum number of steps.
28    pub max_iter: usize,
29    /// Whether to compute the covariance and error bars after convergence.
30    pub compute_covariance: bool,
31}
32
33impl Default for PoissonConfig {
34    fn default() -> Self {
35        Self {
36            max_iter: 200,
37            compute_covariance: true,
38        }
39    }
40}
41
42/// A Gaussian prior on free parameters: a measurement of them made
43/// elsewhere, with mean `m` and covariance `C = LLᵀ`.
44#[derive(Debug, Clone, PartialEq)]
45pub struct Prior {
46    pub(crate) parameters: Vec<usize>,
47    pub(crate) mean: Vec<f64>,
48    pub(crate) factor: Vec<f64>,
49}
50
51impl Prior {
52    /// A measurement `mean ± sd` of the parameter at index `parameter` in the
53    /// [`ParameterSet`]; [`poisson_fit`] refuses a mean that is not finite or
54    /// an sd that is not finite and positive.
55    pub fn measured(parameter: usize, mean: f64, sd: f64) -> Self {
56        Self {
57            parameters: vec![parameter],
58            mean: vec![mean],
59            factor: vec![sd],
60        }
61    }
62
63    /// A joint measurement of the parameters at `parameters` in the
64    /// [`ParameterSet`], with `mean` and `covariance` in that order.
65    ///
66    /// # Errors
67    /// `FittingError::LengthMismatch` if `mean` or `covariance` does not
68    /// match `parameters`; `FittingError::InvalidConfig` if `parameters` is
69    /// empty or lists a parameter twice, `mean` is not finite, or `covariance`
70    /// is not finite, not symmetric to 1e-12 of `√(Cᵢᵢ Cⱼⱼ)`, or not positive
71    /// definite with the condition number of its correlation matrix at most
72    /// 1e10; `FittingError::EvaluationFailed` if the eigendecomposition of
73    /// that matrix fails.
74    pub fn correlated(
75        parameters: &[usize],
76        mean: &[f64],
77        covariance: &FlatMatrix,
78    ) -> Result<Self, FittingError> {
79        let k = parameters.len();
80        if k == 0 {
81            return Err(FittingError::InvalidConfig(
82                "a prior needs at least one parameter".into(),
83            ));
84        }
85        for (expected, actual, field) in [
86            (k, mean.len(), "prior mean"),
87            (k, covariance.nrows, "prior covariance rows"),
88            (k, covariance.ncols, "prior covariance columns"),
89            (k * k, covariance.data.len(), "prior covariance entries"),
90        ] {
91            if actual != expected {
92                return Err(FittingError::LengthMismatch {
93                    expected,
94                    actual,
95                    field,
96                });
97            }
98        }
99        if !mean.iter().all(|m| m.is_finite())
100            || (0..k).any(|i| parameters[..i].contains(&parameters[i]))
101        {
102            return Err(FittingError::InvalidConfig(format!(
103                "a prior needs distinct parameters and a finite mean; got {parameters:?} and \
104                 {mean:?}"
105            )));
106        }
107        let sd: Vec<f64> = (0..k).map(|i| covariance.get(i, i).sqrt()).collect();
108        if !(covariance.data.iter().all(|c| c.is_finite())
109            && sd.iter().all(|&s| s > 0.0)
110            && symmetric(k, |i, j| covariance.get(i, j)))
111        {
112            return Err(FittingError::InvalidConfig(format!(
113                "a prior covariance must be finite and symmetric with a positive diagonal; \
114                 got {covariance:?}"
115            )));
116        }
117        let correlation = Mat::from_fn(k, k, |i, j| {
118            if i == j {
119                1.0
120            } else {
121                covariance.get(i, j) / sd[i] / sd[j]
122            }
123        });
124        let eigenvalues = correlation
125            .self_adjoint_eigenvalues(Side::Lower)
126            .map_err(|e| FittingError::EvaluationFailed(format!("{e:?}")))?;
127        let (smallest, largest) = (eigenvalues[0], eigenvalues[k - 1]);
128        if !(smallest > 0.0 && largest <= MAX_PRIOR_CONDITION * smallest) {
129            return Err(FittingError::InvalidConfig(format!(
130                "a prior covariance must be positive definite with a correlation condition \
131                 number within {MAX_PRIOR_CONDITION:e}; its correlation eigenvalues are \
132                 {eigenvalues:?}"
133            )));
134        }
135        Ok(Self::factored(parameters, mean, covariance))
136    }
137
138    pub(crate) fn factored(parameters: &[usize], mean: &[f64], covariance: &FlatMatrix) -> Self {
139        let k = parameters.len();
140        let sd: Vec<f64> = (0..k).map(|i| covariance.get(i, i).sqrt()).collect();
141        let correlation = |i: usize, j: usize| {
142            if i == j {
143                1.0
144            } else {
145                covariance.get(i, j) / sd[i] / sd[j]
146            }
147        };
148        let mut factor = vec![0.0; k * k];
149        for i in 0..k {
150            for j in 0..=i {
151                let dot: f64 = (0..j).map(|l| factor[i * k + l] * factor[j * k + l]).sum();
152                factor[i * k + j] = if i == j {
153                    (correlation(i, i) - dot).sqrt()
154                } else {
155                    (correlation(i, j) - dot) / factor[j * k + j]
156                };
157            }
158        }
159        for i in 0..k {
160            for j in 0..=i {
161                factor[i * k + j] *= sd[i];
162            }
163        }
164        Self {
165            parameters: parameters.to_vec(),
166            mean: mean.to_vec(),
167            factor,
168        }
169    }
170
171    pub(crate) fn covariance(&self, i: usize, j: usize) -> f64 {
172        let k = self.parameters.len();
173        (0..=i.min(j))
174            .map(|l| self.factor[i * k + l] * self.factor[j * k + l])
175            .sum()
176    }
177
178    pub(crate) fn is_valid(&self) -> bool {
179        let k = self.parameters.len();
180        self.mean.iter().all(|m| m.is_finite())
181            && self.factor.iter().all(|f| f.is_finite())
182            && (0..k).all(|j| self.factor[j * k + j] > 0.0)
183    }
184
185    pub(crate) fn whiten(&self, v: &mut [f64]) {
186        let k = self.parameters.len();
187        for i in 0..k {
188            let dot: f64 = (0..i).map(|j| self.factor[i * k + j] * v[j]).sum();
189            v[i] = (v[i] - dot) / self.factor[i * k + i];
190        }
191    }
192
193    fn residual(&self, values: &[f64]) -> Vec<f64> {
194        let mut difference: Vec<f64> = self
195            .parameters
196            .iter()
197            .zip(&self.mean)
198            .map(|(&p, m)| values[p] - m)
199            .collect();
200        self.whiten(&mut difference);
201        difference
202    }
203
204    fn inverse_factor(&self) -> Vec<f64> {
205        let k = self.parameters.len();
206        let mut inverse = vec![0.0; k * k];
207        for j in 0..k {
208            let mut column = vec![0.0; k];
209            column[j] = 1.0;
210            self.whiten(&mut column);
211            for (i, c) in column.iter().enumerate() {
212                inverse[i * k + j] = *c;
213            }
214        }
215        inverse
216    }
217}
218
219pub(crate) fn symmetric(k: usize, entry: impl Fn(usize, usize) -> f64) -> bool {
220    (0..k).all(|i| {
221        (0..i).all(|j| {
222            let scale = (entry(i, i) * entry(j, j)).abs().sqrt();
223            (entry(j, i) - entry(i, j)).abs() <= 1e-12 * scale
224        })
225    })
226}
227
228/// Result of [`poisson_fit`].
229#[derive(Debug, Clone)]
230pub struct PoissonResult {
231    /// Half the Poisson deviance of the counts at `params`, without the
232    /// priors.
233    pub deviance: f64,
234    /// Number of steps taken.
235    pub iterations: usize,
236    /// Whether the expected-information Newton decrement fell below 1e-6
237    /// inside the bounds: within about 0.0014 standard errors of a minimum
238    /// where the deviance is quadratic there.  Also true where no step
239    /// lowered the objective with `own` below 1e-6 and its trial steps tested
240    /// that; see [`poisson_fit`].
241    pub converged: bool,
242    /// The rule that ended the fit.
243    pub stop: Stop,
244    /// The free parameters, by their place among them, that the direction
245    /// holding most of the Newton decrement moves most, where the fit stopped
246    /// at its step limit or with no step; empty otherwise.
247    pub moving: Vec<usize>,
248    /// The Newton decrement where the fit last took its slopes: the decrease
249    /// the expected information predicts is left.  `None` before the first.
250    pub decrement: Option<f64>,
251    /// The free parameter with the largest Newton decrement of its own, the
252    /// others held, and that decrement `½gⱼ²/Fⱼⱼ`, where the fit last took
253    /// its slopes.
254    pub own: Option<(usize, f64)>,
255    /// The trial steps the fit rejected.
256    pub rejected: Rejected,
257    /// Final parameter values (all parameters, including fixed).
258    pub params: Vec<f64>,
259    /// Covariance of the free parameters; the rows and columns of a
260    /// parameter without an error bar are NaN.  `None` when the fit did not
261    /// converge or covariance computation is disabled.
262    pub covariance: Option<FlatMatrix>,
263    /// Standard error of each free parameter; `None` for a parameter on a
264    /// bound or with a component along a direction the data do not
265    /// determine, larger than the SVD's rounding for that parameter.  `None`
266    /// overall when `covariance` is.
267    pub uncertainties: Option<Vec<Option<f64>>>,
268    /// Whether each free parameter ended on one of its bounds.
269    pub on_bound: Vec<bool>,
270    /// Each count's leverage: the diagonal of the hat matrix of the free
271    /// parameters off their bounds.  The leverages sum to the number of
272    /// directions in those parameters the counts and priors determine, less
273    /// the share the priors take.  `None` when `covariance` is `None` or its
274    /// decomposition fails.
275    pub leverage: Option<Vec<f64>>,
276    /// The free parameters' Gaussian without their bounds; see [`Unbounded`].
277    /// `None` when `covariance` is, when the decomposition over every free
278    /// parameter fails, or when a bin predicted zero adds slope to the
279    /// gradient of a parameter on a bound.
280    pub unbounded: Option<Unbounded>,
281}
282
283/// The trial steps [`poisson_fit`] rejected, counted by the reason.
284#[derive(Debug, Clone, Default, PartialEq)]
285pub struct Rejected {
286    /// Trials the model refused, or predicted with another number of counts.
287    pub refused: usize,
288    /// Trials whose objective was not finite, as for a count predicted
289    /// negative, or zero where something was counted.
290    pub impossible: usize,
291    /// Trials whose objective was finite and not lower.
292    pub not_lower: usize,
293    /// The model's reason for the last trial it refused.
294    pub reason: Option<String>,
295    /// The decrease predicted for the last trial that tested the fit, as
296    /// taken, and the rise it gave; `None` where the trials are no test.
297    pub tested: Option<(f64, f64)>,
298    /// Where no step lowered the objective, the free parameter whose move in
299    /// that trial raised it most when made alone, with the move and the rise.
300    pub alone: Option<(usize, f64, f64)>,
301    /// Where no step lowered the objective, its value when the model is
302    /// evaluated there again, less the value the fit held.
303    pub again: Option<f64>,
304    /// The rises half the move of [`Self::alone`] and its opposite gave, unless a bound stops one.
305    pub around: Option<[f64; 2]>,
306    /// The count whose share of the objective that move changed most, its
307    /// prediction before and after, and how many predictions the move
308    /// changed by over 1e-6 of themselves.
309    pub most: Option<(usize, f64, f64, usize)>,
310}
311
312/// The rule that ended [`poisson_fit`].
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314pub enum Stop {
315    /// The Newton decrement fell below [`NEWTON_DECREMENT_TOL`], or no step
316    /// lowers the objective with every parameter's own decrement below it and
317    /// the trial steps a test of that.
318    Minimum,
319    /// The objective is not finite at the start, as when a count is predicted
320    /// negative, or zero where something was counted.
321    Start,
322    /// A slope of the predicted counts, weighted by its bin, is not finite.
323    Slope,
324    /// The singular value decomposition of the slopes failed.
325    Decomposition,
326    /// `max_iter` steps were taken.
327    StepLimit,
328    /// No step lowers the objective, with [`NEWTON_DECREMENT_TOL`] or more
329    /// left to one parameter on its own or the trial steps no test of that.
330    NoStep,
331}
332
333impl std::fmt::Display for Stop {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        f.write_str(match self {
336            Self::Minimum => "the fitter reached a minimum",
337            Self::Start => {
338                "the objective is not finite at the start, as when a count is predicted \
339                 negative, or zero where something was counted"
340            }
341            Self::Slope => "a weighted slope of the predicted counts is not finite",
342            Self::Decomposition => "the decomposition of the slopes failed",
343            Self::StepLimit => "the fitter reached its step limit",
344            Self::NoStep => "no step of the fitter lowers the objective",
345        })
346    }
347}
348
349/// The expected-information (Fisher scoring) expansion of the objective at
350/// the fit over every free parameter, bounds left out: covariance `F⁻¹`, `F`
351/// the expected information of all free parameters, and mean `θ̂ − F⁻¹g`, `g`
352/// the objective's gradient at the fit, which the convergence test makes
353/// negligible off the bounds.  Both are taken over the directions the counts
354/// and priors determine; the mean and the rows and columns of a parameter
355/// with a component along a direction they do not determine are NaN.  With
356/// none on a bound the covariance is [`PoissonResult::covariance`].
357#[derive(Debug, Clone)]
358pub struct Unbounded {
359    pub mean: Vec<f64>,
360    pub covariance: FlatMatrix,
361}
362
363/// The expected-information Newton decrement below which [`poisson_fit`]
364/// reports a minimum.
365pub const NEWTON_DECREMENT_TOL: f64 = 1e-6;
366
367const DEGENERATE_EIGENVALUE: f64 = 1e-12;
368
369const MAX_PRIOR_CONDITION: f64 = 1e-2 / DEGENERATE_EIGENVALUE;
370
371const MAX_REJECTIONS: usize = 60;
372
373const INITIAL_DAMPING: f64 = 1e-3;
374
375/// `obs·ln(obs/mean) + mean − obs`, by C. Loader's `bd0` ("Fast and
376/// accurate computation of binomial probabilities", 2000): a series in
377/// `v = (obs − mean)/(obs + mean)` when `|obs − mean| < 0.1 (obs + mean)`.
378/// For `obs ≥ 0` and `mean > 0`; 0 when both are 0, and +∞ when only `mean`
379/// is.
380pub fn half_deviance(obs: f64, mean: f64) -> f64 {
381    let half_sum = obs / 2.0 + mean / 2.0;
382    let difference = obs - mean;
383    if difference.abs() < 0.2 * half_sum {
384        let v = difference / 2.0 / half_sum;
385        let mut sum = difference * v;
386        let mut term = obs * (2.0 * v);
387        let mut j = 1.0;
388        loop {
389            term *= v * v;
390            let next = sum + term / (2.0 * j + 1.0);
391            if next == sum {
392                return sum;
393            }
394            sum = next;
395            j += 1.0;
396        }
397    } else if obs == 0.0 {
398        mean
399    } else {
400        obs * (obs.ln() - mean.ln()) + mean - obs
401    }
402}
403
404fn share(obs: f64, mean: f64) -> f64 {
405    if mean > 0.0 || (mean == 0.0 && obs == 0.0) {
406        half_deviance(obs, mean)
407    } else {
408        f64::INFINITY
409    }
410}
411
412fn deviance(y_obs: &[f64], y_model: &[f64]) -> f64 {
413    (y_obs.iter().zip(y_model))
414        .map(|(&obs, &mean)| share(obs, mean))
415        .sum()
416}
417
418fn objective(y_obs: &[f64], y_model: &[f64], priors: &[Prior], params: &ParameterSet) -> f64 {
419    let values = params.all_values();
420    deviance(y_obs, y_model)
421        + priors
422            .iter()
423            .map(|p| 0.5 * p.residual(&values).iter().map(|w| w.powi(2)).sum::<f64>())
424            .sum::<f64>()
425}
426
427struct Linearization {
428    weighted: FlatMatrix,
429    residual: Vec<f64>,
430    zero_slope: Vec<f64>,
431    gradient: Vec<f64>,
432}
433
434impl Linearization {
435    /// The decrease the expected information predicts for lowering the free
436    /// parameters by `step`.
437    fn predicted(&self, step: &[f64]) -> f64 {
438        let slope: f64 = self.gradient.iter().zip(step).map(|(g, d)| g * d).sum();
439        let change = |row: usize| -> f64 {
440            let moved = step.iter().enumerate();
441            moved.map(|(j, d)| self.weighted.get(row, j) * d).sum()
442        };
443        slope
444            - 0.5
445                * (0..self.weighted.nrows)
446                    .map(|row| change(row).powi(2))
447                    .sum::<f64>()
448    }
449}
450
451fn linearize(
452    model: &dyn FitModel,
453    params: &ParameterSet,
454    free: &[usize],
455    priors: &[Prior],
456    y_obs: &[f64],
457    y_model: &[f64],
458) -> Result<Linearization, FittingError> {
459    let mut weighted = model
460        .analytical_jacobian(&params.all_values(), free, y_model)
461        .ok_or_else(|| {
462            FittingError::InvalidConfig(
463                "poisson_fit needs a model with an analytical Jacobian".into(),
464            )
465        })?;
466    for (expected, actual, field) in [
467        (y_obs.len(), weighted.nrows, "analytical Jacobian rows"),
468        (free.len(), weighted.ncols, "analytical Jacobian columns"),
469    ] {
470        if expected != actual {
471            return Err(FittingError::LengthMismatch {
472                expected,
473                actual,
474                field,
475            });
476        }
477    }
478    let root: Vec<f64> = y_model.iter().map(|mean| mean.sqrt()).collect();
479    let mut zero_slope = vec![0.0; weighted.ncols];
480    for (i, &r) in root.iter().enumerate() {
481        for (j, z) in zero_slope.iter_mut().enumerate() {
482            let slope = weighted.get(i, j);
483            if r > 0.0 {
484                *weighted.get_mut(i, j) = slope / r;
485            } else {
486                *z += slope;
487                *weighted.get_mut(i, j) = 0.0;
488            }
489        }
490    }
491    let mut residual: Vec<f64> = y_obs
492        .iter()
493        .zip(y_model)
494        .zip(&root)
495        .map(|((&obs, &mean), &r)| if r > 0.0 { (mean - obs) / r } else { 0.0 })
496        .collect();
497    let mut row = weighted.nrows;
498    weighted.nrows += priors.iter().map(|p| p.parameters.len()).sum::<usize>();
499    weighted.data.resize(weighted.nrows * weighted.ncols, 0.0);
500    let values = params.all_values();
501    for prior in priors {
502        let k = prior.parameters.len();
503        let inverse = prior.inverse_factor();
504        for (i, w) in prior.residual(&values).into_iter().enumerate() {
505            for (j, parameter) in prior.parameters.iter().enumerate().take(i + 1) {
506                let col = free
507                    .iter()
508                    .position(|index| index == parameter)
509                    .expect("priors are on free parameters");
510                *weighted.get_mut(row, col) = inverse[i * k + j];
511            }
512            residual.push(w);
513            row += 1;
514        }
515    }
516    let gradient = zero_slope
517        .iter()
518        .enumerate()
519        .map(|(j, z)| {
520            z + (0..weighted.nrows)
521                .map(|i| weighted.get(i, j) * residual[i])
522                .sum::<f64>()
523        })
524        .collect();
525    Ok(Linearization {
526        weighted,
527        residual,
528        zero_slope,
529        gradient,
530    })
531}
532
533fn column_scale(weighted: &FlatMatrix, col: usize) -> (f64, f64) {
534    let peak = (0..weighted.nrows).fold(0.0_f64, |m, i| m.max(weighted.get(i, col).abs()));
535    let length = (0..weighted.nrows)
536        .map(|i| (weighted.get(i, col) / peak).powi(2))
537        .sum::<f64>()
538        .sqrt();
539    (peak, length)
540}
541
542struct Decomposition {
543    columns: Vec<usize>,
544    largest: Vec<f64>,
545    length: Vec<f64>,
546    rows: usize,
547    singular: Vec<f64>,
548    left: Mat<f64>,
549    right: Vec<Vec<f64>>,
550}
551
552impl Decomposition {
553    fn new(weighted: &FlatMatrix, columns: &[usize]) -> Option<Self> {
554        let (mut kept, mut largest, mut length) = (vec![], vec![], vec![]);
555        for &col in columns {
556            let (peak, norm) = column_scale(weighted, col);
557            if peak > 0.0 {
558                kept.push(col);
559                largest.push(peak);
560                length.push(norm);
561            }
562        }
563        let (rows, k) = (weighted.nrows, kept.len());
564        let scaled = Mat::from_fn(rows, k, |row, i| {
565            weighted.get(row, kept[i]) / largest[i] / length[i]
566        });
567        let mut values = Mat::<f64>::zeros(rows.min(k), rows.min(k));
568        let mut left = Mat::<f64>::zeros(rows, rows.min(k));
569        let mut v = Mat::<f64>::zeros(k, k);
570        let params = Default::default();
571        svd(
572            scaled.as_ref(),
573            values.diagonal_mut(),
574            Some(left.as_mut()),
575            Some(v.as_mut()),
576            Par::Seq,
577            MemStack::new(&mut MemBuffer::new(svd_scratch::<f64>(
578                rows,
579                k,
580                ComputeSvdVectors::Thin,
581                ComputeSvdVectors::Full,
582                Par::Seq,
583                params,
584            ))),
585            params,
586        )
587        .ok()?;
588        Some(Self {
589            columns: kept,
590            largest,
591            length,
592            rows,
593            singular: (0..k)
594                .map(|j| if j < rows { values[(j, j)] } else { 0.0 })
595                .collect(),
596            left,
597            right: (0..k)
598                .map(|j| (0..k).map(|i| v[(i, j)]).collect())
599                .collect(),
600        })
601    }
602
603    fn unscale(&self, i: usize, value: f64) -> f64 {
604        value / self.length[i] / self.largest[i]
605    }
606
607    fn spanned(&self) -> impl Iterator<Item = usize> + '_ {
608        let largest = self.singular.iter().fold(0.0_f64, |m, &s| m.max(s));
609        let rank_floor = f64::EPSILON * self.rows.max(self.singular.len()) as f64 * largest;
610        (0..self.singular.len()).filter(move |&k| self.singular[k] > rank_floor)
611    }
612
613    fn along(&self, k: usize, linear: &Linearization) -> f64 {
614        let zero_part: f64 = self
615            .columns
616            .iter()
617            .enumerate()
618            .map(|(i, &col)| self.right[k][i] * self.unscale(i, linear.zero_slope[col]))
619            .sum();
620        let residual_part: f64 = (0..self.rows)
621            .map(|row| self.left[(row, k)] * linear.residual[row])
622            .sum();
623        residual_part + zero_part / self.singular[k]
624    }
625
626    fn newton_decrement(&self, linear: &Linearization) -> f64 {
627        0.5 * self
628            .spanned()
629            .map(|k| self.along(k, linear).powi(2))
630            .sum::<f64>()
631    }
632
633    /// The column whose parameter has the largest Newton decrement with the
634    /// others held, and that decrement `½gⱼ²/Fⱼⱼ`.
635    fn own(&self, linear: &Linearization) -> Option<(usize, f64)> {
636        let columns = self.columns.iter().enumerate();
637        columns
638            .map(|(i, &col)| (col, 0.5 * self.unscale(i, linear.gradient[col]).powi(2)))
639            .max_by(|a, b| a.1.total_cmp(&b.1))
640    }
641
642    fn moving(&self, linear: &Linearization) -> Vec<usize> {
643        let share = |k: &usize| self.along(*k, linear).abs();
644        let Some(k) = self.spanned().max_by(|a, b| share(a).total_cmp(&share(b))) else {
645            return Vec::new();
646        };
647        let weights = &self.right[k];
648        let peak = weights.iter().fold(0.0_f64, |m, w| m.max(w.abs()));
649        let most = self.columns.iter().zip(weights);
650        most.filter(|(_, w)| w.abs() >= 0.5 * peak)
651            .map(|(&col, _)| col)
652            .collect()
653    }
654
655    fn is_determined(&self, k: usize) -> bool {
656        self.singular[k].powi(2) >= DEGENERATE_EIGENVALUE
657    }
658
659    fn determined(&self) -> impl Iterator<Item = usize> + '_ {
660        (0..self.singular.len()).filter(|&k| self.is_determined(k))
661    }
662
663    fn step(
664        &self,
665        directions: impl Iterator<Item = usize>,
666        linear: &Linearization,
667        n_free: usize,
668        damping: f64,
669    ) -> Vec<f64> {
670        let mut direction = vec![0.0; n_free];
671        for k in directions {
672            let s = self.singular[k];
673            let coefficient = self.along(k, linear) * s / (s * s + damping);
674            for (i, &col) in self.columns.iter().enumerate() {
675                direction[col] += self.unscale(i, self.right[k][i] * coefficient);
676            }
677        }
678        direction
679    }
680
681    /// The length of the step at `damping` in the scaled coordinates, and
682    /// the slope of its square in `damping`, negated and halved.
683    fn reach(&self, linear: &Linearization, damping: f64) -> [f64; 2] {
684        let (mut square, mut slope) = (0.0, 0.0);
685        for k in self.spanned() {
686            let s = self.singular[k];
687            let coefficient = self.along(k, linear) * s / (s * s + damping);
688            square += coefficient.powi(2);
689            slope += coefficient.powi(2) / (s * s + damping);
690        }
691        [square.sqrt(), slope]
692    }
693
694    /// The damping whose step is `radius` long, 0 where the undamped step is
695    /// shorter (J. J. Moré, Lect. Notes Math. 630, 105–116, 1978, §5).
696    fn damping_within(&self, linear: &Linearization, radius: f64) -> f64 {
697        let mut damping = 0.0;
698        for _ in 0..100 {
699            let [length, slope] = self.reach(linear, damping);
700            let more = length.powi(2) / slope * (length - radius) / radius;
701            if length <= 1.1 * radius || !more.is_finite() {
702                break;
703            }
704            damping += more;
705        }
706        damping
707    }
708
709    fn leverage(&self, counts: usize) -> Vec<f64> {
710        (0..counts)
711            .map(|row| self.spanned().map(|k| self.left[(row, k)].powi(2)).sum())
712            .collect()
713    }
714
715    fn error_bars(&self, n_free: usize) -> (FlatMatrix, Vec<Option<f64>>) {
716        let n = self.columns.len();
717        let determined: Vec<bool> = (0..n).map(|k| self.is_determined(k)).collect();
718        let largest = self.singular.iter().fold(0.0_f64, |m, &s| m.max(s));
719        let resolved: Vec<bool> = (0..n)
720            .map(|i| {
721                let sensitivity: f64 = (0..n)
722                    .filter(|&k| determined[k])
723                    .map(|k| self.right[k][i].abs() / self.singular[k])
724                    .sum();
725                let rounding = f64::EPSILON * self.rows.max(n) as f64 * largest * sensitivity;
726                (0..n)
727                    .filter(|&k| !determined[k])
728                    .map(|k| self.right[k][i].powi(2))
729                    .sum::<f64>()
730                    <= rounding.powi(2)
731            })
732            .collect();
733        let variance = |i: usize, j: usize| -> f64 {
734            (0..n)
735                .filter(|&k| determined[k])
736                .map(|k| self.right[k][i] * self.right[k][j] / self.singular[k].powi(2))
737                .sum()
738        };
739        let (mut covariance, mut errors) = withheld(n_free);
740        for i in (0..n).filter(|&i| resolved[i]) {
741            for j in (0..n).filter(|&j| resolved[j]) {
742                *covariance.get_mut(self.columns[i], self.columns[j]) =
743                    self.unscale(j, self.unscale(i, variance(i, j)));
744            }
745            errors[self.columns[i]] = Some(self.unscale(i, variance(i, i).sqrt()));
746        }
747        (covariance, errors)
748    }
749}
750
751/// The inverses of the expected information `information` of `rows` counts,
752/// split as [`poisson_fit`] splits its directions into those its steps take
753/// and those its covariance keeps.  In the information scaled to a unit
754/// `diagonal`, its own or, for an information with other parameters profiled
755/// out, the one it had before, `spanned` keeps every eigen-direction whose
756/// eigenvalue is above the eigendecomposition's rounding, `ε·max(rows, k)`
757/// times the largest, `k` the number of parameters with information, and `determined` keeps those of them whose eigenvalue is
758/// also at least 1e-12; where that rounding exceeds 1e-12, it is the cutoff
759/// of both.  A parameter with no information has a zero row and
760/// column in both.  `resolved[i]` is whether parameter `i` has information
761/// and, beyond rounding, no component along a direction `determined` leaves
762/// out; `undetermined` holds those directions, in the parameters' units.
763#[derive(Debug, Clone)]
764pub struct InformationInverse {
765    pub spanned: FlatMatrix,
766    pub determined: FlatMatrix,
767    pub resolved: Vec<bool>,
768    pub undetermined: Vec<Vec<f64>>,
769}
770
771/// [`InformationInverse`] of `information`, the expected information of
772/// `rows` counts, scaled to `diagonal`.
773///
774/// # Errors
775/// [`FittingError::InvalidConfig`] if `information` is not square, does not
776/// hold its entries, has an entry that is not finite, or is not symmetric to
777/// 1e-12 of `√(dᵢdⱼ)`, or if `diagonal` is not one finite non-negative entry
778/// per row, zero only on a row of zeros; [`FittingError::EvaluationFailed`] if its eigendecomposition
779/// fails.
780pub fn information_inverse(
781    information: &FlatMatrix,
782    diagonal: &[f64],
783    rows: usize,
784) -> Result<InformationInverse, FittingError> {
785    let n = information.nrows;
786    if information.ncols != n
787        || information.data.len() != n * n
788        || !information.data.iter().all(|x| x.is_finite())
789        || diagonal.len() != n
790        || !diagonal.iter().all(|d| d.is_finite() && *d >= 0.0)
791        || (0..n).any(|i| diagonal[i] == 0.0 && (0..n).any(|j| information.get(i, j) != 0.0))
792        || !(0..n).all(|i| {
793            (0..i).all(|j| {
794                (information.get(i, j) - information.get(j, i)).abs()
795                    <= 1e-12 * (diagonal[i] * diagonal[j]).sqrt()
796            })
797        })
798    {
799        return Err(FittingError::InvalidConfig(format!(
800            "an expected information is a finite symmetric square matrix with a finite \
801             non-negative diagonal to scale it by; got {} by {} with {} entries and {} \
802             diagonal entries",
803            information.nrows,
804            information.ncols,
805            information.data.len(),
806            diagonal.len()
807        )));
808    }
809    let kept: Vec<usize> = (0..n).filter(|&i| diagonal[i] > 0.0).collect();
810    let k = kept.len();
811    if k == 0 {
812        return Ok(InformationInverse {
813            spanned: FlatMatrix::zeros(n, n),
814            determined: FlatMatrix::zeros(n, n),
815            resolved: vec![false; n],
816            undetermined: Vec::new(),
817        });
818    }
819    let scale: Vec<f64> = kept.iter().map(|&i| diagonal[i].sqrt()).collect();
820    let eigen = Mat::from_fn(k, k, |a, b| {
821        information.get(kept[a], kept[b]) / (scale[a] * scale[b])
822    })
823    .self_adjoint_eigen(Side::Lower)
824    .map_err(|e| FittingError::EvaluationFailed(format!("{e:?}")))?;
825    let (values, vectors) = (eigen.S().column_vector(), eigen.U());
826    let singular: Vec<f64> = (0..k).map(|d| values[d].max(0.0).sqrt()).collect();
827    let largest = singular.iter().fold(0.0_f64, |m, &s| m.max(s));
828    let rank_floor = f64::EPSILON * rows.max(k) as f64 * largest.powi(2);
829    let inverse = |keep: &dyn Fn(usize) -> bool| {
830        let mut inverse = FlatMatrix::zeros(n, n);
831        for a in 0..k {
832            for b in 0..k {
833                *inverse.get_mut(kept[a], kept[b]) = (0..k)
834                    .filter(|&d| keep(d))
835                    .map(|d| vectors[(a, d)] * vectors[(b, d)] / values[d])
836                    .sum::<f64>()
837                    / (scale[a] * scale[b]);
838            }
839        }
840        inverse
841    };
842    let is_spanned = |d: usize| values[d] > rank_floor;
843    let is_determined = |d: usize| is_spanned(d) && values[d] >= DEGENERATE_EIGENVALUE;
844    let mut resolved = vec![false; n];
845    for a in 0..k {
846        let sensitivity: f64 = (0..k)
847            .filter(|&d| is_determined(d))
848            .map(|d| vectors[(a, d)].abs() / singular[d])
849            .sum();
850        let rounding = f64::EPSILON * rows.max(k) as f64 * largest * sensitivity;
851        resolved[kept[a]] = (0..k)
852            .filter(|&d| !is_determined(d))
853            .map(|d| vectors[(a, d)].powi(2))
854            .sum::<f64>()
855            <= rounding.powi(2);
856    }
857    let undetermined = (0..k)
858        .filter(|&d| !is_determined(d))
859        .map(|d| {
860            let mut direction = vec![0.0; n];
861            for a in 0..k {
862                direction[kept[a]] = vectors[(a, d)] / scale[a];
863            }
864            direction
865        })
866        .collect();
867    Ok(InformationInverse {
868        spanned: inverse(&is_spanned),
869        determined: inverse(&is_determined),
870        resolved,
871        undetermined,
872    })
873}
874
875fn withheld(n_free: usize) -> (FlatMatrix, Vec<Option<f64>>) {
876    let mut covariance = FlatMatrix::zeros(n_free, n_free);
877    covariance.data.fill(f64::NAN);
878    (covariance, vec![None; n_free])
879}
880
881fn on_bound(param: &FitParameter) -> bool {
882    param.value == param.lower || param.value == param.upper
883}
884
885fn held_by_bound(param: &FitParameter, gradient: f64) -> bool {
886    (param.value == param.lower && gradient > 0.0) || (param.value == param.upper && gradient < 0.0)
887}
888
889/// Fit `params` to the counts `y_obs` by minimizing half the Poisson
890/// deviance plus `½(θₚ − mₚ)ᵀCₚ⁻¹(θₚ − mₚ)` for each of the `priors`, within
891/// the parameter bounds.
892///
893/// The model must provide an analytical Jacobian at every point the fit
894/// visits.  A trial predicting a negative count, or zero where something was
895/// counted, is rejected; a bin predicted zero with no counts adds its slope
896/// to the gradient and nothing to the information.  Each step is the
897/// Levenberg–Marquardt step `(F + λI)⁻¹g` in coordinates scaled to unit
898/// Fisher information, projected onto the box, with `λ` 1e-3 at first and
899/// then that which keeps the step within a trust radius (J. J. Moré, Lect.
900/// Notes Math. 630, 105–116, 1978): twice the length of a step that
901/// delivers over three quarters of the decrease predicted for it as taken if
902/// that is longer, a quarter of the length of one that delivers under a
903/// quarter or does not lower the objective, which is then retried.  A free
904/// parameter on its bound whose gradient points out of the box is held there
905/// for the step and left out of the convergence test.
906///
907/// The fit has converged when the Newton decrement `½ gᵀF⁺g` over the
908/// parameters not held by a bound (on it, gradient pointing out),
909/// `F = Jᵀ diag(1/μ) J + Σₚ Cₚ⁻¹` the expected information, each `Cₚ⁻¹` on
910/// its prior's parameters, is below 1e-6: the
911/// quadratic model built from `F` predicts less than 1e-6 of further
912/// decrease.  Where the deviance is quadratic near the minimum this puts the
913/// fit within about 0.0014 standard errors of it, and within 0.01 where the
914/// expected information overstates the curvature, as at one count per bin.
915/// The fit has also converged when none of its trial steps lowers the
916/// objective and the decrement of each parameter with the others held,
917/// `½gⱼ²/Fⱼⱼ`, is below 1e-6, provided those steps tested that since the fit
918/// last moved beyond the rounding of the objective and of the predicted
919/// counts, `ε·(n·|objective| + Σ|yᵢ − μᵢ|)` over `n` counts: the last
920/// rejected one predicted to lower the objective beyond that rounding was
921/// evaluated and, as taken after rounding and the bounds, still predicted so,
922/// and none rejected after it was refused or impossible.  Along
923/// a weakly determined direction a slope error, or a curvature the expected
924/// information leaves out, can keep `½ gᵀF⁺g` large where no decrease is
925/// left.
926/// Where it is not quadratic — weakly determined parameters on a curved or
927/// flat likelihood ridge, a minimum at infinity, or a parameter that adds
928/// counts to a bin predicted near zero — the fit can stop short of the
929/// minimum, or at another local minimum, and the error bars are not standard
930/// errors.  A minimum where a bin's prediction reaches zero inside the box is
931/// reported unconverged.
932///
933/// It stops unconverged when no step lowers the objective otherwise, when the
934/// Jacobian
935/// weighted by its bins is not finite or its decomposition fails, when the
936/// objective is not finite at the start, as for a negative count or zero where
937/// something was counted, or after `config.max_iter` steps;
938/// [`PoissonResult::stop`] says which.  A trial whose
939/// prediction has a different length from `y_obs` is rejected.
940///
941/// # Errors
942/// `FittingError::EmptyData` if `y_obs` is empty;
943/// `FittingError::InvalidConfig` if an observation is negative or not
944/// finite, a parameter value is not finite, a free parameter's bounds are
945/// inverted, NaN or admit no finite value, a prior is not on free
946/// parameters, two priors are on one parameter, a prior's mean is not finite
947/// or a measured sd not finite and positive, or the model returns no
948/// analytical Jacobian;
949/// `FittingError::LengthMismatch` if the prediction or the Jacobian does not
950/// match `y_obs` and the free parameters; the model's error if it fails at
951/// the start.
952pub fn poisson_fit(
953    model: &dyn FitModel,
954    y_obs: &[f64],
955    priors: &[Prior],
956    params: &mut ParameterSet,
957    config: &PoissonConfig,
958) -> Result<PoissonResult, FittingError> {
959    if let Some((bin, &obs)) = y_obs
960        .iter()
961        .enumerate()
962        .find(|(_, obs)| !(obs.is_finite() && **obs >= 0.0))
963    {
964        return Err(FittingError::InvalidConfig(format!(
965            "observed counts must be finite and non-negative, got {obs} in bin {bin}"
966        )));
967    }
968    if y_obs.is_empty() {
969        return Err(FittingError::EmptyData);
970    }
971    if let Some(p) = params.params.iter().find(|p| {
972        !p.value.is_finite()
973            || (!p.fixed
974                && (p.lower.is_nan()
975                    || p.upper.is_nan()
976                    || p.lower > p.upper
977                    || p.lower == f64::INFINITY
978                    || p.upper == f64::NEG_INFINITY))
979    }) {
980        return Err(FittingError::InvalidConfig(format!(
981            "parameter {} = {} with bounds [{}, {}]",
982            p.name, p.value, p.lower, p.upper
983        )));
984    }
985    let covered: Vec<usize> = priors.iter().flat_map(|p| p.parameters.clone()).collect();
986    if let Some((i, prior)) = priors.iter().enumerate().find(|(_, p)| {
987        p.parameters.iter().any(|&parameter| {
988            params.params.get(parameter).is_none_or(|param| param.fixed)
989                || covered.iter().filter(|&&c| c == parameter).count() > 1
990        }) || !p.is_valid()
991    }) {
992        return Err(FittingError::InvalidConfig(format!(
993            "prior {i} must be on free parameters without another prior, with a finite mean \
994             and finite positive sds; got parameters {:?} with mean {:?}",
995            prior.parameters, prior.mean
996        )));
997    }
998    params.set_free_values(&params.free_values());
999    let mut y_model = model.evaluate(&params.all_values())?;
1000    if y_model.len() != y_obs.len() {
1001        return Err(FittingError::LengthMismatch {
1002            expected: y_model.len(),
1003            actual: y_obs.len(),
1004            field: "y_obs",
1005        });
1006    }
1007    let free = params.free_indices();
1008    let mut value = objective(y_obs, &y_model, priors, params);
1009    let mut iterations = 0;
1010    let mut at_minimum = None;
1011    let mut stop = Stop::Start;
1012    let mut moving = Vec::new();
1013    let mut decrement = None;
1014    let mut own = None;
1015    let mut rejected = Rejected::default();
1016    let mut radius: Option<f64> = None;
1017    let mut last = None;
1018    // The objective where `rejected.tested` was recorded.
1019    let mut tested_at = value;
1020    while value.is_finite() {
1021        let linear = linearize(model, params, &free, priors, y_obs, &y_model)?;
1022        if !linear
1023            .weighted
1024            .data
1025            .iter()
1026            .chain(&linear.zero_slope)
1027            .all(|v| v.is_finite())
1028        {
1029            stop = Stop::Slope;
1030            break;
1031        }
1032        let movable: Vec<usize> = (0..free.len())
1033            .filter(|&j| !held_by_bound(&params.params[free[j]], linear.gradient[j]))
1034            .collect();
1035        let Some(decomposition) = Decomposition::new(&linear.weighted, &movable) else {
1036            stop = Stop::Decomposition;
1037            break;
1038        };
1039        let left = decomposition.newton_decrement(&linear);
1040        let alone = decomposition.own(&linear);
1041        decrement = Some(left);
1042        own = alone;
1043        if left < NEWTON_DECREMENT_TOL {
1044            at_minimum = Some(linear);
1045            stop = Stop::Minimum;
1046            break;
1047        }
1048        if iterations == config.max_iter {
1049            stop = Stop::StepLimit;
1050            moving = decomposition.moving(&linear);
1051            break;
1052        }
1053        let start = params.free_values();
1054        let misfit: f64 = y_obs.iter().zip(&y_model).map(|(y, m)| (y - m).abs()).sum();
1055        let resolved = f64::EPSILON * (y_obs.len() as f64 * value.abs() + misfit);
1056        let mut accepted = None;
1057        for _ in 0..MAX_REJECTIONS {
1058            let damping = radius.map_or(INITIAL_DAMPING, |radius| {
1059                decomposition.damping_within(&linear, radius)
1060            });
1061            let [length, _] = decomposition.reach(&linear, damping);
1062            let direction =
1063                decomposition.step(decomposition.spanned(), &linear, free.len(), damping);
1064            let unprojected: Vec<f64> = start.iter().zip(&direction).map(|(x, d)| x - d).collect();
1065            params.set_free_values(&unprojected);
1066            let taken: Vec<f64> = (start.iter().zip(params.free_values()))
1067                .map(|(x, trial)| x - trial)
1068                .collect();
1069            let rise = match model.evaluate(&params.all_values()) {
1070                Ok(trial_model) if trial_model.len() == y_obs.len() => {
1071                    let trial_value = objective(y_obs, &trial_model, priors, params);
1072                    if trial_value < value {
1073                        let gain = (value - trial_value) / linear.predicted(&taken);
1074                        radius = Some(if gain > 0.75 {
1075                            radius.map_or(2.0 * length, |radius| radius.max(2.0 * length))
1076                        } else if gain >= 0.25 {
1077                            radius.unwrap_or(length)
1078                        } else {
1079                            length / 4.0
1080                        });
1081                        if tested_at - trial_value > resolved {
1082                            (rejected.tested, last) = (None, None);
1083                        }
1084                        accepted = Some((trial_model, trial_value));
1085                        break;
1086                    }
1087                    match trial_value.is_finite() {
1088                        true => rejected.not_lower += 1,
1089                        false => rejected.impossible += 1,
1090                    }
1091                    trial_value.is_finite().then_some(trial_value - value)
1092                }
1093                Ok(_) => {
1094                    rejected.refused += 1;
1095                    None
1096                }
1097                Err(reason) => {
1098                    rejected.refused += 1;
1099                    rejected.reason = Some(reason.to_string());
1100                    None
1101                }
1102            };
1103            if rise.is_none() || linear.predicted(&direction) > resolved {
1104                let as_taken = linear.predicted(&taken);
1105                rejected.tested = rise
1106                    .filter(|_| as_taken > resolved)
1107                    .map(|rise| (as_taken, rise));
1108                last = rejected.tested.map(|_| taken);
1109                tested_at = value;
1110            }
1111            params.set_free_values(&start);
1112            radius = Some(length / 4.0);
1113        }
1114        let Some((trial_model, trial_value)) = accepted else {
1115            let alone = alone.map_or(0.0, |(_, left)| left);
1116            if rejected.tested.is_some() && alone < NEWTON_DECREMENT_TOL {
1117                at_minimum = Some(linear);
1118                stop = Stop::Minimum;
1119            } else {
1120                stop = Stop::NoStep;
1121                moving = decomposition.moving(&linear);
1122                let moves = last.iter().flatten().enumerate();
1123                let alone = moves
1124                    .filter(|(_, step)| **step != 0.0)
1125                    .filter_map(|(j, step)| {
1126                        let mut moved = start.clone();
1127                        moved[j] -= step;
1128                        params.set_free_values(&moved);
1129                        let counts = model.evaluate(&params.all_values()).ok()?;
1130                        (counts.len() == y_obs.len())
1131                            .then(|| (j, -step, objective(y_obs, &counts, priors, params) - value))
1132                    });
1133                rejected.alone = alone.max_by(|a, b| a.2.total_cmp(&b.2));
1134                if let Some((j, by, _)) = rejected.alone {
1135                    let mut moved_by = |by: f64| {
1136                        let mut moved = start.clone();
1137                        moved[j] += by;
1138                        params.set_free_values(&moved);
1139                        if params.params[free[j]].value != moved[j] {
1140                            return None;
1141                        }
1142                        let counts = model.evaluate(&params.all_values()).ok()?;
1143                        (counts.len() == y_obs.len())
1144                            .then(|| (objective(y_obs, &counts, priors, params) - value, counts))
1145                    };
1146                    rejected.around = (moved_by(0.5 * by).zip(moved_by(-by)))
1147                        .map(|(half, opposite)| [half.0, opposite.0]);
1148                    rejected.most = moved_by(by).and_then(|(_, counts)| {
1149                        let changed = (y_model.iter().zip(&counts))
1150                            .filter(|(before, after)| {
1151                                (*after - *before).abs() > 1e-6 * before.abs()
1152                            })
1153                            .count();
1154                        let change = |k: usize| {
1155                            (share(y_obs[k], counts[k]) - share(y_obs[k], y_model[k])).abs()
1156                        };
1157                        (0..counts.len())
1158                            .max_by(|&a, &b| change(a).total_cmp(&change(b)))
1159                            .map(|k| (k, y_model[k], counts[k], changed))
1160                    });
1161                }
1162                params.set_free_values(&start);
1163                let again = model.evaluate(&params.all_values()).ok();
1164                rejected.again = again
1165                    .filter(|counts| counts.len() == y_obs.len())
1166                    .map(|counts| objective(y_obs, &counts, priors, params) - value);
1167            }
1168            break;
1169        };
1170        y_model = trial_model;
1171        value = trial_value;
1172        iterations += 1;
1173    }
1174
1175    let bounded: Vec<bool> = free
1176        .iter()
1177        .map(|&idx| on_bound(&params.params[idx]))
1178        .collect();
1179    let (covariance, uncertainties, leverage, unbounded) = match &at_minimum {
1180        Some(linear) if config.compute_covariance => {
1181            let interior: Vec<usize> = (0..free.len()).filter(|&j| !bounded[j]).collect();
1182            let decomposition = Decomposition::new(&linear.weighted, &interior);
1183            let (covariance, errors) = decomposition.as_ref().map_or_else(
1184                || withheld(free.len()),
1185                |decomposition| decomposition.error_bars(free.len()),
1186            );
1187            let leverage = decomposition
1188                .as_ref()
1189                .map(|decomposition| decomposition.leverage(y_obs.len()));
1190            let unbounded = unbounded(linear, &params.free_values(), &bounded);
1191            (Some(covariance), Some(errors), leverage, unbounded)
1192        }
1193        _ => (None, None, None, None),
1194    };
1195    Ok(PoissonResult {
1196        deviance: deviance(y_obs, &y_model),
1197        iterations,
1198        converged: at_minimum.is_some(),
1199        stop,
1200        moving,
1201        decrement,
1202        own,
1203        rejected,
1204        params: params.all_values(),
1205        covariance,
1206        uncertainties,
1207        on_bound: bounded,
1208        leverage,
1209        unbounded,
1210    })
1211}
1212
1213fn unbounded(linear: &Linearization, fitted: &[f64], bounded: &[bool]) -> Option<Unbounded> {
1214    if (0..fitted.len()).any(|j| bounded[j] && linear.zero_slope[j] != 0.0) {
1215        return None;
1216    }
1217    let columns: Vec<usize> = (0..fitted.len()).collect();
1218    let decomposition = Decomposition::new(&linear.weighted, &columns)?;
1219    let step = decomposition.step(decomposition.determined(), linear, fitted.len(), 0.0);
1220    let covariance = decomposition.error_bars(fitted.len()).0;
1221    let mean = (0..fitted.len())
1222        .map(|i| {
1223            if covariance.get(i, i).is_nan() {
1224                f64::NAN
1225            } else {
1226                fitted[i] - step[i]
1227            }
1228        })
1229        .collect();
1230    Some(Unbounded { mean, covariance })
1231}
1232
1233#[cfg(test)]
1234mod tests {
1235    use super::*;
1236
1237    /// Simple model: y = a * exp(-b * x)
1238    /// This mimics transmission: counts = flux * exp(-density * sigma)
1239    struct ExponentialModel {
1240        x: Vec<f64>,
1241        flux: Vec<f64>,
1242    }
1243
1244    impl FitModel for ExponentialModel {
1245        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
1246            let b = params[0]; // "density"
1247            Ok(self
1248                .x
1249                .iter()
1250                .zip(self.flux.iter())
1251                .map(|(&xi, &fi)| fi * (-b * xi).exp())
1252                .collect())
1253        }
1254    }
1255
1256    struct Decay {
1257        t: Vec<f64>,
1258        jacobian_factor: f64,
1259    }
1260
1261    impl FitModel for Decay {
1262        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
1263            Ok(self
1264                .t
1265                .iter()
1266                .map(|&t| params[0] * (-params[1] * t).exp())
1267                .collect())
1268        }
1269
1270        fn analytical_jacobian(
1271            &self,
1272            params: &[f64],
1273            free_param_indices: &[usize],
1274            _y_current: &[f64],
1275        ) -> Option<FlatMatrix> {
1276            let mut jacobian = FlatMatrix::zeros(self.t.len(), free_param_indices.len());
1277            for (row, &t) in self.t.iter().enumerate() {
1278                let e = (-params[1] * t).exp();
1279                for (col, &index) in free_param_indices.iter().enumerate() {
1280                    let slope = [e, -params[0] * t * e][index];
1281                    *jacobian.get_mut(row, col) = slope * self.jacobian_factor;
1282                }
1283            }
1284            Some(jacobian)
1285        }
1286    }
1287
1288    /// Counts `1e6·(a + b·(1 + tilt·x))`: only the tilt tells `a` from `b`.
1289    /// The slopes in `b` are off by `error·(x² − ⅓)` of their size, and a
1290    /// last bin counts `a − floor` under a `floor`.
1291    struct Tilted {
1292        x: Vec<f64>,
1293        tilt: f64,
1294        error: f64,
1295        floor: Option<f64>,
1296    }
1297
1298    impl FitModel for Tilted {
1299        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
1300            let counts = |x: &f64| 1e6 * (params[0] + params[1] * (1.0 + self.tilt * x));
1301            let last = self.floor.map(|floor| params[0] - floor);
1302            Ok(self.x.iter().map(counts).chain(last).collect())
1303        }
1304
1305        fn analytical_jacobian(
1306            &self,
1307            _params: &[f64],
1308            free: &[usize],
1309            y_current: &[f64],
1310        ) -> Option<FlatMatrix> {
1311            let mut jacobian = FlatMatrix::zeros(y_current.len(), free.len());
1312            for (col, &index) in free.iter().enumerate() {
1313                for (row, x) in self.x.iter().enumerate() {
1314                    let off = 1.0 + self.error * (x * x - 1.0 / 3.0);
1315                    *jacobian.get_mut(row, col) = [1e6, 1e6 * (1.0 + self.tilt * x) * off][index];
1316                }
1317                if self.floor.is_some() {
1318                    *jacobian.get_mut(self.x.len(), col) = [1.0, 0.0][index];
1319                }
1320            }
1321            Some(jacobian)
1322        }
1323    }
1324
1325    /// Two bins of `1e6 + 100(u + v) + 25((u − v)/2)² ± 0.01(u − v)`.
1326    struct Valley;
1327
1328    impl FitModel for Valley {
1329        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
1330            let (sum, half) = (params[0] + params[1], 0.5 * (params[0] - params[1]));
1331            let level = 1e6 + 100.0 * sum + 25.0 * half * half;
1332            Ok(vec![level + 0.02 * half, level - 0.02 * half])
1333        }
1334
1335        fn analytical_jacobian(
1336            &self,
1337            params: &[f64],
1338            free: &[usize],
1339            _y_current: &[f64],
1340        ) -> Option<FlatMatrix> {
1341            let half = 0.5 * (params[0] - params[1]);
1342            let mut jacobian = FlatMatrix::zeros(2, free.len());
1343            for (col, &index) in free.iter().enumerate() {
1344                for (row, tilt) in [0.01, -0.01].into_iter().enumerate() {
1345                    *jacobian.get_mut(row, col) = 100.0 + [1.0, -1.0][index] * (25.0 * half + tilt);
1346                }
1347            }
1348            Some(jacobian)
1349        }
1350    }
1351
1352    /// `model` with its parameters counted from `origin`.
1353    struct Offset<M> {
1354        model: M,
1355        origin: f64,
1356    }
1357
1358    impl<M: FitModel> FitModel for Offset<M> {
1359        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
1360            let from: Vec<f64> = params.iter().map(|p| p - self.origin).collect();
1361            self.model.evaluate(&from)
1362        }
1363
1364        fn analytical_jacobian(
1365            &self,
1366            params: &[f64],
1367            free: &[usize],
1368            y_current: &[f64],
1369        ) -> Option<FlatMatrix> {
1370            let from: Vec<f64> = params.iter().map(|p| p - self.origin).collect();
1371            self.model.analytical_jacobian(&from, free, y_current)
1372        }
1373    }
1374
1375    #[test]
1376    fn a_fit_no_step_lowers_converges_with_no_decrease_left_to_a_parameter_on_its_own() {
1377        let x: Vec<f64> = (0..200).map(|i| f64::from(i) / 99.5 - 1.0).collect();
1378        let fit = |tilt: f64, error: f64, power: i32, start: [f64; 2], floor: Option<f64>| {
1379            let observed: Vec<f64> = (x.iter())
1380                .map(|x| 2e6 * (1.0 + 0.01 * x.powi(power)))
1381                .chain(floor.map(|_| 0.0))
1382                .collect();
1383            let mut params = ParameterSet::new(vec![
1384                FitParameter::unbounded("a", start[0]),
1385                FitParameter::unbounded("b", start[1]),
1386            ]);
1387            let model = Tilted {
1388                x: x.clone(),
1389                tilt,
1390                error,
1391                floor,
1392            };
1393            poisson_fit(
1394                &model,
1395                &observed,
1396                &[],
1397                &mut params,
1398                &PoissonConfig::default(),
1399            )
1400            .unwrap()
1401        };
1402        let report = |fit: &PoissonResult| {
1403            format!(
1404                "{:?} {:?} {:?} {:?} {:?}",
1405                fit.stop, fit.decrement, fit.own, fit.rejected, fit.params
1406            )
1407        };
1408        // The counts curve as x², which leaves a misfit, and are fitted best by b = 0.
1409        let level = 2.0 + 0.02 * x.iter().map(|x| x * x).sum::<f64>() / 200.0;
1410        let weak = fit(1e-4, 1e-7, 2, [level, 0.0], None);
1411        assert_eq!(weak.stop, Stop::Minimum, "{}", report(&weak));
1412        assert!(
1413            weak.decrement.unwrap() > NEWTON_DECREMENT_TOL && weak.params[1].abs() < 1e-6,
1414            "{}",
1415            report(&weak)
1416        );
1417        assert!(weak.uncertainties.unwrap().iter().all(Option::is_some));
1418
1419        let wrong = fit(1e-4, 1e-2, 2, [level, 0.0], None);
1420        assert_eq!(wrong.stop, Stop::NoStep, "{}", report(&wrong));
1421        let (alone, left) = wrong.own.unwrap();
1422        let (predicted, rise) = wrong.rejected.tested.unwrap();
1423        assert!(
1424            alone == 1 && left > NEWTON_DECREMENT_TOL && predicted > 0.0 && rise >= 0.0,
1425            "{}",
1426            report(&wrong)
1427        );
1428
1429        // Every step toward b = 0 lowers a, which the last bin forbids.
1430        let walled = fit(1e-4, 0.0, 2, [level + 1.0, -1.0], Some(level + 1.0));
1431        // No step can show the decrease left along a direction of so little information.
1432        let unseen = fit(1e-12, 0.0, 1, [1.3, 0.4], None);
1433        // One bin's misfit puts every predicted decrease within the objective's rounding.
1434        let model = Affine {
1435            offset: vec![1e8, 1e8, 1.0],
1436            jacobian: vec![vec![1e8, 1e8], vec![1e8, 1.00001e8], vec![0.0; 2]],
1437        };
1438        let observed = [9.9e7, 1.01e8, 1e30];
1439        let config = PoissonConfig::default();
1440        let hidden = poisson_fit(&model, &observed, &[], &mut two_free(), &config).unwrap();
1441        // Every step rounds away against parameters of 1e16.
1442        let model = Offset {
1443            model: Affine {
1444                offset: vec![1e8; 2],
1445                jacobian: vec![vec![1e8, 1e8], vec![1e8, 1.00001e8]],
1446            },
1447            origin: 1e16,
1448        };
1449        let mut far = ParameterSet::new(
1450            ["a", "b"]
1451                .map(|name| FitParameter::unbounded(name, 1e16))
1452                .to_vec(),
1453        );
1454        let lost = poisson_fit(&model, &[9.9e7, 1.01e8], &[], &mut far, &config).unwrap();
1455        // The first step is taken and fails on the curve; every smaller one rounds away.
1456        let model = Offset {
1457            model: Valley,
1458            origin: 1e16,
1459        };
1460        far.set_free_values(&[1e16; 2]);
1461        let coarse = poisson_fit(&model, &[1.004e6, 9.96e5], &[], &mut far, &config).unwrap();
1462        for untested in [walled, unseen, hidden, lost, coarse] {
1463            assert_eq!(untested.stop, Stop::NoStep, "{}", report(&untested));
1464            assert!(
1465                untested.own.unwrap().1 < NEWTON_DECREMENT_TOL
1466                    && untested.rejected.tested.is_none(),
1467                "{}",
1468                report(&untested)
1469            );
1470        }
1471    }
1472
1473    /// Ten bins `1e6 + 1e3·(a + b·x)`, the first with 5e4 more once `b ≥ 1`.
1474    struct Jump;
1475
1476    impl FitModel for Jump {
1477        fn evaluate(&self, p: &[f64]) -> Result<Vec<f64>, FittingError> {
1478            let step = |i: usize| if i == 0 && p[1] >= 1.0 { 5e4 } else { 0.0 };
1479            Ok((0..10)
1480                .map(|i| 1e6 + 1e3 * (p[0] + p[1] * (i as f64 / 9.0 - 0.5)) + step(i))
1481                .collect())
1482        }
1483
1484        fn analytical_jacobian(&self, _: &[f64], _: &[usize], _: &[f64]) -> Option<FlatMatrix> {
1485            let mut jacobian = FlatMatrix::zeros(10, 2);
1486            for i in 0..10 {
1487                *jacobian.get_mut(i, 0) = 1e3;
1488                *jacobian.get_mut(i, 1) = 1e3 * (i as f64 / 9.0 - 0.5);
1489            }
1490            Some(jacobian)
1491        }
1492    }
1493
1494    #[test]
1495    fn a_fit_stopped_at_a_jump_of_the_counts_names_the_quantity_that_jumps() {
1496        let observed: Vec<f64> = (0..10)
1497            .map(|i| 1e6 + 2e3 * (i as f64 / 9.0 - 0.5))
1498            .collect();
1499        let config = PoissonConfig::default();
1500        let fit = poisson_fit(&Jump, &observed, &[], &mut two_free(), &config).unwrap();
1501        assert_eq!(fit.stop, Stop::NoStep, "{fit:?}");
1502        let (predicted, rise) = fit.rejected.tested.unwrap();
1503        let (alone, moved, risen) = fit.rejected.alone.unwrap();
1504        assert!(
1505            rise > 1e3 && predicted < 1e-3 && alone == 1 && moved > 0.0 && risen > 1e3,
1506            "{fit:?}"
1507        );
1508        assert_eq!(fit.rejected.again, Some(0.0));
1509        let [half, opposite] = fit.rejected.around.unwrap();
1510        let (most, before, after, changed) = fit.rejected.most.unwrap();
1511        assert!(
1512            half > 1e3 && opposite.abs() < 1.0 && (most, changed) == (0, 1) && after - before > 4e4,
1513            "{fit:?}"
1514        );
1515        // On a lower bound just under the jump, the opposite move cannot be made.
1516        let under = f64::from_bits(1.0_f64.to_bits() - 1);
1517        let mut bounded = two_free();
1518        bounded.params[1].value = under;
1519        bounded.params[1].lower = under;
1520        let fit = poisson_fit(&Jump, &observed, &[], &mut bounded, &config).unwrap();
1521        assert_eq!(fit.stop, Stop::NoStep, "{fit:?}");
1522        assert!(
1523            fit.rejected.alone.is_some() && fit.rejected.around.is_none(),
1524            "{fit:?}"
1525        );
1526    }
1527
1528    /// Two bins `1e6 ± 1e3·a`, halfway to 1.005e6 the first time they are asked for.
1529    struct Fickle(std::cell::Cell<bool>);
1530
1531    impl FitModel for Fickle {
1532        fn evaluate(&self, p: &[f64]) -> Result<Vec<f64>, FittingError> {
1533            let pull = if self.0.replace(false) { 0.5 } else { 0.0 };
1534            Ok([1.0, -1.0]
1535                .map(|sign| 1e6 + 1e3 * sign * p[0])
1536                .map(|count| count + pull * (1.005e6 - count))
1537                .to_vec())
1538        }
1539
1540        fn analytical_jacobian(&self, _: &[f64], _: &[usize], _: &[f64]) -> Option<FlatMatrix> {
1541            let mut jacobian = FlatMatrix::zeros(2, 1);
1542            jacobian.data = vec![1e3, -1e3];
1543            Some(jacobian)
1544        }
1545    }
1546
1547    #[test]
1548    fn a_model_that_changes_its_counts_at_the_same_parameters_is_reported() {
1549        let mut params = ParameterSet::new(vec![FitParameter::unbounded("a", 3.0)]);
1550        let model = Fickle(std::cell::Cell::new(true));
1551        let config = PoissonConfig::default();
1552        let fit = poisson_fit(&model, &[1.005e6; 2], &[], &mut params, &config).unwrap();
1553        assert_eq!(fit.stop, Stop::NoStep, "{fit:?}");
1554        assert!(fit.rejected.again.unwrap() > 20.0, "{fit:?}");
1555    }
1556
1557    /// Two bins near 1e6 counts, half deviance about `½[(k(v − u²))² + (1 − u)²]`.
1558    struct Curved(f64);
1559
1560    impl FitModel for Curved {
1561        fn evaluate(&self, p: &[f64]) -> Result<Vec<f64>, FittingError> {
1562            Ok(vec![
1563                1e6 + self.0 * 1e3 * (p[1] - p[0] * p[0]),
1564                1e6 + 1e3 * (1.0 - p[0]),
1565            ])
1566        }
1567
1568        fn analytical_jacobian(&self, p: &[f64], _: &[usize], _: &[f64]) -> Option<FlatMatrix> {
1569            let mut jacobian = FlatMatrix::zeros(2, 2);
1570            jacobian.data = vec![-2e3 * self.0 * p[0], 1e3 * self.0, -1e3, 0.0];
1571            Some(jacobian)
1572        }
1573    }
1574
1575    #[test]
1576    fn a_fit_follows_a_narrow_curved_valley_to_its_minimum() {
1577        let mut params = ParameterSet::new(vec![
1578            FitParameter::unbounded("u", -1.2),
1579            FitParameter::unbounded("v", 1.0),
1580        ]);
1581        let config = PoissonConfig::default();
1582        let fit = poisson_fit(&Curved(300.0), &[1e6; 2], &[], &mut params, &config).unwrap();
1583        assert!(
1584            fit.converged && fit.params.iter().all(|p| (p - 1.0).abs() < 1e-5),
1585            "{fit:?}"
1586        );
1587    }
1588
1589    fn decay(jacobian_factor: f64) -> Decay {
1590        Decay {
1591            t: (0..25).map(|i| 0.2 * f64::from(i)).collect(),
1592            jacobian_factor,
1593        }
1594    }
1595
1596    fn decay_params(a: f64, b: f64, a_upper: f64) -> ParameterSet {
1597        ParameterSet::new(vec![
1598            FitParameter {
1599                name: "a".into(),
1600                value: a,
1601                lower: 0.0,
1602                upper: a_upper,
1603                fixed: false,
1604            },
1605            FitParameter::non_negative("b", b),
1606        ])
1607    }
1608
1609    fn fit_decay(
1610        model: &Decay,
1611        observed: &[f64],
1612        start: (f64, f64),
1613        max_iter: usize,
1614    ) -> PoissonResult {
1615        let mut params = decay_params(start.0, start.1, f64::INFINITY);
1616        let config = PoissonConfig {
1617            max_iter,
1618            ..PoissonConfig::default()
1619        };
1620        poisson_fit(model, observed, &[], &mut params, &config).unwrap()
1621    }
1622
1623    #[test]
1624    fn half_deviance_matches_high_precision_values() {
1625        for (obs, mean, exact) in [
1626            (1_000_001.0, 1_000_000.0, 4.999_998_333_334_167e-7),
1627            (3.0, 2.5, 0.046_964_670_381_863_88),
1628            (0.0, 2.5, 2.5),
1629            (1.0e308, 9.0e307, 5.360_515_657_826_301e305),
1630            (1.7e308, 1.65e308, 7.500_373_544_579_622e304),
1631            (1.0, 1.0e-310, 712.801_378_828_154_2),
1632        ] {
1633            let got = half_deviance(obs, mean);
1634            assert!(
1635                ((got - exact) / exact).abs() < 1e-12,
1636                "{obs}, {mean}: {got}"
1637            );
1638        }
1639    }
1640
1641    #[test]
1642    fn inputs_that_are_not_counts_for_this_model_are_refused() {
1643        let model = decay(1.0);
1644        let observed = model.evaluate(&[100.0, 1.5]).unwrap();
1645        let fit = |model: &dyn FitModel, observed: &[f64]| {
1646            poisson_fit(
1647                model,
1648                observed,
1649                &[],
1650                &mut decay_params(50.0, 1.0, f64::INFINITY),
1651                &PoissonConfig::default(),
1652            )
1653        };
1654        let mut bad = observed.clone();
1655        bad[3] = f64::NAN;
1656        assert!(fit(&model, &bad).is_err());
1657        bad[3] = -1.0;
1658        assert!(fit(&model, &bad).is_err());
1659        assert!(fit(&model, &observed[1..]).is_err());
1660        let empty = Decay {
1661            t: vec![],
1662            jacobian_factor: 1.0,
1663        };
1664        assert!(fit(&empty, &[]).is_err());
1665        let no_jacobian = ExponentialModel {
1666            x: model.t.clone(),
1667            flux: vec![100.0; model.t.len()],
1668        };
1669        assert!(fit(&no_jacobian, &observed).is_err());
1670    }
1671
1672    #[test]
1673    fn a_start_with_a_zero_prediction_is_not_converged() {
1674        let model = decay(1.0);
1675        let observed = model.evaluate(&[100.0, 1.5]).unwrap();
1676        let result = fit_decay(&model, &observed, (0.0, 1.0), 200);
1677        assert!(!result.converged && result.iterations == 0, "{result:?}");
1678        assert_eq!(result.stop, Stop::Start);
1679    }
1680
1681    #[test]
1682    fn a_non_finite_slope_ends_the_fit_unconverged() {
1683        let model = decay(f64::NAN);
1684        let observed = decay(1.0).evaluate(&[100.0, 1.5]).unwrap();
1685        let result = fit_decay(&model, &observed, (50.0, 1.0), 200);
1686        assert!(
1687            !result.converged && result.uncertainties.is_none(),
1688            "{result:?}"
1689        );
1690        assert_eq!(result.stop, Stop::Slope);
1691    }
1692
1693    #[test]
1694    fn a_fit_whose_step_cannot_lower_the_deviance_is_not_converged() {
1695        let model = decay(-1.0);
1696        let observed = decay(1.0).evaluate(&[100.0, 1.5]).unwrap();
1697        let result = fit_decay(&model, &observed, (50.0, 1.0), 200);
1698        assert!(
1699            !result.converged && result.iterations == 0 && result.uncertainties.is_none(),
1700            "{result:?}"
1701        );
1702        assert_eq!(result.stop, Stop::NoStep);
1703    }
1704
1705    #[test]
1706    fn a_start_outside_the_bounds_ends_inside_them() {
1707        let model = decay(1.0);
1708        let observed = model.evaluate(&[100.0, 1.5]).unwrap();
1709        let mut params = decay_params(100.0, 1.5, 80.0);
1710        let result = poisson_fit(
1711            &model,
1712            &observed,
1713            &[],
1714            &mut params,
1715            &PoissonConfig::default(),
1716        )
1717        .unwrap();
1718        assert!(result.converged && result.params[0] == 80.0, "{result:?}");
1719        assert_eq!(result.on_bound, vec![true, false]);
1720    }
1721
1722    #[test]
1723    fn a_fit_that_reaches_the_minimum_on_its_last_allowed_step_has_converged() {
1724        let model = decay(1.0);
1725        let observed = model.evaluate(&[100.0, 1.5]).unwrap();
1726        let steps = fit_decay(&model, &observed, (20.0, 0.3), 200).iterations;
1727        assert!(steps > 1);
1728        let last = fit_decay(&model, &observed, (20.0, 0.3), steps);
1729        assert!(last.converged && last.stop == Stop::Minimum, "{last:?}");
1730        assert!(last.moving.is_empty());
1731        let short = fit_decay(&model, &observed, (20.0, 0.3), steps - 1);
1732        assert!(
1733            !short.converged && short.stop == Stop::StepLimit,
1734            "{short:?}"
1735        );
1736    }
1737
1738    struct Scaled {
1739        x: Vec<f64>,
1740        slope: f64,
1741        tiny: f64,
1742    }
1743
1744    impl FitModel for Scaled {
1745        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
1746            Ok(self
1747                .x
1748                .iter()
1749                .map(|&x| 100.0 * (self.slope * params[0] * x).exp() + self.tiny * params[1] * x)
1750                .collect())
1751        }
1752
1753        fn analytical_jacobian(
1754            &self,
1755            params: &[f64],
1756            free_param_indices: &[usize],
1757            _y_current: &[f64],
1758        ) -> Option<FlatMatrix> {
1759            let mut jacobian = FlatMatrix::zeros(self.x.len(), free_param_indices.len());
1760            for (row, &x) in self.x.iter().enumerate() {
1761                let slopes = [
1762                    100.0 * self.slope * x * (self.slope * params[0] * x).exp(),
1763                    self.tiny * x,
1764                ];
1765                for (col, &index) in free_param_indices.iter().enumerate() {
1766                    *jacobian.get_mut(row, col) = slopes[index];
1767                }
1768            }
1769            Some(jacobian)
1770        }
1771    }
1772
1773    fn fit_scaled(slope: f64, tiny: f64) -> PoissonResult {
1774        let model = Scaled {
1775            x: vec![1.0, 2.0, 3.0],
1776            slope,
1777            tiny,
1778        };
1779        let observed = model.evaluate(&[0.3 / slope, 0.0]).unwrap();
1780        let mut params = ParameterSet::new(vec![
1781            FitParameter::unbounded("theta", 0.0),
1782            FitParameter::unbounded("weak", 0.0),
1783        ]);
1784        poisson_fit(
1785            &model,
1786            &observed,
1787            &[],
1788            &mut params,
1789            &PoissonConfig::default(),
1790        )
1791        .unwrap()
1792    }
1793
1794    #[test]
1795    fn a_slope_too_large_to_square_is_fitted() {
1796        let result = fit_scaled(1.0e160, 1.0);
1797        assert!(
1798            result.converged && result.deviance < NEWTON_DECREMENT_TOL,
1799            "{result:?}"
1800        );
1801    }
1802
1803    #[test]
1804    fn a_slope_too_small_to_square_does_not_fake_convergence() {
1805        let result = fit_scaled(1.0, 1.0e-310);
1806        assert!(
1807            !result.converged || result.deviance < NEWTON_DECREMENT_TOL,
1808            "{result:?}"
1809        );
1810    }
1811
1812    struct Line {
1813        x: Vec<f64>,
1814    }
1815
1816    impl FitModel for Line {
1817        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
1818            Ok(self.x.iter().map(|&x| 1.0 + params[0] * x).collect())
1819        }
1820
1821        fn analytical_jacobian(
1822            &self,
1823            _params: &[f64],
1824            free_param_indices: &[usize],
1825            _y_current: &[f64],
1826        ) -> Option<FlatMatrix> {
1827            let mut jacobian = FlatMatrix::zeros(self.x.len(), free_param_indices.len());
1828            jacobian.data.copy_from_slice(&self.x);
1829            Some(jacobian)
1830        }
1831    }
1832
1833    struct Proportional {
1834        a: Vec<f64>,
1835    }
1836
1837    impl FitModel for Proportional {
1838        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
1839            Ok(self.a.iter().map(|a| a * params[0]).collect())
1840        }
1841
1842        fn analytical_jacobian(
1843            &self,
1844            _params: &[f64],
1845            free_param_indices: &[usize],
1846            _y_current: &[f64],
1847        ) -> Option<FlatMatrix> {
1848            let mut jacobian = FlatMatrix::zeros(self.a.len(), free_param_indices.len());
1849            jacobian.data.copy_from_slice(&self.a);
1850            Some(jacobian)
1851        }
1852    }
1853
1854    #[test]
1855    fn a_prior_moves_the_fit_to_the_maximum_of_the_posterior() {
1856        let model = Proportional {
1857            a: vec![1.0, 2.0, 3.0, 4.0],
1858        };
1859        let observed = [3.0, 5.0, 9.0, 12.0];
1860        let (a_sum, y_sum): (f64, f64) = (10.0, 29.0);
1861        let (mean, sd) = (2.0, 0.3);
1862        let fit = |priors: &[Prior]| {
1863            let mut params = ParameterSet::new(vec![FitParameter::non_negative("theta", 1.0)]);
1864            poisson_fit(
1865                &model,
1866                &observed,
1867                priors,
1868                &mut params,
1869                &PoissonConfig::default(),
1870            )
1871            .unwrap()
1872        };
1873        let result = fit(&[Prior::measured(0, mean, sd)]);
1874        assert!(result.converged);
1875        let theta = result.params[0];
1876        let b = a_sum - mean / sd.powi(2);
1877        let root = sd.powi(2) * 0.5 * (-b + (b * b + 4.0 * y_sum / sd.powi(2)).sqrt());
1878        let variance = 1.0 / (a_sum / theta + 1.0 / sd.powi(2));
1879        assert!(
1880            (theta - root).abs() <= 2e-3 * variance.sqrt(),
1881            "{theta} vs {root}"
1882        );
1883        let covariance = result.covariance.expect("covariance").get(0, 0);
1884        assert!((covariance / variance - 1.0).abs() <= 1e-12, "{covariance}");
1885        let deviance: f64 = observed
1886            .iter()
1887            .zip(&model.a)
1888            .map(|(y, a)| a * theta - y + y * (y / (a * theta)).ln())
1889            .sum();
1890        assert!((result.deviance / deviance - 1.0).abs() <= 1e-12);
1891        let leverage = result.leverage.expect("leverage");
1892        for (h, a) in leverage.iter().zip(&model.a) {
1893            assert!((h / (a / theta * variance) - 1.0).abs() <= 1e-12, "{h}");
1894        }
1895        let unmeasured = fit(&[]).leverage.expect("leverage");
1896        assert!((unmeasured.iter().sum::<f64>() - 1.0).abs() <= 1e-12);
1897    }
1898
1899    #[test]
1900    fn priors_that_are_not_measurements_of_one_free_parameter_are_refused() {
1901        let model = decay(1.0);
1902        let observed = model.evaluate(&[100.0, 1.5]).unwrap();
1903        let fit = |priors: &[Prior], fixed: bool| {
1904            let mut params = decay_params(50.0, 1.0, f64::INFINITY);
1905            params.params[1].fixed = fixed;
1906            poisson_fit(
1907                &model,
1908                &observed,
1909                priors,
1910                &mut params,
1911                &PoissonConfig::default(),
1912            )
1913        };
1914        let prior = Prior::measured;
1915        assert!(fit(&[prior(1, 1.5, 0.1)], false).is_ok());
1916        for priors in [
1917            vec![prior(2, 1.5, 0.1)],
1918            vec![prior(1, 1.5, 0.1), prior(1, 1.4, 0.1)],
1919            vec![prior(1, f64::NAN, 0.1)],
1920            vec![prior(1, 1.5, 0.0)],
1921            vec![prior(1, 1.5, f64::INFINITY)],
1922            vec![block(&[0, 1]), prior(1, 1.5, 0.1)],
1923        ] {
1924            assert!(fit(&priors, false).is_err(), "{priors:?}");
1925        }
1926        assert!(fit(&[prior(1, 1.5, 0.1)], true).is_err());
1927        assert!(fit(&[block(&[0, 1])], false).is_ok());
1928    }
1929
1930    fn two_by_two(data: [f64; 4]) -> FlatMatrix {
1931        FlatMatrix {
1932            data: data.to_vec(),
1933            nrows: 2,
1934            ncols: 2,
1935        }
1936    }
1937
1938    fn block(parameters: &[usize]) -> Prior {
1939        Prior::correlated(
1940            parameters,
1941            &[100.0, 1.5],
1942            &two_by_two([1.0, 0.0, 0.0, 0.01]),
1943        )
1944        .unwrap()
1945    }
1946
1947    #[test]
1948    fn covariances_that_are_not_symmetric_and_well_conditioned_are_refused() {
1949        let correlated = |data| Prior::correlated(&[0, 1], &[0.0, 0.0], &two_by_two(data));
1950        let scaled = |rho: f64| correlated([1.0, rho * 1e3, rho * 1e3, 1e6]);
1951        assert!(scaled(1.0 - 1e-9).is_ok());
1952        assert!(correlated([1.0, 1e-6, 1e-6 + 1e-17, 1.0]).is_ok());
1953        for result in [
1954            scaled(1.0 - 1e-11),
1955            scaled(1.0 + 1e-9),
1956            correlated([1.0, 0.5, 0.5 + 1e-10, 1.0]),
1957            correlated([1.0, 1e-6, 1e-6 + 1e-11, 1.0]),
1958            correlated([1.0, f64::NAN, f64::NAN, 1.0]),
1959            correlated([0.0, 0.0, 0.0, 1.0]),
1960            Prior::correlated(&[0, 1], &[0.0], &two_by_two([1.0, 0.0, 0.0, 1.0])),
1961            Prior::correlated(
1962                &[0, 1],
1963                &[0.0, 0.0],
1964                &FlatMatrix {
1965                    data: vec![1.0, 0.0, 0.0],
1966                    nrows: 2,
1967                    ncols: 2,
1968                },
1969            ),
1970            Prior::correlated(&[], &[], &FlatMatrix::zeros(0, 0)),
1971            Prior::correlated(&[0, 1], &[f64::NAN, 0.0], &two_by_two([1.0, 0.0, 0.0, 1.0])),
1972            Prior::correlated(&[1, 1], &[0.0, 0.0], &two_by_two([1.0, 0.0, 0.0, 1.0])),
1973        ] {
1974            assert!(result.is_err(), "{result:?}");
1975        }
1976    }
1977
1978    #[test]
1979    fn a_measured_prior_divides_by_its_sd() {
1980        for (value, mean, sd) in [
1981            (1.234_567, 0.987_654_3, 0.031_4),
1982            (1e-7, -3.3e5, 7.0e3),
1983            (2.0, 2.0, 0.3),
1984        ] {
1985            let prior = Prior::measured(0, mean, sd);
1986            assert_eq!(
1987                prior.residual(&[value])[0].to_bits(),
1988                ((value - mean) / sd).to_bits()
1989            );
1990            assert_eq!(prior.inverse_factor()[0].to_bits(), (1.0 / sd).to_bits());
1991        }
1992    }
1993
1994    struct Mixture;
1995
1996    const MIXTURE: [[f64; 2]; 5] = [[1.0, 5.0], [2.0, 3.0], [3.0, 2.0], [4.0, 1.0], [5.0, 0.5]];
1997
1998    const MIXTURE_COUNTS: [f64; 5] = [21.0, 20.0, 15.0, 18.0, 16.0];
1999
2000    impl FitModel for Mixture {
2001        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2002            Ok(MIXTURE
2003                .iter()
2004                .map(|a| a[0] * params[0] + a[1] * params[1])
2005                .collect())
2006        }
2007
2008        fn analytical_jacobian(
2009            &self,
2010            _params: &[f64],
2011            free_param_indices: &[usize],
2012            _y_current: &[f64],
2013        ) -> Option<FlatMatrix> {
2014            let mut jacobian = FlatMatrix::zeros(MIXTURE.len(), free_param_indices.len());
2015            for (row, a) in MIXTURE.iter().enumerate() {
2016                for (col, &index) in free_param_indices.iter().enumerate() {
2017                    *jacobian.get_mut(row, col) = a[index];
2018                }
2019            }
2020            Some(jacobian)
2021        }
2022    }
2023
2024    fn fit_mixture(priors: &[Prior]) -> PoissonResult {
2025        let mut params = ParameterSet::new(vec![
2026            FitParameter::non_negative("x", 1.0),
2027            FitParameter::non_negative("y", 1.0),
2028        ]);
2029        poisson_fit(
2030            &Mixture,
2031            &MIXTURE_COUNTS,
2032            priors,
2033            &mut params,
2034            &PoissonConfig::default(),
2035        )
2036        .unwrap()
2037    }
2038
2039    fn inverse(m: [[f64; 2]; 2]) -> [[f64; 2]; 2] {
2040        let det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
2041        [
2042            [m[1][1] / det, -m[0][1] / det],
2043            [-m[1][0] / det, m[0][0] / det],
2044        ]
2045    }
2046
2047    #[test]
2048    fn a_correlated_prior_adds_its_inverse_covariance_to_the_information() {
2049        let (mean, c) = ([3.0, 4.0], [[0.25, 0.15], [0.15, 0.36]]);
2050        let prior = Prior::correlated(&[0, 1], &mean, &two_by_two(c.concat().try_into().unwrap()));
2051        let result = fit_mixture(&[prior.unwrap()]);
2052        assert!(result.converged);
2053        let precision = inverse(c);
2054        let information = |theta: [f64; 2], observed: bool| {
2055            let mut information = precision;
2056            for (a, y) in MIXTURE.iter().zip(MIXTURE_COUNTS) {
2057                let mu = a[0] * theta[0] + a[1] * theta[1];
2058                let weight = if observed { y / mu.powi(2) } else { 1.0 / mu };
2059                for k in 0..2 {
2060                    for l in 0..2 {
2061                        information[k][l] += weight * a[k] * a[l];
2062                    }
2063                }
2064            }
2065            information
2066        };
2067        let mut mode = mean;
2068        for _ in 0..50 {
2069            let gradient: Vec<f64> = (0..2)
2070                .map(|k| {
2071                    (0..2)
2072                        .map(|l| precision[k][l] * (mode[l] - mean[l]))
2073                        .sum::<f64>()
2074                        + MIXTURE
2075                            .iter()
2076                            .zip(MIXTURE_COUNTS)
2077                            .map(|(a, y)| a[k] * (1.0 - y / (a[0] * mode[0] + a[1] * mode[1])))
2078                            .sum::<f64>()
2079                })
2080                .collect();
2081            let step = inverse(information(mode, true));
2082            for k in 0..2 {
2083                mode[k] -= (0..2).map(|l| step[k][l] * gradient[l]).sum::<f64>();
2084            }
2085        }
2086        let fitted = [result.params[0], result.params[1]];
2087        let expected = information(fitted, false);
2088        let shift: Vec<f64> = (0..2).map(|k| fitted[k] - mode[k]).collect();
2089        let distance = (0..2)
2090            .flat_map(|k| (0..2).map(move |l| (k, l)))
2091            .map(|(k, l)| shift[k] * expected[k][l] * shift[l])
2092            .sum::<f64>()
2093            .sqrt();
2094        assert!(distance <= 2e-3, "{fitted:?} vs {mode:?}");
2095        let covariance = inverse(expected);
2096        let reported = result.covariance.expect("covariance");
2097        for k in 0..2 {
2098            for l in 0..2 {
2099                let scale = (covariance[k][k] * covariance[l][l]).sqrt();
2100                assert!(
2101                    (reported.get(k, l) - covariance[k][l]).abs() <= 1e-12 * scale,
2102                    "{k}{l}: {} vs {}",
2103                    reported.get(k, l),
2104                    covariance[k][l]
2105                );
2106            }
2107        }
2108        let unbounded = result.unbounded.expect("unbounded");
2109        assert_eq!(unbounded.covariance.data, reported.data);
2110        for k in 0..2 {
2111            assert!((unbounded.mean[k] - fitted[k]).abs() <= 2e-3 * covariance[k][k].sqrt());
2112        }
2113    }
2114
2115    const FAR_COUNTS: [f64; 5] = [9743.0, 20046.0, 30110.0, 39769.0, 49761.0];
2116
2117    fn fit_far(params: Vec<FitParameter>, priors: &[Prior]) -> PoissonResult {
2118        let mut params = ParameterSet::new(params);
2119        poisson_fit(
2120            &Mixture,
2121            &FAR_COUNTS,
2122            priors,
2123            &mut params,
2124            &PoissonConfig::default(),
2125        )
2126        .unwrap()
2127    }
2128
2129    #[test]
2130    fn the_unbounded_gaussian_is_one_newton_step_past_the_bounds() {
2131        let (x, y) = (
2132            FitParameter::non_negative("x", 9000.0),
2133            FitParameter::non_negative("y", 1.0),
2134        );
2135        let capped = FitParameter {
2136            upper: 9000.0,
2137            ..x.clone()
2138        };
2139        let cases = [
2140            (vec![x.clone(), y.clone()], None, 1),
2141            (vec![capped, FitParameter::unbounded("y", 1.0)], None, 0),
2142            (vec![x, y], Some((10.0, 20.0)), 1),
2143        ];
2144        for (params, prior, held) in cases {
2145            let priors: Vec<Prior> = prior
2146                .iter()
2147                .map(|&(mean, sd)| Prior::measured(1, mean, sd))
2148                .collect();
2149            let result = fit_far(params, &priors);
2150            assert!(result.converged && result.on_bound[held] && !result.on_bound[1 - held]);
2151            let theta = [result.params[0], result.params[1]];
2152            let (mut information, mut gradient) = ([[0.0; 2]; 2], [0.0; 2]);
2153            for (a, n) in MIXTURE.iter().zip(FAR_COUNTS) {
2154                let mu = a[0] * theta[0] + a[1] * theta[1];
2155                for k in 0..2 {
2156                    gradient[k] += a[k] * (1.0 - n / mu);
2157                    for l in 0..2 {
2158                        information[k][l] += a[k] * a[l] / mu;
2159                    }
2160                }
2161            }
2162            if let Some((mean, sd)) = prior {
2163                information[1][1] += sd.powi(-2);
2164                gradient[1] += (theta[1] - mean) / sd.powi(2);
2165            }
2166            let covariance = inverse(information);
2167            let unbounded = result.unbounded.expect("unbounded");
2168            for k in 0..2 {
2169                let mean = theta[k] - (0..2).map(|l| covariance[k][l] * gradient[l]).sum::<f64>();
2170                let sd = covariance[k][k].sqrt();
2171                assert!(
2172                    (unbounded.mean[k] - mean).abs() <= 1e-12 * sd,
2173                    "{held} {k}: {} vs {mean}",
2174                    unbounded.mean[k]
2175                );
2176                for (l, expected) in covariance[k].iter().enumerate() {
2177                    let scale = sd * covariance[l][l].sqrt();
2178                    assert!((unbounded.covariance.get(k, l) - expected).abs() <= 1e-12 * scale);
2179                }
2180            }
2181        }
2182    }
2183
2184    struct Unused;
2185
2186    impl FitModel for Unused {
2187        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2188            Ok(vec![params[0]])
2189        }
2190
2191        fn analytical_jacobian(
2192            &self,
2193            _params: &[f64],
2194            free_param_indices: &[usize],
2195            _y_current: &[f64],
2196        ) -> Option<FlatMatrix> {
2197            let mut jacobian = FlatMatrix::zeros(1, free_param_indices.len());
2198            for (col, &index) in free_param_indices.iter().enumerate() {
2199                *jacobian.get_mut(0, col) = f64::from(u8::from(index == 0));
2200            }
2201            Some(jacobian)
2202        }
2203    }
2204
2205    #[test]
2206    fn a_parameter_on_a_bound_the_counts_do_not_determine_leaves_the_others_their_gaussian() {
2207        let mut params = ParameterSet::new(vec![
2208            FitParameter::unbounded("x", 90.0),
2209            FitParameter::non_negative("y", 0.0),
2210        ]);
2211        let result = poisson_fit(
2212            &Unused,
2213            &[100.0],
2214            &[],
2215            &mut params,
2216            &PoissonConfig::default(),
2217        )
2218        .unwrap();
2219        assert!(result.converged && result.on_bound == [false, true]);
2220        let unbounded = result.unbounded.expect("unbounded");
2221        let variance = unbounded.covariance.get(0, 0);
2222        assert!((variance / result.params[0] - 1.0).abs() <= 1e-12);
2223        assert!((unbounded.mean[0] - 100.0).abs() <= 2e-3 * variance.sqrt());
2224        assert!(unbounded.covariance.get(1, 1).is_nan() && unbounded.mean[1].is_nan());
2225    }
2226
2227    #[test]
2228    fn the_unbounded_gaussian_is_the_fit_without_its_bound_to_second_order() {
2229        let x = FitParameter::non_negative("x", 9000.0);
2230        let bounded = fit_far(vec![x.clone(), FitParameter::non_negative("y", 1.0)], &[]);
2231        let free = fit_far(vec![x, FitParameter::unbounded("y", 1.0)], &[]);
2232        let covariance = free.covariance.expect("covariance");
2233        assert!(bounded.on_bound[1] && !free.on_bound[1]);
2234        assert!(free.params[1] <= -1.5 * covariance.get(1, 1).sqrt());
2235        let unbounded = bounded.unbounded.expect("unbounded");
2236        for k in 0..2 {
2237            let variance = covariance.get(k, k);
2238            assert!((unbounded.mean[k] - free.params[k]).abs() <= 0.05 * variance.sqrt());
2239            assert!((unbounded.covariance.get(k, k) / variance - 1.0).abs() <= 0.05);
2240        }
2241    }
2242
2243    #[test]
2244    fn a_correlated_prior_with_a_diagonal_covariance_is_two_measured_priors() {
2245        let (mean, sd) = ([3.0, 4.0], [0.5, 0.6]);
2246        let diagonal = two_by_two([sd[0] * sd[0], 0.0, 0.0, sd[1] * sd[1]]);
2247        let bits = |result: PoissonResult| -> Vec<u64> {
2248            result
2249                .params
2250                .iter()
2251                .chain(&result.covariance.expect("covariance").data)
2252                .chain([&result.deviance])
2253                .map(|v| v.to_bits())
2254                .collect()
2255        };
2256        assert_eq!(
2257            bits(fit_mixture(&[
2258                Prior::correlated(&[0, 1], &mean, &diagonal).unwrap()
2259            ])),
2260            bits(fit_mixture(&[
2261                Prior::measured(0, mean[0], sd[0]),
2262                Prior::measured(1, mean[1], sd[1]),
2263            ]))
2264        );
2265    }
2266
2267    #[test]
2268    fn predictions_stay_positive_where_nothing_was_counted() {
2269        let model = Line {
2270            x: vec![1.0, 2.0, 3.0],
2271        };
2272        let mut params = ParameterSet::new(vec![FitParameter::unbounded("a", 0.0)]);
2273        let result = poisson_fit(
2274            &model,
2275            &[0.0; 3],
2276            &[],
2277            &mut params,
2278            &PoissonConfig::default(),
2279        )
2280        .unwrap();
2281        let predicted = model.evaluate(&result.params).unwrap();
2282        assert!(predicted.iter().all(|&mean| mean > 0.0), "{result:?}");
2283    }
2284
2285    struct WrongShape;
2286
2287    impl FitModel for WrongShape {
2288        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2289            Ok(vec![params[0]; 3])
2290        }
2291
2292        fn analytical_jacobian(
2293            &self,
2294            _params: &[f64],
2295            free_param_indices: &[usize],
2296            _y_current: &[f64],
2297        ) -> Option<FlatMatrix> {
2298            Some(FlatMatrix::zeros(2, free_param_indices.len()))
2299        }
2300    }
2301
2302    #[test]
2303    fn a_jacobian_of_the_wrong_shape_is_refused() {
2304        let mut params = ParameterSet::new(vec![FitParameter::non_negative("a", 1.0)]);
2305        let result = poisson_fit(
2306            &WrongShape,
2307            &[1.0; 3],
2308            &[],
2309            &mut params,
2310            &PoissonConfig::default(),
2311        );
2312        assert!(
2313            matches!(result, Err(FittingError::LengthMismatch { .. })),
2314            "{result:?}"
2315        );
2316    }
2317
2318    #[test]
2319    fn inverted_or_nan_bounds_are_refused() {
2320        let model = decay(1.0);
2321        let observed = model.evaluate(&[100.0, 1.5]).unwrap();
2322        for (lower, upper) in [
2323            (1.0, 0.0),
2324            (f64::NAN, 1.0),
2325            (0.0, f64::NAN),
2326            (f64::INFINITY, f64::INFINITY),
2327            (f64::NEG_INFINITY, f64::NEG_INFINITY),
2328        ] {
2329            let mut params = ParameterSet::new(vec![
2330                FitParameter {
2331                    name: "a".into(),
2332                    value: 50.0,
2333                    lower,
2334                    upper,
2335                    fixed: false,
2336                },
2337                FitParameter::non_negative("b", 1.0),
2338            ]);
2339            let result = poisson_fit(
2340                &model,
2341                &observed,
2342                &[],
2343                &mut params,
2344                &PoissonConfig::default(),
2345            );
2346            assert!(
2347                matches!(result, Err(FittingError::InvalidConfig(_))),
2348                "{lower}, {upper}"
2349            );
2350        }
2351    }
2352
2353    struct Additive;
2354
2355    impl FitModel for Additive {
2356        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2357            Ok(vec![2.0 * params[0], 1.0 - params[0]])
2358        }
2359
2360        fn analytical_jacobian(
2361            &self,
2362            _params: &[f64],
2363            free_param_indices: &[usize],
2364            _y_current: &[f64],
2365        ) -> Option<FlatMatrix> {
2366            let mut jacobian = FlatMatrix::zeros(2, free_param_indices.len());
2367            jacobian.data.copy_from_slice(&[2.0, -1.0]);
2368            Some(jacobian)
2369        }
2370    }
2371
2372    #[test]
2373    fn a_bin_predicted_zero_keeps_its_slope_in_the_gradient() {
2374        let mut params = ParameterSet::new(vec![FitParameter {
2375            name: "theta".into(),
2376            value: 0.0,
2377            lower: 0.0,
2378            upper: 1.0,
2379            fixed: false,
2380        }]);
2381        let result = poisson_fit(
2382            &Additive,
2383            &[0.0, 0.0],
2384            &[],
2385            &mut params,
2386            &PoissonConfig::default(),
2387        )
2388        .unwrap();
2389        assert!(
2390            result.converged
2391                && result.params[0] == 0.0
2392                && result.on_bound == vec![true]
2393                && result.unbounded.is_none(),
2394            "{result:?}"
2395        );
2396    }
2397
2398    struct Line2 {
2399        offset: [f64; 2],
2400        slope: [f64; 2],
2401    }
2402
2403    impl FitModel for Line2 {
2404        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2405            Ok((0..2)
2406                .map(|i| self.offset[i] + self.slope[i] * params[0])
2407                .collect())
2408        }
2409
2410        fn analytical_jacobian(
2411            &self,
2412            _params: &[f64],
2413            free_param_indices: &[usize],
2414            _y_current: &[f64],
2415        ) -> Option<FlatMatrix> {
2416            let mut jacobian = FlatMatrix::zeros(2, free_param_indices.len());
2417            jacobian.data.copy_from_slice(&self.slope);
2418            Some(jacobian)
2419        }
2420    }
2421
2422    fn bounded(value: f64, upper: f64) -> ParameterSet {
2423        ParameterSet::new(vec![FitParameter {
2424            name: "theta".into(),
2425            value,
2426            lower: 0.0,
2427            upper,
2428            fixed: false,
2429        }])
2430    }
2431
2432    #[test]
2433    fn a_zero_bin_slope_enters_the_convergence_test() {
2434        let model = Line2 {
2435            offset: [0.0, 4.0],
2436            slope: [1.0, -4.0],
2437        };
2438        let result = poisson_fit(
2439            &model,
2440            &[0.0, 3.0],
2441            &[],
2442            &mut bounded(0.0, 1.5),
2443            &PoissonConfig::default(),
2444        )
2445        .unwrap();
2446        assert!(
2447            result.converged && result.iterations == 0 && result.params[0] == 0.0,
2448            "{result:?}"
2449        );
2450    }
2451
2452    struct Affine {
2453        offset: Vec<f64>,
2454        jacobian: Vec<Vec<f64>>,
2455    }
2456
2457    impl FitModel for Affine {
2458        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2459            Ok(self
2460                .offset
2461                .iter()
2462                .zip(&self.jacobian)
2463                .map(|(offset, row)| {
2464                    offset + row.iter().zip(params).map(|(j, p)| j * p).sum::<f64>()
2465                })
2466                .collect())
2467        }
2468
2469        fn analytical_jacobian(
2470            &self,
2471            _params: &[f64],
2472            free_param_indices: &[usize],
2473            _y_current: &[f64],
2474        ) -> Option<FlatMatrix> {
2475            let mut jacobian = FlatMatrix::zeros(self.offset.len(), free_param_indices.len());
2476            jacobian.data.copy_from_slice(&self.jacobian.concat());
2477            Some(jacobian)
2478        }
2479    }
2480
2481    fn two_free() -> ParameterSet {
2482        ParameterSet::new(vec![
2483            FitParameter::unbounded("a", 0.0),
2484            FitParameter::unbounded("b", 0.0),
2485        ])
2486    }
2487
2488    fn at_the_start() -> PoissonConfig {
2489        PoissonConfig {
2490            max_iter: 0,
2491            ..PoissonConfig::default()
2492        }
2493    }
2494
2495    #[test]
2496    fn a_fit_stopped_at_its_step_limit_names_the_parameters_it_was_moving() {
2497        let model = Affine {
2498            offset: vec![1.0; 2],
2499            jacobian: vec![vec![1.0, 0.0], vec![0.0, 1.0e-3]],
2500        };
2501        for (observed, moving) in [([0.9, 1.0], [0]), ([1.0, 0.9], [1])] {
2502            let result =
2503                poisson_fit(&model, &observed, &[], &mut two_free(), &at_the_start()).unwrap();
2504            assert_eq!(result.stop, Stop::StepLimit);
2505            assert_eq!(result.moving, moving);
2506        }
2507        let both = Affine {
2508            offset: vec![1.0; 2],
2509            jacobian: vec![vec![1.0, 1.0], vec![0.0, 1.0e-3]],
2510        };
2511        let result =
2512            poisson_fit(&both, &[1.0, 0.9], &[], &mut two_free(), &at_the_start()).unwrap();
2513        assert_eq!(result.moving, [0, 1]);
2514    }
2515
2516    struct Reversed {
2517        slope: f64,
2518        floor: f64,
2519    }
2520
2521    impl FitModel for Reversed {
2522        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2523            if params[0] < self.floor {
2524                return Err(FittingError::EvaluationFailed("below the floor".into()));
2525            }
2526            Ok(vec![params[0]; 4])
2527        }
2528
2529        fn analytical_jacobian(&self, _: &[f64], free: &[usize], _: &[f64]) -> Option<FlatMatrix> {
2530            let mut slopes = FlatMatrix::zeros(4, free.len());
2531            slopes.data.fill(-self.slope);
2532            Some(slopes)
2533        }
2534    }
2535
2536    #[test]
2537    fn a_fit_counts_the_trial_steps_it_rejected_by_the_reason() {
2538        let fit = |slope: f64, floor: f64| {
2539            let mut level = ParameterSet::new(vec![FitParameter::unbounded("level", 50.0)]);
2540            let model = Reversed { slope, floor };
2541            let config = PoissonConfig::default();
2542            poisson_fit(&model, &[100.0; 4], &[], &mut level, &config).unwrap()
2543        };
2544        let impossible = |r: &PoissonResult| (r.rejected.refused, r.rejected.impossible);
2545        let uphill = fit(1.0, f64::NEG_INFINITY);
2546        assert_eq!(uphill.stop, Stop::NoStep);
2547        assert_eq!(impossible(&uphill), (0, 0));
2548        assert!(uphill.rejected.not_lower >= 60, "{uphill:?}");
2549        assert!(
2550            (uphill.decrement.unwrap() - 100.0).abs() < 1e-9,
2551            "{uphill:?}"
2552        );
2553        assert_eq!(impossible(&fit(0.4, f64::NEG_INFINITY)), (0, 1));
2554        let refused = fit(0.4, 45.0);
2555        assert_eq!(impossible(&refused), (3, 0));
2556        assert_eq!(
2557            refused.rejected.reason.as_deref(),
2558            Some("model evaluation failed: below the floor")
2559        );
2560        let observed = decay(1.0).evaluate(&[100.0, 1.5]).unwrap();
2561        let unstarted = fit_decay(&decay(1.0), &observed, (0.0, 1.0), 200);
2562        assert_eq!(unstarted.decrement, None);
2563        assert_eq!(unstarted.rejected, Rejected::default());
2564    }
2565
2566    #[test]
2567    fn a_weak_direction_keeps_its_share_of_the_newton_decrement() {
2568        let model = Affine {
2569            offset: vec![1.0; 2],
2570            jacobian: vec![vec![1.0, 1.0], vec![1.0e-14, -1.0e-14]],
2571        };
2572        for observed in [[0.999, 0.998999], [0.999, 0.999001]] {
2573            let decrement = 0.5
2574                * observed
2575                    .iter()
2576                    .map(|y: &f64| (1.0 - y).powi(2))
2577                    .sum::<f64>();
2578            let result =
2579                poisson_fit(&model, &observed, &[], &mut two_free(), &at_the_start()).unwrap();
2580            assert_eq!(
2581                result.converged,
2582                decrement < NEWTON_DECREMENT_TOL,
2583                "{decrement:e}: {result:?}"
2584            );
2585        }
2586    }
2587
2588    #[test]
2589    fn the_information_inverse_is_poisson_fits_covariance() {
2590        for weak in [0.0, 1.0e-6] {
2591            let jacobian = vec![
2592                vec![1.0, 1.0 + weak, 0.0],
2593                vec![2.0, 2.0, 1.0],
2594                vec![1.0, 1.0, 3.0],
2595                vec![3.0, 3.0 - weak, 1.0],
2596            ];
2597            let model = Affine {
2598                offset: vec![5.0; 4],
2599                jacobian: jacobian.clone(),
2600            };
2601            let mut parameters = ParameterSet::new(
2602                ["a", "b", "c"]
2603                    .map(|name| FitParameter::unbounded(name, 0.0))
2604                    .to_vec(),
2605            );
2606            let result =
2607                poisson_fit(&model, &[5.0; 4], &[], &mut parameters, &at_the_start()).unwrap();
2608            let covariance = result.covariance.expect("covariance");
2609            let information = FlatMatrix {
2610                data: (0..9)
2611                    .map(|e| {
2612                        jacobian
2613                            .iter()
2614                            .map(|row| row[e / 3] * row[e % 3] / 5.0)
2615                            .sum()
2616                    })
2617                    .collect(),
2618                nrows: 3,
2619                ncols: 3,
2620            };
2621            let diagonal: Vec<f64> = (0..3).map(|i| information.get(i, i)).collect();
2622            let inverse = information_inverse(&information, &diagonal, 4).unwrap();
2623            for i in 0..3 {
2624                assert_eq!(
2625                    inverse.resolved[i],
2626                    !covariance.get(i, i).is_nan(),
2627                    "{weak}: {i}"
2628                );
2629                for j in (0..3).filter(|&j| inverse.resolved[i] && inverse.resolved[j]) {
2630                    let (got, expected) = (inverse.determined.get(i, j), covariance.get(i, j));
2631                    assert!(
2632                        (got - expected).abs() <= 1e-9 * expected.abs().max(1.0),
2633                        "{weak}: {got} vs {expected}"
2634                    );
2635                }
2636            }
2637            assert_eq!(inverse.spanned.get(0, 0) > 1e12, weak > 0.0, "{weak}");
2638        }
2639    }
2640
2641    #[test]
2642    fn an_information_with_nothing_determined_inverts_to_zero() {
2643        let inverse = information_inverse(&FlatMatrix::zeros(2, 2), &[0.0; 2], 4).unwrap();
2644        assert!(inverse.spanned.data.iter().all(|&x| x == 0.0));
2645        assert!(inverse.determined.data.iter().all(|&x| x == 0.0));
2646        assert_eq!(inverse.resolved, [false; 2]);
2647        let empty = information_inverse(&FlatMatrix::zeros(0, 0), &[], 4).unwrap();
2648        assert!(empty.resolved.is_empty());
2649    }
2650
2651    #[test]
2652    fn a_direction_the_steps_leave_out_has_no_error_bar() {
2653        let weak = 2.0e-12;
2654        let information = FlatMatrix {
2655            data: vec![1.0, 1.0 - weak, 1.0 - weak, 1.0],
2656            nrows: 2,
2657            ncols: 2,
2658        };
2659        for (rows, determined) in [(4, true), (100_000, false)] {
2660            let inverse = information_inverse(&information, &[1.0; 2], rows).unwrap();
2661            assert_eq!(inverse.resolved, [determined; 2], "{rows}");
2662            assert_eq!(
2663                inverse.undetermined.len(),
2664                usize::from(!determined),
2665                "{rows}"
2666            );
2667        }
2668    }
2669
2670    #[test]
2671    fn a_zero_bin_slope_enters_every_direction_of_the_decrement() {
2672        let jacobian = vec![vec![1.0, 2.0], vec![1.0, 3.0], vec![2.0, -1.0]];
2673        let offset: Vec<f64> = vec![0.0, 4.0, 9.0];
2674        let root = [offset[1].sqrt(), offset[2].sqrt()];
2675        let w = [
2676            [jacobian[1][0] / root[0], jacobian[1][1] / root[0]],
2677            [jacobian[2][0] / root[1], jacobian[2][1] / root[1]],
2678        ];
2679        let information = |a: usize, b: usize| w[0][a] * w[0][b] + w[1][a] * w[1][b];
2680        let inverse_00 =
2681            information(1, 1) / (information(0, 0) * information(1, 1) - information(0, 1).powi(2));
2682        let transpose_det = w[0][0] * w[1][1] - w[1][0] * w[0][1];
2683        for decrement in [0.99e-6_f64, 1.01e-6] {
2684            let gradient = [(2.0 * decrement / inverse_00).sqrt(), 0.0];
2685            let rhs = [gradient[0] - jacobian[0][0], gradient[1] - jacobian[0][1]];
2686            let residual = [
2687                (rhs[0] * w[1][1] - w[1][0] * rhs[1]) / transpose_det,
2688                (w[0][0] * rhs[1] - w[0][1] * rhs[0]) / transpose_det,
2689            ];
2690            let observed = [
2691                0.0,
2692                offset[1] - residual[0] * root[0],
2693                offset[2] - residual[1] * root[1],
2694            ];
2695            let model = Affine {
2696                offset: offset.clone(),
2697                jacobian: jacobian.clone(),
2698            };
2699            let result =
2700                poisson_fit(&model, &observed, &[], &mut two_free(), &at_the_start()).unwrap();
2701            assert_eq!(
2702                result.converged,
2703                decrement < NEWTON_DECREMENT_TOL,
2704                "{decrement:e}: {result:?}"
2705            );
2706        }
2707    }
2708
2709    #[test]
2710    fn a_fit_with_hundreds_of_parameters_has_the_error_bars_of_its_inverse_information() {
2711        use rand::SeedableRng;
2712        use rand_chacha::ChaCha12Rng;
2713        use rand_distr::{Distribution, StandardNormal};
2714        let (bins, count, level) = (300, 150, 1.0e4);
2715        let mut rng = ChaCha12Rng::seed_from_u64(806);
2716        let jacobian: Vec<Vec<f64>> = (0..bins)
2717            .map(|_| {
2718                (0..count)
2719                    .map(|_| StandardNormal.sample(&mut rng))
2720                    .collect()
2721            })
2722            .collect();
2723        let model = Affine {
2724            offset: vec![level; bins],
2725            jacobian: jacobian.clone(),
2726        };
2727        let mut params = ParameterSet::new(
2728            (0..count)
2729                .map(|j| FitParameter::unbounded(format!("c{j}"), 0.0))
2730                .collect(),
2731        );
2732        let result = poisson_fit(
2733            &model,
2734            &vec![level; bins],
2735            &[],
2736            &mut params,
2737            &PoissonConfig::default(),
2738        )
2739        .unwrap();
2740        assert!(result.converged && result.iterations == 0, "{result:?}");
2741        let mut cholesky = vec![vec![0.0; count]; count];
2742        for a in 0..count {
2743            for b in 0..=a {
2744                let information: f64 = jacobian.iter().map(|row| row[a] * row[b] / level).sum();
2745                let rest =
2746                    information - (0..b).map(|c| cholesky[a][c] * cholesky[b][c]).sum::<f64>();
2747                cholesky[a][b] = if a == b {
2748                    rest.sqrt()
2749                } else {
2750                    rest / cholesky[b][b]
2751                };
2752            }
2753        }
2754        for (j, error) in result.uncertainties.unwrap().into_iter().enumerate() {
2755            let mut solved = vec![0.0; count];
2756            for a in 0..count {
2757                let unit = if a == j { 1.0 } else { 0.0 };
2758                solved[a] = (unit - (0..a).map(|c| cholesky[a][c] * solved[c]).sum::<f64>())
2759                    / cholesky[a][a];
2760            }
2761            let expected = solved.iter().map(|v| v * v).sum::<f64>().sqrt();
2762            let error = error.unwrap();
2763            assert!(
2764                (error / expected - 1.0).abs() < 1e-10,
2765                "{j}: {error} vs {expected}"
2766            );
2767        }
2768    }
2769
2770    struct SilentZeroBin;
2771
2772    impl FitModel for SilentZeroBin {
2773        fn evaluate(&self, _params: &[f64]) -> Result<Vec<f64>, FittingError> {
2774            Ok(vec![0.0])
2775        }
2776
2777        fn analytical_jacobian(
2778            &self,
2779            _params: &[f64],
2780            free_param_indices: &[usize],
2781            _y_current: &[f64],
2782        ) -> Option<FlatMatrix> {
2783            let mut jacobian = FlatMatrix::zeros(1, free_param_indices.len());
2784            jacobian.data[0] = f64::NAN;
2785            Some(jacobian)
2786        }
2787    }
2788
2789    #[test]
2790    fn a_non_finite_slope_in_a_zero_bin_ends_the_fit_unconverged() {
2791        let mut params = ParameterSet::new(vec![FitParameter::unbounded("theta", 0.0)]);
2792        let result = poisson_fit(
2793            &SilentZeroBin,
2794            &[0.0],
2795            &[],
2796            &mut params,
2797            &PoissonConfig::default(),
2798        )
2799        .unwrap();
2800        assert!(!result.converged, "{result:?}");
2801    }
2802
2803    struct Wall;
2804
2805    impl FitModel for Wall {
2806        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2807            let x = params[0];
2808            Ok(vec![(100.0 - x + (x - 80.0).max(0.0).powi(2)).exp()])
2809        }
2810
2811        fn analytical_jacobian(
2812            &self,
2813            params: &[f64],
2814            free_param_indices: &[usize],
2815            _y_current: &[f64],
2816        ) -> Option<FlatMatrix> {
2817            let x = params[0];
2818            let mean = (100.0 - x + (x - 80.0).max(0.0).powi(2)).exp();
2819            let mut jacobian = FlatMatrix::zeros(1, free_param_indices.len());
2820            jacobian.data[0] = mean * (2.0 * (x - 80.0).max(0.0) - 1.0);
2821            Some(jacobian)
2822        }
2823    }
2824
2825    #[test]
2826    fn damping_recovers_after_many_accepted_steps_to_reach_the_minimum() {
2827        let mut params = ParameterSet::new(vec![FitParameter::unbounded("x", 0.0)]);
2828        let result =
2829            poisson_fit(&Wall, &[0.0], &[], &mut params, &PoissonConfig::default()).unwrap();
2830        assert!((result.params[0] - 80.5).abs() < 1e-3, "{result:?}");
2831    }
2832
2833    #[test]
2834    fn non_finite_parameter_values_are_refused() {
2835        let model = decay(1.0);
2836        let observed = model.evaluate(&[100.0, 1.5]).unwrap();
2837        for (a, b) in [(f64::NAN, 1.0), (50.0, f64::INFINITY)] {
2838            let mut params = ParameterSet::new(vec![
2839                FitParameter::non_negative("a", a),
2840                FitParameter::fixed("b", b),
2841            ]);
2842            let result = poisson_fit(
2843                &model,
2844                &observed,
2845                &[],
2846                &mut params,
2847                &PoissonConfig::default(),
2848            );
2849            assert!(
2850                matches!(result, Err(FittingError::InvalidConfig(_))),
2851                "{a}, {b}"
2852            );
2853        }
2854    }
2855
2856    /// Counts that follow `script` call by call whatever the parameters, with slopes nearly parallel in bins 0–2.
2857    struct Scripted {
2858        script: Vec<Vec<f64>>,
2859        calls: std::cell::Cell<usize>,
2860    }
2861
2862    impl FitModel for Scripted {
2863        fn evaluate(&self, _: &[f64]) -> Result<Vec<f64>, FittingError> {
2864            let call = self.calls.get();
2865            self.calls.set(call + 1);
2866            Ok(self.script[call.min(self.script.len() - 1)].clone())
2867        }
2868
2869        fn analytical_jacobian(&self, _: &[f64], free: &[usize], _: &[f64]) -> Option<FlatMatrix> {
2870            let mut jacobian = FlatMatrix::zeros(4, free.len());
2871            for (row, slopes) in [[1e4, 1e4], [0.0, 300.0], [1e4, 1e4]].iter().enumerate() {
2872                for (col, &index) in free.iter().enumerate() {
2873                    *jacobian.get_mut(row, col) = slopes[index];
2874                }
2875            }
2876            Some(jacobian)
2877        }
2878    }
2879
2880    #[test]
2881    fn a_failed_trial_is_no_test_once_accepted_steps_have_lowered_the_fit_past_rounding() {
2882        // Bin 1 leaves a decrease along the weak direction only; bin 3 sets the objective's rounding.
2883        let observed = [1e8, 1e8 + 316.0, 1e8, 1.1e4];
2884        let at = |ulps: u64| vec![1e8, 1e8, 1e8, f64::from_bits(1e4_f64.to_bits() + ulps)];
2885        let value = |ulps: u64| objective(&observed, &at(ulps), &[], &two_free());
2886        let resolved = f64::EPSILON * (4.0 * value(0) + 1e3 + 316.0);
2887        // Fifteen steps, each lowering the fit by under 0.9 of its rounding.
2888        let mut steps = vec![0];
2889        for ulps in 1..100 {
2890            let last = value(*steps.last().unwrap());
2891            if steps.len() < 16 && value(ulps) < last && last - value(ulps) < 0.9 * resolved {
2892                steps.push(ulps);
2893            }
2894        }
2895        assert!(
2896            steps.len() == 16 && value(0) - value(steps[2]) > resolved,
2897            "{steps:?}"
2898        );
2899        // A trial that rises, then those steps, then none lowers the fit.
2900        let rise = [vec![9.9e7], at(0)[1..].to_vec()].concat();
2901        let model = Scripted {
2902            script: [
2903                vec![at(0), rise],
2904                steps[1..].iter().map(|&k| at(k)).collect(),
2905            ]
2906            .concat(),
2907            calls: std::cell::Cell::new(0),
2908        };
2909        let fit = poisson_fit(
2910            &model,
2911            &observed,
2912            &[],
2913            &mut two_free(),
2914            &PoissonConfig::default(),
2915        )
2916        .unwrap();
2917        assert_eq!(fit.stop, Stop::NoStep, "{:?} {:?}", fit.rejected, fit.own);
2918        assert!(
2919            fit.iterations == 15 && fit.own.unwrap().1 < NEWTON_DECREMENT_TOL,
2920            "{:?} {:?}",
2921            fit.iterations,
2922            fit.own
2923        );
2924        assert!(fit.rejected.tested.is_none(), "{:?}", fit.rejected);
2925    }
2926
2927    struct Shrinking;
2928
2929    impl FitModel for Shrinking {
2930        fn evaluate(&self, params: &[f64]) -> Result<Vec<f64>, FittingError> {
2931            let bins = if params[0] < 0.5 { 3 } else { 2 };
2932            Ok(vec![1.0 + params[0]; bins])
2933        }
2934
2935        fn analytical_jacobian(
2936            &self,
2937            params: &[f64],
2938            free_param_indices: &[usize],
2939            _y_current: &[f64],
2940        ) -> Option<FlatMatrix> {
2941            let bins = if params[0] < 0.5 { 3 } else { 2 };
2942            let mut jacobian = FlatMatrix::zeros(bins, free_param_indices.len());
2943            jacobian.data.fill(1.0);
2944            Some(jacobian)
2945        }
2946    }
2947
2948    #[test]
2949    fn a_trial_prediction_of_the_wrong_length_is_rejected() {
2950        let mut params = ParameterSet::new(vec![FitParameter::non_negative("theta", 0.0)]);
2951        let result = poisson_fit(
2952            &Shrinking,
2953            &[3.0; 3],
2954            &[],
2955            &mut params,
2956            &PoissonConfig::default(),
2957        )
2958        .unwrap();
2959        assert_eq!(
2960            Shrinking.evaluate(&result.params).unwrap().len(),
2961            3,
2962            "{result:?}"
2963        );
2964    }
2965}