fdars-core 0.13.0

Functional Data Analysis algorithms in Rust
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! P-spline fitting and penalty (difference) matrices.

use super::bspline::{bspline_basis, bspline_basis_from_knots, construct_bspline_knots};
use super::helpers::svd_pseudoinverse;
use crate::matrix::FdMatrix;
use nalgebra::{DMatrix, DVector};

/// Compute difference matrix for P-spline penalty.
pub fn difference_matrix(n: usize, order: usize) -> DMatrix<f64> {
    if order == 0 {
        return DMatrix::identity(n, n);
    }

    let mut d = DMatrix::zeros(n - 1, n);
    for i in 0..(n - 1) {
        d[(i, i)] = -1.0;
        d[(i, i + 1)] = 1.0;
    }

    let mut result = d;
    for _ in 1..order {
        if result.nrows() <= 1 {
            break;
        }
        let rows = result.nrows() - 1;
        let cols = result.ncols();
        let mut d_next = DMatrix::zeros(rows, cols);
        for i in 0..rows {
            for j in 0..cols {
                d_next[(i, j)] = -result[(i, j)] + result[(i + 1, j)];
            }
        }
        result = d_next;
    }

    result
}

/// Result of P-spline fitting.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct PsplineFitResult {
    /// Coefficient matrix (n x nbasis)
    pub coefficients: FdMatrix,
    /// Fitted values (n x m)
    pub fitted: FdMatrix,
    /// Effective degrees of freedom
    pub edf: f64,
    /// Residual sum of squares
    pub rss: f64,
    /// GCV score
    pub gcv: f64,
    /// AIC
    pub aic: f64,
    /// BIC
    pub bic: f64,
    /// Number of basis functions
    pub n_basis: usize,
    /// B-spline knot vector used during fitting
    pub knots: Vec<f64>,
    /// B-spline order used during fitting (typically 4 for cubic)
    pub order: usize,
}

/// Fit P-splines to functional data.
pub fn pspline_fit_1d(
    data: &FdMatrix,
    argvals: &[f64],
    nbasis: usize,
    lambda: f64,
    order: usize,
) -> Option<PsplineFitResult> {
    let n = data.nrows();
    let m = data.ncols();
    if n == 0 || m == 0 || nbasis < 2 || argvals.len() != m {
        return None;
    }

    // For order 4 B-splines: nbasis = nknots + order, so nknots = nbasis - 4
    let nknots = nbasis.saturating_sub(4).max(2);
    let spline_order = 4;
    let t_min = argvals.iter().copied().fold(f64::INFINITY, f64::min);
    let t_max = argvals.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let knots = construct_bspline_knots(t_min, t_max, nknots, spline_order);
    let basis = bspline_basis(argvals, nknots, spline_order);
    let actual_nbasis = basis.len() / m;
    let b_mat = DMatrix::from_column_slice(m, actual_nbasis, &basis);

    let d = difference_matrix(actual_nbasis, order);
    let penalty = &d.transpose() * &d;

    let btb = &b_mat.transpose() * &b_mat;
    let btb_penalized = &btb + lambda * &penalty;

    let btb_inv = svd_pseudoinverse(&btb_penalized)?;
    let proj = &btb_inv * b_mat.transpose();
    let h_mat = &b_mat * &proj;
    let edf: f64 = (0..m).map(|i| h_mat[(i, i)]).sum();

    let mut all_coefs = FdMatrix::zeros(n, actual_nbasis);
    let mut all_fitted = FdMatrix::zeros(n, m);
    let mut total_rss = 0.0;

    for i in 0..n {
        let curve: Vec<f64> = (0..m).map(|j| data[(i, j)]).collect();
        let curve_vec = DVector::from_vec(curve.clone());

        let bt_y = b_mat.transpose() * &curve_vec;
        let coefs = &btb_inv * bt_y;

        for k in 0..actual_nbasis {
            all_coefs[(i, k)] = coefs[k];
        }

        let fitted = &b_mat * &coefs;
        for j in 0..m {
            all_fitted[(i, j)] = fitted[j];
            let resid = curve[j] - fitted[j];
            total_rss += resid * resid;
        }
    }

    let total_points = (n * m) as f64;

    let gcv_denom = 1.0 - edf / m as f64;
    let gcv = if gcv_denom.abs() > 1e-10 {
        (total_rss / total_points) / (gcv_denom * gcv_denom)
    } else {
        f64::INFINITY
    };

    let mse = total_rss / total_points;
    let aic = total_points * mse.ln() + 2.0 * edf;
    let bic = total_points * mse.ln() + total_points.ln() * edf;

    Some(PsplineFitResult {
        coefficients: all_coefs,
        fitted: all_fitted,
        edf,
        rss: total_rss,
        gcv,
        aic,
        bic,
        n_basis: actual_nbasis,
        knots,
        order: spline_order,
    })
}

