Skip to main content

fpm_rs/model/
mixing.rs

1//! Numerical diagnostics of the declared spectral exposure weights.
2use crate::{Error, Result};
3use ndarray::Array2;
4
5/// Linear weight diagnostics in detector-row and stable channel order.
6/// These omit spatial forward operators and do not prove nonlinear recoverability.
7#[derive(Clone, Debug)]
8pub struct SpectralMixingDiagnostics {
9    /// Stable IDs corresponding to matrix columns.
10    pub channel_ids: Vec<String>,
11    /// Effective mode weights, shaped `(detector frames, channels)`.
12    pub matrix: Array2<f64>,
13    /// Descending singular values; length `min(frames, channels)`.
14    pub singular_values: Vec<f64>,
15    /// Number of singular values strictly above the absolute tolerance.
16    pub rank: usize,
17    /// Dimensionless threshold relative to the largest singular value.
18    pub relative_tolerance: f64,
19    /// Singular-value threshold in matrix-weight units.
20    pub absolute_tolerance: f64,
21    /// Largest/smallest singular value when columns have full numerical rank.
22    /// None for deficient column rank or an unrepresentable binary64 ratio.
23    pub condition_number: Option<f64>,
24}
25
26pub(super) fn diagnose(
27    channel_ids: Vec<String>,
28    matrix: Array2<f64>,
29    tolerance: Option<f64>,
30) -> Result<SpectralMixingDiagnostics> {
31    let relative_tolerance =
32        tolerance.unwrap_or(matrix.nrows().max(matrix.ncols()) as f64 * f64::EPSILON);
33    if !relative_tolerance.is_finite()
34        || relative_tolerance < 0.0
35        || matrix.iter().any(|v| !v.is_finite())
36    {
37        return Err(Error::InvalidParameter {
38            name: "mixing_tolerance",
39            reason: "matrix and nonnegative relative tolerance must be finite".into(),
40        });
41    }
42    let singular_values = singular_values(&matrix)?;
43    let largest = singular_values.first().copied().unwrap_or(0.0);
44    let absolute_tolerance = largest * relative_tolerance;
45    if !absolute_tolerance.is_finite() {
46        return Err(Error::InvalidParameter {
47            name: "mixing_tolerance",
48            reason: "absolute tolerance overflows binary64".into(),
49        });
50    }
51    let rank = singular_values
52        .iter()
53        .filter(|&&s| s > absolute_tolerance)
54        .count();
55    let condition_number = if rank == matrix.ncols() {
56        singular_values
57            .last()
58            .map(|s| largest / s)
59            .filter(|v| v.is_finite())
60    } else {
61        None
62    };
63    Ok(SpectralMixingDiagnostics {
64        channel_ids,
65        matrix,
66        singular_values,
67        rank,
68        relative_tolerance,
69        absolute_tolerance,
70        condition_number,
71    })
72}
73
74fn singular_values(matrix: &Array2<f64>) -> Result<Vec<f64>> {
75    let scale = matrix.iter().fold(0.0_f64, |a, &b| a.max(b.abs()));
76    let count = matrix.nrows().min(matrix.ncols());
77    if scale == 0.0 {
78        return Ok(vec![0.0; count]);
79    }
80    let mut a = if matrix.nrows() >= matrix.ncols() {
81        matrix.clone()
82    } else {
83        matrix.t().to_owned()
84    };
85    a.mapv_inplace(|v| v / scale);
86    // Cyclic one-sided Jacobi, following the column-orthogonalization formulation
87    // documented by LAPACK DGESVJ. Scaling avoids forming a poorly conditioned Gram matrix.
88    let mut converged = false;
89    for _ in 0..100 {
90        let mut changed = false;
91        for p in 0..count {
92            for q in p + 1..count {
93                let norm_p = a.column(p).iter().fold(0.0_f64, |n, &v| n.hypot(v));
94                let norm_q = a.column(q).iter().fold(0.0_f64, |n, &v| n.hypot(v));
95                if norm_p == 0.0 || norm_q == 0.0 {
96                    continue;
97                }
98                let correlation = a
99                    .column(p)
100                    .iter()
101                    .zip(a.column(q))
102                    .map(|(&x, &y)| (x / norm_p) * (y / norm_q))
103                    .sum::<f64>();
104                if correlation.abs() <= 8.0 * f64::EPSILON {
105                    continue;
106                }
107                let pair_scale = norm_p.max(norm_q);
108                let p_scaled = norm_p / pair_scale;
109                let q_scaled = norm_q / pair_scale;
110                let delta = (q_scaled * q_scaled - p_scaled * p_scaled) / 2.0;
111                let cross = correlation * p_scaled * q_scaled;
112                // This form avoids dividing by a tiny off-diagonal entry and
113                // overflowing the tangent parameter for strongly unequal columns.
114                let t = if delta == 0.0 {
115                    1.0
116                } else {
117                    cross / (delta + delta.hypot(cross).copysign(delta))
118                };
119                let c = 1.0 / t.hypot(1.0);
120                let s = c * t;
121                for row in 0..a.nrows() {
122                    let x = a[[row, p]];
123                    let y = a[[row, q]];
124                    a[[row, p]] = c * x - s * y;
125                    a[[row, q]] = s * x + c * y;
126                }
127                changed = true;
128            }
129        }
130        if !changed {
131            converged = true;
132            break;
133        }
134    }
135    if !converged {
136        return Err(Error::InvalidParameter {
137            name: "mixing_matrix",
138            reason: "Jacobi singular values did not converge within 100 sweeps".into(),
139        });
140    }
141    let mut values: Vec<f64> = a
142        .columns()
143        .into_iter()
144        .map(|column| column.iter().fold(0.0_f64, |norm, &v| norm.hypot(v)) * scale)
145        .collect();
146    if values.iter().any(|v| !v.is_finite()) {
147        return Err(Error::InvalidParameter {
148            name: "mixing_matrix",
149            reason: "singular values overflow binary64".into(),
150        });
151    }
152    values.sort_by(|a, b| b.total_cmp(a));
153    Ok(values)
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use ndarray::array;
160    #[test]
161    fn rank_condition_scale_and_wide_matrix() {
162        for scale in [1e-200, 1.0, 1e200] {
163            let d = diagnose(
164                vec![],
165                array![[3.0, 0.0], [0.0, 1.0], [0.0, 0.0]] * scale,
166                None,
167            )
168            .unwrap();
169            assert_eq!(d.rank, 2);
170            assert!((d.condition_number.unwrap() - 3.0).abs() < 1e-13);
171            let d = diagnose(
172                vec![],
173                array![[1.0, 2.0, 3.0], [2.0, 4.0, 6.0]] * scale,
174                None,
175            )
176            .unwrap();
177            assert_eq!(d.rank, 1);
178            assert_eq!(d.condition_number, None);
179        }
180        let tiny = diagnose(vec![], array![[1.0, 1e-200], [0.0, 1e-200]], None).unwrap();
181        assert_eq!(tiny.rank, 1);
182        assert!((tiny.singular_values[1] / 1e-200 - 1.0).abs() < 1e-14);
183        let a = array![[1.0, 1.0], [0.0, 1e-10]];
184        let d = diagnose(vec![], a.clone(), None).unwrap();
185        assert_eq!(d.rank, 2);
186        assert!((d.condition_number.unwrap() / 2e10 - 1.0).abs() < 1e-10);
187        assert_eq!(diagnose(vec![], a, Some(1e-8)).unwrap().rank, 1);
188        assert!(diagnose(vec![], array![[1.0]], Some(-1.0)).is_err());
189    }
190}