Skip to main content

fdars_core/
utility.rs

1//! Utility functions for functional data analysis.
2
3use crate::helpers::simpsons_weights;
4use crate::iter_maybe_parallel;
5use crate::matrix::FdMatrix;
6#[cfg(feature = "parallel")]
7use rayon::iter::ParallelIterator;
8use std::f64::consts::PI;
9
10/// Compute Simpson's rule integration for a single function.
11///
12/// # Arguments
13/// * `values` - Function values at evaluation points
14/// * `argvals` - Evaluation points
15pub fn integrate_simpson(values: &[f64], argvals: &[f64]) -> f64 {
16    if values.len() != argvals.len() || values.is_empty() {
17        return 0.0;
18    }
19
20    let weights = simpsons_weights(argvals);
21    values
22        .iter()
23        .zip(weights.iter())
24        .map(|(&v, &w)| v * w)
25        .sum()
26}
27
28/// Compute inner product between two functional data curves.
29///
30/// # Arguments
31/// * `curve1` - First curve values
32/// * `curve2` - Second curve values
33/// * `argvals` - Evaluation points
34pub fn inner_product(curve1: &[f64], curve2: &[f64], argvals: &[f64]) -> f64 {
35    if curve1.len() != curve2.len() || curve1.len() != argvals.len() || curve1.is_empty() {
36        return 0.0;
37    }
38
39    let weights = simpsons_weights(argvals);
40    curve1
41        .iter()
42        .zip(curve2.iter())
43        .zip(weights.iter())
44        .map(|((&c1, &c2), &w)| c1 * c2 * w)
45        .sum()
46}
47
48/// Compute inner product matrix for functional data.
49///
50/// # Arguments
51/// * `data` - Matrix of observations (n rows) x evaluation points (m cols)
52/// * `argvals` - Evaluation points
53///
54/// # Returns
55/// Symmetric inner product matrix (n x n)
56pub fn inner_product_matrix(data: &FdMatrix, argvals: &[f64]) -> FdMatrix {
57    let n = data.nrows();
58    let m = data.ncols();
59
60    if n == 0 || m == 0 || argvals.len() != m {
61        return FdMatrix::zeros(0, 0);
62    }
63
64    let weights = simpsons_weights(argvals);
65
66    // Compute upper triangle (parallel when feature enabled)
67    let upper_triangle: Vec<(usize, usize, f64)> = iter_maybe_parallel!(0..n)
68        .flat_map(|i| {
69            (i..n)
70                .map(|j| {
71                    let mut ip = 0.0;
72                    for k in 0..m {
73                        ip += data[(i, k)] * data[(j, k)] * weights[k];
74                    }
75                    (i, j, ip)
76                })
77                .collect::<Vec<_>>()
78        })
79        .collect();
80
81    // Build symmetric matrix
82    let mut result = FdMatrix::zeros(n, n);
83    for (i, j, ip) in upper_triangle {
84        result[(i, j)] = ip;
85        result[(j, i)] = ip;
86    }
87
88    result
89}
90
91/// Compute the Adot matrix used in PCvM statistic.
92/// Packed symmetric index for 1-based indices in lower-triangular storage.
93fn packed_sym_index(a: usize, b: usize) -> usize {
94    let (hi, lo) = if a >= b { (a, b) } else { (b, a) };
95    hi * (hi - 1) / 2 + lo - 1
96}
97
98/// Compute the angular distance sum for a single (i, j) pair over all reference points.
99fn adot_pair_sum(inprod: &[f64], n: usize, i: usize, j: usize) -> f64 {
100    let ij = packed_sym_index(i, j);
101    let ii = packed_sym_index(i, i);
102    let jj = packed_sym_index(j, j);
103    let mut sumr = 0.0;
104
105    for r in 1..=n {
106        if i == r || j == r {
107            sumr += PI;
108        } else {
109            let rr = packed_sym_index(r, r);
110            let ir = packed_sym_index(i, r);
111            let rj = packed_sym_index(r, j);
112
113            let num = inprod[ij] - inprod[ir] - inprod[rj] + inprod[rr];
114            let aux1 = (inprod[ii] - 2.0 * inprod[ir] + inprod[rr]).sqrt();
115            let aux2 = (inprod[jj] - 2.0 * inprod[rj] + inprod[rr]).sqrt();
116            let den = aux1 * aux2;
117
118            let mut quo = if den.abs() > 1e-10 { num / den } else { 0.0 };
119            quo = quo.clamp(-1.0, 1.0);
120
121            sumr += (PI - quo.acos()).abs();
122        }
123    }
124
125    sumr
126}
127
128pub fn compute_adot(n: usize, inprod: &[f64]) -> Vec<f64> {
129    if n == 0 {
130        return Vec::new();
131    }
132
133    let expected_len = (n * n + n) / 2;
134    if inprod.len() != expected_len {
135        return Vec::new();
136    }
137
138    let out_len = (n * n - n + 2) / 2;
139    let mut adot_vec = vec![0.0; out_len];
140
141    adot_vec[0] = PI * (n + 1) as f64;
142
143    // Collect all (i, j) pairs for parallel processing
144    let pairs: Vec<(usize, usize)> = (2..=n).flat_map(|i| (1..i).map(move |j| (i, j))).collect();
145
146    // Compute adot values (parallel when feature enabled)
147    let results: Vec<(usize, f64)> = iter_maybe_parallel!(pairs)
148        .map(|(i, j)| {
149            let sumr = adot_pair_sum(inprod, n, i, j);
150            let idx = 1 + ((i - 1) * (i - 2) / 2) + j - 1;
151            (idx, sumr)
152        })
153        .collect();
154
155    // Fill in the results
156    for (idx, val) in results {
157        if idx < adot_vec.len() {
158            adot_vec[idx] = val;
159        }
160    }
161
162    adot_vec
163}
164
165/// Compute the PCvM statistic.
166pub fn pcvm_statistic(adot_vec: &[f64], residuals: &[f64]) -> f64 {
167    let n = residuals.len();
168
169    if n == 0 || adot_vec.is_empty() {
170        return 0.0;
171    }
172
173    let mut sums = 0.0;
174    for i in 2..=n {
175        for j in 1..i {
176            let idx = 1 + ((i - 1) * (i - 2) / 2) + j - 1;
177            if idx < adot_vec.len() {
178                sums += residuals[i - 1] * adot_vec[idx] * residuals[j - 1];
179            }
180        }
181    }
182
183    let diag_sum: f64 = residuals.iter().map(|r| r * r).sum();
184    adot_vec[0] * diag_sum + 2.0 * sums
185}
186
187/// Result of random projection statistics.
188pub struct RpStatResult {
189    /// CvM statistics for each projection
190    pub cvm: Vec<f64>,
191    /// KS statistics for each projection
192    pub ks: Vec<f64>,
193}
194
195/// Compute random projection statistics.
196pub fn rp_stat(proj_x_ord: &[i32], residuals: &[f64], n_proj: usize) -> RpStatResult {
197    let n = residuals.len();
198
199    if n == 0 || n_proj == 0 || proj_x_ord.len() != n * n_proj {
200        return RpStatResult {
201            cvm: Vec::new(),
202            ks: Vec::new(),
203        };
204    }
205
206    // Process projections (parallel when feature enabled)
207    let stats: Vec<(f64, f64)> = iter_maybe_parallel!(0..n_proj)
208        .map(|p| {
209            let mut y = vec![0.0; n];
210            let mut cumsum = 0.0;
211
212            for i in 0..n {
213                let idx = proj_x_ord[p * n + i] as usize;
214                if idx > 0 && idx <= n {
215                    cumsum += residuals[idx - 1];
216                }
217                y[i] = cumsum;
218            }
219
220            let sum_y_sq: f64 = y.iter().map(|yi| yi * yi).sum();
221            let cvm = sum_y_sq / (n * n) as f64;
222
223            let max_abs_y = y.iter().map(|yi| yi.abs()).fold(0.0, f64::max);
224            let ks = max_abs_y / (n as f64).sqrt();
225
226            (cvm, ks)
227        })
228        .collect();
229
230    let cvm_stats: Vec<f64> = stats.iter().map(|(cvm, _)| *cvm).collect();
231    let ks_stats: Vec<f64> = stats.iter().map(|(_, ks)| *ks).collect();
232
233    RpStatResult {
234        cvm: cvm_stats,
235        ks: ks_stats,
236    }
237}
238
239/// k-NN prediction for functional regression.
240///
241/// # Arguments
242/// * `distance_matrix` - Distance matrix (n_test rows x n_train cols)
243/// * `y` - Training response values (length n_train)
244/// * `k` - Number of nearest neighbors
245pub fn knn_predict(distance_matrix: &FdMatrix, y: &[f64], k: usize) -> Vec<f64> {
246    let n_test = distance_matrix.nrows();
247    let n_train = distance_matrix.ncols();
248
249    if n_train == 0 || n_test == 0 || k == 0 || y.len() != n_train {
250        return vec![0.0; n_test];
251    }
252
253    let k = k.min(n_train);
254
255    iter_maybe_parallel!(0..n_test)
256        .map(|i| {
257            // Get distances from test point i to all training points
258            let mut distances: Vec<(usize, f64)> =
259                (0..n_train).map(|j| (j, distance_matrix[(i, j)])).collect();
260
261            // Sort by distance
262            distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
263
264            // Average of k nearest neighbors
265            let sum: f64 = distances.iter().take(k).map(|(j, _)| y[*j]).sum();
266            sum / k as f64
267        })
268        .collect()
269}
270
271/// Compute leave-one-out cross-validation error for k-NN.
272///
273/// # Arguments
274/// * `distance_matrix` - Square distance matrix (n x n)
275/// * `y` - Response values (length n)
276/// * `k` - Number of nearest neighbors
277pub fn knn_loocv(distance_matrix: &FdMatrix, y: &[f64], k: usize) -> f64 {
278    let n = distance_matrix.nrows();
279
280    if n == 0 || k == 0 || y.len() != n || distance_matrix.ncols() != n {
281        return f64::INFINITY;
282    }
283
284    let k = k.min(n - 1);
285
286    let errors: Vec<f64> = iter_maybe_parallel!(0..n)
287        .map(|i| {
288            // Get distances from point i to all other points
289            let mut distances: Vec<(usize, f64)> = (0..n)
290                .filter(|&j| j != i)
291                .map(|j| (j, distance_matrix[(i, j)]))
292                .collect();
293
294            // Sort by distance
295            distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
296
297            // Prediction
298            let pred: f64 = distances.iter().take(k).map(|(j, _)| y[*j]).sum::<f64>() / k as f64;
299
300            // Squared error
301            (y[i] - pred).powi(2)
302        })
303        .collect();
304
305    errors.iter().sum::<f64>() / n as f64
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    fn uniform_grid(n: usize) -> Vec<f64> {
313        (0..n).map(|i| i as f64 / (n - 1) as f64).collect()
314    }
315
316    #[test]
317    fn test_integrate_simpson_constant() {
318        let argvals = uniform_grid(11);
319        let values = vec![1.0; 11];
320        let result = integrate_simpson(&values, &argvals);
321        assert!((result - 1.0).abs() < 1e-10);
322    }
323
324    #[test]
325    fn test_inner_product_orthogonal() {
326        let argvals = uniform_grid(101);
327        let curve1: Vec<f64> = argvals.iter().map(|&t| (2.0 * PI * t).sin()).collect();
328        let curve2: Vec<f64> = argvals.iter().map(|&t| (2.0 * PI * t).cos()).collect();
329        let result = inner_product(&curve1, &curve2, &argvals);
330        assert!(result.abs() < 0.01);
331    }
332
333    #[test]
334    fn test_inner_product_matrix_symmetry() {
335        let n = 5;
336        let m = 10;
337        let argvals = uniform_grid(m);
338        let data: Vec<f64> = (0..n * m).map(|i| (i as f64).sin()).collect();
339        let mat = FdMatrix::from_column_major(data, n, m).unwrap();
340
341        let matrix = inner_product_matrix(&mat, &argvals);
342
343        for i in 0..n {
344            for j in 0..n {
345                let diff = (matrix[(i, j)] - matrix[(j, i)]).abs();
346                assert!(diff < 1e-10, "Matrix should be symmetric");
347            }
348        }
349    }
350
351    #[test]
352    fn test_knn_predict() {
353        let n_train = 10;
354        let n_test = 3;
355        let k = 3;
356
357        let mut distance_data = vec![0.0; n_test * n_train];
358        for i in 0..n_test {
359            for j in 0..n_train {
360                distance_data[i + j * n_test] = ((i as f64) - (j as f64)).abs();
361            }
362        }
363        let distance_matrix = FdMatrix::from_column_major(distance_data, n_test, n_train).unwrap();
364
365        let y: Vec<f64> = (0..n_train).map(|i| i as f64).collect();
366        let predictions = knn_predict(&distance_matrix, &y, k);
367
368        assert_eq!(predictions.len(), n_test);
369    }
370
371    // ============== compute_adot tests ==============
372
373    #[test]
374    fn test_compute_adot_basic() {
375        let n = 4;
376        // Upper-triangular packed inner product: (n*(n+1))/2 = 10 elements
377        // Layout: (1,1), (2,1), (2,2), (3,1), (3,2), (3,3), (4,1), (4,2), (4,3), (4,4)
378        let mut inprod = vec![0.0; (n * (n + 1)) / 2];
379        // Set diagonal to 1.0 (identity-like)
380        // idx for (i,i): i*(i-1)/2 + i - 1 = i*(i+1)/2 - 1
381        for i in 1..=n {
382            let idx = i * (i - 1) / 2 + i - 1;
383            inprod[idx] = 1.0;
384        }
385
386        let adot = compute_adot(n, &inprod);
387
388        let expected_len = (n * n - n + 2) / 2;
389        assert_eq!(
390            adot.len(),
391            expected_len,
392            "Adot length should be (n^2-n+2)/2"
393        );
394        assert!(
395            (adot[0] - PI * (n + 1) as f64).abs() < 1e-10,
396            "First element should be π*(n+1), got {}",
397            adot[0]
398        );
399        for (i, &val) in adot.iter().enumerate() {
400            assert!(val.is_finite(), "Adot[{}] should be finite, got {}", i, val);
401        }
402    }
403
404    #[test]
405    fn test_compute_adot_n1() {
406        let n = 1;
407        let inprod = vec![1.0]; // (1*(1+1))/2 = 1
408        let adot = compute_adot(n, &inprod);
409
410        assert_eq!(adot.len(), 1, "n=1 should give length 1");
411        assert!(
412            (adot[0] - PI * 2.0).abs() < 1e-10,
413            "n=1: first element should be π*2, got {}",
414            adot[0]
415        );
416    }
417
418    #[test]
419    fn test_compute_adot_invalid() {
420        // n=0
421        assert!(compute_adot(0, &[]).is_empty());
422
423        // Wrong inprod length
424        assert!(compute_adot(4, &[1.0, 2.0]).is_empty());
425    }
426
427    // ============== pcvm_statistic tests ==============
428
429    #[test]
430    fn test_pcvm_statistic_basic() {
431        let n = 4;
432        let mut inprod = vec![0.0; (n * (n + 1)) / 2];
433        for i in 1..=n {
434            let idx = i * (i - 1) / 2 + i - 1;
435            inprod[idx] = 1.0;
436        }
437        let adot = compute_adot(n, &inprod);
438        let residuals = vec![0.5, -0.3, 0.2, -0.1];
439
440        let stat = pcvm_statistic(&adot, &residuals);
441
442        assert!(stat.is_finite(), "PCvM statistic should be finite");
443        assert!(stat >= 0.0, "PCvM statistic should be non-negative");
444    }
445
446    #[test]
447    fn test_pcvm_statistic_zero_residuals() {
448        let n = 4;
449        let mut inprod = vec![0.0; (n * (n + 1)) / 2];
450        for i in 1..=n {
451            let idx = i * (i - 1) / 2 + i - 1;
452            inprod[idx] = 1.0;
453        }
454        let adot = compute_adot(n, &inprod);
455        let residuals = vec![0.0, 0.0, 0.0, 0.0];
456
457        let stat = pcvm_statistic(&adot, &residuals);
458        assert!(
459            stat.abs() < 1e-10,
460            "PCvM with zero residuals should be ~0, got {}",
461            stat
462        );
463    }
464
465    #[test]
466    fn test_pcvm_statistic_empty() {
467        assert!(pcvm_statistic(&[], &[]).abs() < 1e-10);
468        assert!(pcvm_statistic(&[1.0], &[]).abs() < 1e-10);
469    }
470
471    // ============== rp_stat tests ==============
472
473    #[test]
474    fn test_rp_stat_basic() {
475        let n_proj = 3;
476        let residuals = vec![0.5, -0.3, 0.2, -0.1, 0.4];
477
478        // proj_x_ord is n_proj columns of n rows, 1-indexed ranks
479        let proj_x_ord: Vec<i32> = vec![
480            1, 3, 5, 2, 4, // projection 1
481            2, 4, 1, 5, 3, // projection 2
482            5, 1, 3, 4, 2, // projection 3
483        ];
484
485        let result = rp_stat(&proj_x_ord, &residuals, n_proj);
486
487        assert_eq!(result.cvm.len(), n_proj);
488        assert_eq!(result.ks.len(), n_proj);
489        for &cvm_val in &result.cvm {
490            assert!(cvm_val >= 0.0, "CvM stat should be non-negative");
491            assert!(cvm_val.is_finite(), "CvM stat should be finite");
492        }
493        for &ks_val in &result.ks {
494            assert!(ks_val >= 0.0, "KS stat should be non-negative");
495            assert!(ks_val.is_finite(), "KS stat should be finite");
496        }
497    }
498
499    #[test]
500    fn test_rp_stat_invalid() {
501        let result = rp_stat(&[], &[], 0);
502        assert!(result.cvm.is_empty());
503        assert!(result.ks.is_empty());
504
505        let result = rp_stat(&[], &[1.0], 0);
506        assert!(result.cvm.is_empty());
507    }
508
509    // ============== knn_loocv tests ==============
510
511    #[test]
512    fn test_knn_loocv_basic() {
513        let size = 5;
514        let k = 2;
515        // Simple distance matrix
516        let mut dist_data = vec![0.0; size * size];
517        for i in 0..size {
518            for j in 0..size {
519                dist_data[i + j * size] = ((i as f64) - (j as f64)).abs();
520            }
521        }
522        let dist = FdMatrix::from_column_major(dist_data, size, size).unwrap();
523        let y: Vec<f64> = (0..size).map(|i| i as f64 * 2.0).collect();
524
525        let mse = knn_loocv(&dist, &y, k);
526
527        assert!(mse.is_finite(), "k-NN LOOCV MSE should be finite");
528        assert!(mse >= 0.0, "k-NN LOOCV MSE should be non-negative");
529    }
530
531    #[test]
532    fn test_knn_loocv_perfect() {
533        // When nearest neighbors have the same y value, MSE should be ~0
534        let n = 4;
535        let k = 1;
536        // Distance matrix where each pair of adjacent points is close
537        let mut dist = FdMatrix::from_column_major(vec![100.0; n * n], n, n).unwrap();
538        for i in 0..n {
539            dist[(i, i)] = 0.0;
540        }
541        // Make pairs (0,1) and (2,3) very close
542        dist[(0, 1)] = 0.1;
543        dist[(1, 0)] = 0.1;
544        dist[(2, 3)] = 0.1;
545        dist[(3, 2)] = 0.1;
546
547        // Same y for paired points
548        let y = vec![1.0, 1.0, 5.0, 5.0];
549        let mse = knn_loocv(&dist, &y, k);
550
551        assert!(
552            mse < 1e-10,
553            "k-NN LOOCV MSE should be ~0 for perfectly paired data, got {}",
554            mse
555        );
556    }
557
558    #[test]
559    fn test_knn_loocv_invalid() {
560        let empty = FdMatrix::zeros(0, 0);
561        assert!(knn_loocv(&empty, &[], 1).is_infinite());
562        let single = FdMatrix::from_column_major(vec![0.0], 1, 1).unwrap();
563        assert!(knn_loocv(&single, &[1.0], 0).is_infinite());
564    }
565}