/// Evaluate P-spline fit on a new grid using stored knot vector.
///
/// Uses the B-spline coefficients and knot vector from [`pspline_fit_1d`]
/// to evaluate the fitted curves at arbitrary evaluation points within
/// the original domain.
///
/// # Arguments
/// * `result` - P-spline fit result containing coefficients and knots
/// * `new_argvals` - New evaluation points
///
/// # Returns
/// Matrix (n x m_new) of evaluated curves
#[must_use]
pub fn pspline_evaluate(result: &PsplineFitResult, new_argvals: &[f64]) -> FdMatrix {
    let n = result.coefficients.nrows();
    let m_new = new_argvals.len();
    let nbasis = result.n_basis;

    let basis = bspline_basis_from_knots(new_argvals, &result.knots, result.order);
    let actual_nbasis = basis.len() / m_new;

    // Column-major: iterate columns then rows
    let flat: Vec<f64> = (0..m_new)
        .flat_map(|j| {
            (0..n)
                .map(|i| {
                    let mut sum = 0.0;
                    for k in 0..actual_nbasis.min(nbasis) {
                        sum += result.coefficients[(i, k)] * basis[j + k * m_new];
                    }
                    sum
                })
                .collect::<Vec<_>>()
        })
        .collect();

    FdMatrix::from_column_major(flat, n, m_new).expect("dimension invariant")
}

