nyx_space/od/process/solution/
stats.rs1use crate::linalg::allocator::Allocator;
20use crate::linalg::{DefaultAllocator, DimName};
21use crate::md::trajectory::Interpolatable;
22pub use crate::od::estimate::*;
23pub use crate::od::*;
24use log::warn;
25use msr::sensitivity::TrackerSensitivity;
26use statrs::distribution::{ContinuousCDF, Normal};
27use std::ops::Add;
28
29use super::ODSolution;
30
31impl<StateType, EstType, MsrSize, Trk> ODSolution<StateType, EstType, MsrSize, Trk>
32where
33 StateType: Interpolatable + Add<OVector<f64, <StateType as State>::Size>, Output = StateType>,
34 EstType: Estimate<StateType>,
35 MsrSize: DimName,
36 Trk: TrackerSensitivity<StateType, StateType>,
37 <DefaultAllocator as Allocator<<StateType as State>::VecLength>>::Buffer<f64>: Send,
38 DefaultAllocator: Allocator<<StateType as State>::Size>
39 + Allocator<<StateType as State>::VecLength>
40 + Allocator<MsrSize>
41 + Allocator<MsrSize, <StateType as State>::Size>
42 + Allocator<MsrSize, MsrSize>
43 + Allocator<<StateType as State>::Size, <StateType as State>::Size>
44 + Allocator<<StateType as State>::Size, MsrSize>,
45{
46 pub fn rms_prefit_residuals(&self) -> f64 {
48 let mut sum = 0.0;
49 for residual in self.residuals.iter().flatten() {
50 sum += residual.prefit.dot(&residual.prefit);
51 }
52 (sum / (self.residuals.len() as f64)).sqrt()
53 }
54
55 pub fn rms_postfit_residuals(&self) -> f64 {
57 let mut sum = 0.0;
58 for residual in self.residuals.iter().flatten() {
59 sum += residual.postfit.dot(&residual.postfit);
60 }
61 (sum / (self.residuals.len() as f64)).sqrt()
62 }
63
64 pub fn rms_residual_ratios(&self) -> f64 {
66 let mut sum = 0.0;
67 for residual in self.residuals.iter().flatten() {
68 sum += residual.ratio.powi(2);
69 }
70 (sum / (self.residuals.len() as f64)).sqrt()
71 }
72
73 pub fn residual_ratio_within_threshold(&self, threshold: f64) -> Result<f64, ODError> {
75 let mut total = 0;
76 let mut count_within = 0;
77 for residual in self.residuals.iter().flatten() {
78 total += 1;
79 if residual.ratio.abs() <= threshold {
80 count_within += 1;
81 }
82 }
83 if total > 0 {
84 Ok(count_within as f64 / total as f64)
85 } else {
86 Err(ODError::ODNoResiduals {
87 action: "percentage of residuals within threshold",
88 })
89 }
90 }
91
92 pub fn ks_test_normality(&self) -> Result<f64, ODError> {
96 let mut residual_ratios = self
97 .accepted_residuals()
98 .iter()
99 .flat_map(|resid| resid.whitened_resid.into_iter().copied())
100 .collect::<Vec<f64>>();
101
102 if residual_ratios.is_empty() {
103 return Err(ODError::ODNoResiduals {
104 action: "percentage of residuals within threshold",
105 });
106 }
107 residual_ratios.sort_by(|a, b| a.partial_cmp(b).unwrap());
108 let n = residual_ratios.len() as f64;
109 let mean = residual_ratios.iter().sum::<f64>() / n;
110 let variance = residual_ratios
111 .iter()
112 .map(|v| (v - mean).powi(2))
113 .sum::<f64>()
114 / n;
115 let std_dev = variance.sqrt();
116
117 let normal_dist = Normal::new(mean, std_dev).unwrap();
119
120 let mut d_stat = 0.0;
122 for (i, &value) in residual_ratios.iter().enumerate() {
123 let empirical_cdf = (i + 1) as f64 / n;
124 let model_cdf = normal_dist.cdf(value);
125 let diff = (empirical_cdf - model_cdf).abs();
126 if diff > d_stat {
127 d_stat = diff;
128 }
129 }
130 Ok(d_stat)
131 }
132
133 pub fn is_normal(&self, alpha: Option<f64>) -> Result<bool, ODError> {
145 let n = self.residuals.iter().flatten().count();
146 if n == 0 {
147 return Err(ODError::ODNoResiduals {
148 action: "evaluating residual normality",
149 });
150 } else if n < 35 {
151 warn!("KS normality test unreliable for n={n} < 35; skipping");
152 }
153 let ks_stat = self.ks_test_normality()?;
154
155 let alpha = alpha.unwrap_or(0.05);
157
158 let c_alpha = (-(alpha * 0.5).ln() * 0.5).sqrt();
160
161 let d_critical = c_alpha / (n as f64).sqrt();
162
163 Ok(ks_stat <= d_critical)
164 }
165
166 pub fn is_nis_consistent(&self, alpha: Option<f64>) -> Result<bool, ODError> {
181 let n = self.accepted_residuals().iter().count();
182
183 if n == 0 {
184 return Err(ODError::ODNoResiduals {
185 action: "evaluating NIS consistency",
186 });
187 }
188
189 let nis_sum: f64 = self.accepted_residuals().iter().map(|r| r.nis()).sum();
193
194 let k = (n * MsrSize::DIM) as f64;
197 if k < 35.0 {
198 warn!("NIS consistency test lacks statistical power for n*MsrSize={k} < 35");
199 }
200 let alpha = alpha.unwrap_or(0.05);
202
203 let z_critical = Normal::new(0.0, 1.0)
206 .unwrap()
207 .inverse_cdf(1.0 - alpha / 2.0);
208
209 let factor = 2.0 / (9.0 * k);
212 let lower_bound = k * (1.0 - factor - z_critical * factor.sqrt()).powi(3);
213 let upper_bound = k * (1.0 - factor + z_critical * factor.sqrt()).powi(3);
214
215 if nis_sum > upper_bound {
216 warn!("NIS consistency test failed high: NIS sum {nis_sum:.6} > upper bound {upper_bound:.6}. Innovations are larger than expected.");
217 warn!("Filter may be overconfident: P, R, or Q may be too small, or the dynamics/measurement model may be biased.");
218 Ok(false)
219 } else if nis_sum < lower_bound {
220 warn!("NIS consistency test failed low: NIS sum {nis_sum:.6} < lower bound {lower_bound:.6}. Innovations are smaller than expected.");
221 warn!("Filter may be underconfident: P, R, or Q may be too large.");
222 Ok(false)
223 } else {
224 Ok(true)
225 }
226 }
227}