1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//! Hotelling T-squared and SPE (Squared Prediction Error) statistics.
//!
//! These are the two fundamental monitoring statistics for functional
//! statistical process control: T-squared captures systematic variation
//! in the principal component subspace, while SPE captures residual
//! variation outside it.
//!
//! # Finite-sample distribution
//!
//! For finite calibration samples of size *n*, T² follows
//! `(n·ncomp/(n−ncomp))·F(ncomp, n−ncomp)` exactly under Gaussian scores.
//! The `χ²(ncomp)` limit is the large-sample limit as *n* → ∞.
//!
//! # Numerical stability
//!
//! If the ratio `max(eigenvalue)/min(eigenvalue)` exceeds ~10^6, the T²
//! statistic becomes numerically sensitive. Use [`hotelling_t2_regularized`]
//! in such cases.
//!
//! # Quadrature
//!
//! The Simpson's rule quadrature used for SPE integration has error
//! O(h^4 * max|f''''|) where h is the grid spacing, giving excellent
//! accuracy for smooth functional data.
//!
//! # References
//!
//! - Hotelling, H. (1947). Multivariate quality control. *Techniques of
//! Statistical Analysis*, pp. 111–113.
//! - Bersimis, S., Psarakis, S. & Panaretos, J. (2007). Multivariate
//! statistical process control charts: an overview. *Quality and
//! Reliability Engineering International*, 23(5), 517–543. §2.1,
//! pp. 519–522.
//!
//! # Assumptions
//!
//! The statistics in this module assume the FPCA scores are approximately
//! uncorrelated (diagonal covariance). This holds by construction when
//! eigenvalues come from PCA/SVD. For non-PCA score vectors, use the full
//! covariance Mahalanobis distance instead.
use crateFdarError;
use cratesimpsons_weights;
use crateFdMatrix;
/// Compute Hotelling T-squared statistic for each observation.
///
/// T-squared_i = sum_{l=1}^{L} scores_{i,l}^2 / eigenvalues_l
///
/// Under in-control conditions with Gaussian scores, T² follows
/// approximately a chi²(ncomp) distribution (Hotelling, 1947, pp. 111–113).
/// For finite calibration samples of size *n*, T² follows
/// `(n·ncomp/(n−ncomp))·F(ncomp, n−ncomp)` exactly under Gaussian scores.
/// The `χ²(ncomp)` limit is the large-sample limit as *n* → ∞.
///
/// Use [`t2_control_limit`](super::control::t2_control_limit) to obtain the
/// corresponding upper control limit.
///
/// # Numerical stability
///
/// If the ratio `max(eigenvalue)/min(eigenvalue)` exceeds ~10^6, the T²
/// statistic becomes numerically sensitive. Use [`hotelling_t2_regularized`]
/// in such cases.
///
/// # Arguments
/// * `scores` - FPC score matrix (n x ncomp)
/// * `eigenvalues` - Eigenvalues (length ncomp): sv_l^2 / (n-1)
///
/// # Example
///
/// ```
/// use fdars_core::matrix::FdMatrix;
/// use fdars_core::spm::stats::hotelling_t2;
/// let scores = FdMatrix::from_column_major(vec![1.0, 2.0, 3.0, 0.5, 1.0, 1.5], 3, 2).unwrap();
/// let eigenvalues = vec![2.0, 1.0];
/// let t2 = hotelling_t2(&scores, &eigenvalues).unwrap();
/// assert_eq!(t2.len(), 3);
/// assert!((t2[0] - 0.75).abs() < 1e-10); // 1²/2 + 0.5²/1
/// ```
///
/// # Errors
///
/// Returns [`FdarError::InvalidDimension`] if scores columns != eigenvalues length.
/// Returns [`FdarError::InvalidParameter`] if any eigenvalue is non-positive.
/// Compute Hotelling T-squared with eigenvalue regularization.
///
/// Like [`hotelling_t2`], but applies a floor to eigenvalues to prevent
/// numerical instability from near-zero values. Useful when some
/// eigenvalues are very small (< 1e-8) which would cause numerical
/// instability in standard T². The epsilon floor prevents division by
/// near-zero eigenvalues.
///
/// # Condition number
///
/// If the ratio `max(eigenvalue)/min(eigenvalue)` exceeds ~10^6, the
/// standard T² statistic becomes numerically sensitive. This function
/// clamps small eigenvalues to `epsilon`, effectively bounding the
/// condition number at `max(eigenvalue)/epsilon`.
///
/// Choosing epsilon: set epsilon approximately 1e-2 times the minimum
/// eigenvalue to regularize without substantially altering the statistic.
/// The default regularization in `spm_monitor` uses this approach. For
/// manual use, epsilon = 1e-6 is a safe general-purpose default that
/// handles eigenvalue ratios up to 1e6.
///
/// # Arguments
/// * `scores` - Score matrix (n x ncomp)
/// * `eigenvalues` - Eigenvalues (length ncomp)
/// * `epsilon` - Minimum eigenvalue floor (values below this are set to epsilon)
///
/// # Errors
///
/// Returns [`FdarError::InvalidDimension`] if shapes are inconsistent.
/// Returns [`FdarError::InvalidParameter`] if epsilon is non-positive.
/// Compute SPE (Squared Prediction Error) for univariate functional data.
///
/// SPE_i = integral (x_centered_i(t) - x_reconstructed_i(t))^2 w(t) dt
///
/// Requires `argvals` to be sorted in ascending order with at least 3
/// points for Simpson's rule integration. Non-uniform spacing is handled
/// correctly by the quadrature weights.
///
/// # Quadrature accuracy
///
/// The Simpson's rule quadrature has error O(h^4 * max|f''''|) where h is
/// the grid spacing, giving excellent accuracy for smooth functional data
/// (Bersimis et al., 2007, §2.1, pp. 519–522).
///
/// # Arguments
/// * `centered` - Centered functional data (n x m)
/// * `reconstructed` - Reconstructed data from FPCA (n x m), already centered (mean subtracted)
/// * `argvals` - Grid points (length m)
///
/// # Example
///
/// ```
/// use fdars_core::matrix::FdMatrix;
/// use fdars_core::spm::stats::spe_univariate;
/// let centered = FdMatrix::from_column_major(vec![1.0, 0.0, 0.0, 1.0], 2, 2).unwrap();
/// let reconstructed = FdMatrix::from_column_major(vec![0.0; 4], 2, 2).unwrap();
/// let argvals = vec![0.0, 1.0];
/// let spe = spe_univariate(¢ered, &reconstructed, &argvals).unwrap();
/// assert_eq!(spe.len(), 2);
/// assert!(spe[0] > 0.0);
/// ```
///
/// # Errors
///
/// Returns [`FdarError::InvalidDimension`] if shapes do not match.
/// Compute SPE for multivariate functional data.
///
/// Sum of per-variable integrated squared differences, each variable using
/// its own grid-specific integration weights. Each entry in `argvals_list`
/// must be sorted in ascending order with at least 3 points for Simpson's
/// rule integration. Non-uniform spacing is handled correctly by the
/// quadrature weights.
///
/// # Quadrature accuracy
///
/// Each variable's contribution uses Simpson's rule with error
/// O(h^4 * max|f''''|) where h is the per-variable grid spacing.
///
/// # Arguments
/// * `standardized_vars` - Per-variable standardized centered data (each n x m_p)
/// * `reconstructed_vars` - Per-variable reconstructed data (each n x m_p)
/// * `argvals_list` - Per-variable grid points
///
/// # Errors
///
/// Returns [`FdarError::InvalidDimension`] if the number of variables is inconsistent
/// or any shapes do not match.