/// Fit P-splines with automatic lambda selection via GCV minimization.
///
/// Searches over a logarithmic grid of lambda values and returns the
/// result with the lowest GCV score.
///
/// # Arguments
/// * `data` - Functional data matrix (n x m)
/// * `argvals` - Evaluation points (length m)
/// * `nbasis` - Number of basis functions
/// * `order` - Difference penalty order (typically 2)
///
/// # Returns
/// The P-spline fit result with optimal lambda, or `None` if all
/// lambda values produce invalid fits.
#[must_use]
pub fn pspline_fit_gcv(
    data: &FdMatrix,
    argvals: &[f64],
    nbasis: usize,
    order: usize,
) -> Option<PsplineFitResult> {
    let lambdas: Vec<f64> = (-6..=6)
        .flat_map(|exp| {
            [1.0, 3.16]
                .iter()
                .map(move |&base| base * 10.0f64.powi(exp))
        })
        .collect();

    let mut best: Option<PsplineFitResult> = None;
    let mut best_gcv = f64::INFINITY;

    for &lambda in &lambdas {
        if let Some(result) = pspline_fit_1d(data, argvals, nbasis, lambda, order) {
            if result.gcv.is_finite() && result.gcv < best_gcv {
                best_gcv = result.gcv;
                best = Some(result);
            }
        }
    }

    best
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::matrix::FdMatrix;

    fn sine_data(argvals: &[f64]) -> FdMatrix {
        let n = 3;
        let m = argvals.len();
        let vals: Vec<f64> = (0..n)
            .flat_map(|i| argvals.iter().map(move |&t| ((i + 1) as f64 * t).sin()))
            .collect();
        FdMatrix::from_column_major(vals, n, m).unwrap()
    }

    #[test]
    fn pspline_stores_knots() {
        let t: Vec<f64> = (0..50).map(|i| i as f64 / 49.0).collect();
        let data = sine_data(&t);
        let result = pspline_fit_1d(&data, &t, 10, 0.001, 2).unwrap();
        assert!(!result.knots.is_empty());
        assert_eq!(result.order, 4);
    }

    #[test]
    fn pspline_evaluate_on_original_grid() {
        let t: Vec<f64> = (0..50).map(|i| i as f64 / 49.0).collect();
        let data = sine_data(&t);
        let result = pspline_fit_1d(&data, &t, 10, 0.001, 2).unwrap();
        let eval = pspline_evaluate(&result, &t);
        // Should match fitted values closely
        for i in 0..data.nrows() {
            for j in 0..t.len() {
                assert!(
                    (eval[(i, j)] - result.fitted[(i, j)]).abs() < 1e-10,
                    "mismatch at ({i}, {j}): eval={} fitted={}",
                    eval[(i, j)],
                    result.fitted[(i, j)]
                );
            }
        }
    }

    #[test]
    fn pspline_evaluate_on_finer_grid() {
        let t: Vec<f64> = (0..30).map(|i| i as f64 / 29.0).collect();
        let data = sine_data(&t);
        let result = pspline_fit_1d(&data, &t, 12, 0.001, 2).unwrap();

        // Evaluate on a finer grid
        let t_fine: Vec<f64> = (0..200).map(|i| i as f64 / 199.0).collect();
        let eval = pspline_evaluate(&result, &t_fine);
        assert_eq!(eval.nrows(), data.nrows());
        assert_eq!(eval.ncols(), 200);

        // Values should be in a reasonable range (sin is in [-1, 1])
        for i in 0..eval.nrows() {
            for j in 0..eval.ncols() {
                assert!(
                    eval[(i, j)].abs() < 2.0,
                    "wild value at ({i}, {j}): {}",
                    eval[(i, j)]
                );
            }
        }
    }

    /// Regression test for issue #21: pspline_evaluate on a different grid
    /// matches the fitted values when evaluated at original grid points,
    /// and produces bounded values on a finer grid (no wild oscillations).
    #[test]
    fn regression_issue_21_cross_grid_consistency() {
        // Fit on 31-point grid in [1, 18] (non-[0,1] domain like growth data)
        let t: Vec<f64> = (0..31).map(|i| 1.0 + 17.0 * i as f64 / 30.0).collect();
        let data = sine_data(&t);
        let result = pspline_fit_1d(&data, &t, 12, 1.0, 2).unwrap();

        // Evaluate at original grid points — must match fitted exactly
        let eval_orig = pspline_evaluate(&result, &t);
        for i in 0..data.nrows() {
            for j in 0..t.len() {
                assert!(
                    (eval_orig[(i, j)] - result.fitted[(i, j)]).abs() < 1e-10,
                    "mismatch at ({i}, {j})"
                );
            }
        }

        // Evaluate on 200-point finer grid — values must stay bounded
        let t_fine: Vec<f64> = (0..200).map(|i| 1.0 + 17.0 * i as f64 / 199.0).collect();
        let eval_fine = pspline_evaluate(&result, &t_fine);
        assert_eq!(eval_fine.shape(), (data.nrows(), 200));

        // Find range of fitted values for reference
        let mut fit_min = f64::INFINITY;
        let mut fit_max = f64::NEG_INFINITY;
        for i in 0..data.nrows() {
            for j in 0..t.len() {
                let v = result.fitted[(i, j)];
                fit_min = fit_min.min(v);
                fit_max = fit_max.max(v);
            }
        }
        let margin = (fit_max - fit_min) * 0.5;

        for i in 0..eval_fine.nrows() {
            for j in 0..200 {
                assert!(
                    eval_fine[(i, j)] > fit_min - margin && eval_fine[(i, j)] < fit_max + margin,
                    "curve {i} at t={:.2}: value {:.2} outside [{:.1}, {:.1}]",
                    t_fine[j],
                    eval_fine[(i, j)],
                    fit_min - margin,
                    fit_max + margin,
                );
            }
        }
    }

    /// Regression test: pspline_evaluate on a non-[0,1] domain produces
    /// smooth interpolation (not wild oscillations as in old basis_to_fdata).
    #[test]
    fn regression_issue_21_non_unit_domain_interp() {
        // Fit on [5, 15] (arbitrary non-[0,1] domain)
        let t: Vec<f64> = (0..40).map(|i| 5.0 + 10.0 * i as f64 / 39.0).collect();
        let data = sine_data(&t);
        let result = pspline_fit_1d(&data, &t, 10, 1.0, 2).unwrap();

        // Evaluate at midpoints between original grid points
        let t_mid: Vec<f64> = t.windows(2).map(|w| (w[0] + w[1]) / 2.0).collect();
        let eval_mid = pspline_evaluate(&result, &t_mid);

        // Midpoint values should be between neighboring fitted values (approximately)
        for i in 0..data.nrows() {
            for j in 0..t_mid.len() {
                let lo = result.fitted[(i, j)].min(result.fitted[(i, j + 1)]);
                let hi = result.fitted[(i, j)].max(result.fitted[(i, j + 1)]);
                let margin = (hi - lo).abs() + 0.5; // generous margin
                assert!(
                    eval_mid[(i, j)] >= lo - margin && eval_mid[(i, j)] <= hi + margin,
                    "curve {i} midpoint {j}: value {:.4} far from [{:.4}, {:.4}]",
                    eval_mid[(i, j)],
                    lo,
                    hi
                );
            }
        }
    }

    #[test]
    fn pspline_evaluate_matches_at_subset_points() {
        // Fit on fine grid, evaluate on coarser subset
        let t: Vec<f64> = (0..100).map(|i| i as f64 / 99.0).collect();
        let data = sine_data(&t);
        let result = pspline_fit_1d(&data, &t, 15, 0.0001, 2).unwrap();

        // Evaluate on every 10th point
        let t_coarse: Vec<f64> = (0..10).map(|i| i as f64 * 10.0 / 99.0).collect();
        let eval = pspline_evaluate(&result, &t_coarse);

        for i in 0..data.nrows() {
            for (jc, &_tc) in t_coarse.iter().enumerate() {
                let j_orig = jc * 10;
                let diff = (eval[(i, jc)] - result.fitted[(i, j_orig)]).abs();
                assert!(
                    diff < 1e-8,
                    "mismatch at curve {i}, coarse idx {jc} (orig {j_orig}): diff={diff}"
                );
            }
        }
    }
}