fdars-core 0.10.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Cross-conformal (CV+) and jackknife+ prediction methods.

use crate::cv::{create_folds, fold_indices, subset_rows, subset_vec};
use crate::error::FdarError;
use crate::matrix::FdMatrix;

use super::{
    argmax, build_classification_result, build_regression_result, compute_cal_scores,
    conformal_quantile, empirical_coverage, subset_vec_usize, vstack, vstack_opt,
    ClassificationScore, ConformalClassificationResult, ConformalMethod, ConformalRegressionResult,
};

/// Cross-conformal (CV+) prediction intervals for regression.
///
/// Uses K-fold CV: each fold produces out-of-fold predictions that serve
/// as calibration residuals, so no data is "wasted" on calibration.
///
/// The `fit_predict` closure takes `(train_data, train_y, train_sc, predict_data, predict_sc)`,
/// fits a model on `train_data`/`train_y`, and returns `Some((preds, _))` — predictions on
/// `predict_data`. Only the first element of the tuple is used; the second is ignored.
///
/// # Errors
///
/// Returns [`FdarError::InvalidDimension`] if `data` has fewer than 4 observations,
/// `test_data` is empty, or `y` length differs from the number of rows in `data`.
/// Returns [`FdarError::InvalidParameter`] if `alpha` is not in (0, 1).
/// Returns [`FdarError::ComputationFailed`] if the `fit_predict` closure returns `None`
/// on any fold, or no valid folds are produced.
#[must_use = "expensive computation whose result should not be discarded"]
pub fn cv_conformal_regression(
    data: &FdMatrix,
    y: &[f64],
    test_data: &FdMatrix,
    scalar_train: Option<&FdMatrix>,
    scalar_test: Option<&FdMatrix>,
    fit_predict: impl Fn(
        &FdMatrix,
        &[f64],
        Option<&FdMatrix>,
        &FdMatrix,
        Option<&FdMatrix>,
    ) -> Option<(Vec<f64>, Vec<f64>)>,
    n_folds: usize,
    alpha: f64,
    seed: u64,
) -> Result<ConformalRegressionResult, FdarError> {
    let n = data.nrows();
    let n_test = test_data.nrows();
    if n < 4 {
        return Err(FdarError::InvalidDimension {
            parameter: "data",
            expected: "at least 4 observations".to_string(),
            actual: format!("{n}"),
        });
    }
    if n_test == 0 {
        return Err(FdarError::InvalidDimension {
            parameter: "test_data",
            expected: "at least 1 observation".to_string(),
            actual: "0".to_string(),
        });
    }
    if y.len() != n {
        return Err(FdarError::InvalidDimension {
            parameter: "y",
            expected: format!("{n}"),
            actual: format!("{}", y.len()),
        });
    }
    if alpha <= 0.0 || alpha >= 1.0 {
        return Err(FdarError::InvalidParameter {
            parameter: "alpha",
            message: format!("must be in (0, 1), got {alpha}"),
        });
    }
    let n_folds = n_folds.max(2).min(n);

    let folds = create_folds(n, n_folds, seed);
    let mut all_cal_residuals = vec![0.0; n];
    let mut test_preds_sum = vec![0.0; n_test];
    let mut n_models = 0usize;

    for fold in 0..n_folds {
        let (train_idx, test_idx) = fold_indices(&folds, fold);
        if train_idx.is_empty() || test_idx.is_empty() {
            continue;
        }

        let train_data = subset_rows(data, &train_idx);
        let train_y = subset_vec(y, &train_idx);
        let train_sc = scalar_train.map(|sc| subset_rows(sc, &train_idx));
        let cal_data = subset_rows(data, &test_idx);
        let cal_sc = scalar_train.map(|sc| subset_rows(sc, &test_idx));

        // Single call: predict on combined [cal_data; test_data] to avoid double model fit
        let n_cal_fold = cal_data.nrows();
        let combined = vstack(&cal_data, test_data);
        let combined_sc = vstack_opt(cal_sc.as_ref(), scalar_test);
        let (all_preds, _) = fit_predict(
            &train_data,
            &train_y,
            train_sc.as_ref(),
            &combined,
            combined_sc.as_ref(),
        )
        .ok_or_else(|| FdarError::ComputationFailed {
            operation: "cv_conformal_regression",
            detail: format!("fit_predict closure returned None on fold {fold}"),
        })?;

        // Split predictions: first n_cal_fold are calibration, rest are test
        let cal_preds = &all_preds[..n_cal_fold];
        let test_preds_fold = &all_preds[n_cal_fold..];

        // Store calibration residuals at their original positions
        for (local_i, &orig_i) in test_idx.iter().enumerate() {
            if local_i < cal_preds.len() {
                all_cal_residuals[orig_i] = (y[orig_i] - cal_preds[local_i]).abs();
            }
        }

        for j in 0..n_test {
            if j < test_preds_fold.len() {
                test_preds_sum[j] += test_preds_fold[j];
            }
        }
        n_models += 1;
    }

    if n_models == 0 {
        return Err(FdarError::ComputationFailed {
            operation: "cv_conformal_regression",
            detail: "no valid folds produced".to_string(),
        });
    }

    // Average test predictions across folds
    let test_predictions: Vec<f64> = test_preds_sum
        .iter()
        .map(|&s| s / n_models as f64)
        .collect();

    Ok(build_regression_result(
        all_cal_residuals,
        test_predictions,
        alpha,
        ConformalMethod::CrossConformal { n_folds },
    ))
}

/// Run one fold of cross-conformal classification.
///
/// Fits the model on train indices, predicts on calibration + test combined,
/// and returns `(cal_scores_with_indices, test_probs)`.
fn conformal_classif_fold(
    data: &FdMatrix,
    y: &[usize],
    test_data: &FdMatrix,
    scalar_train: Option<&FdMatrix>,
    scalar_test: Option<&FdMatrix>,
    train_idx: &[usize],
    test_idx: &[usize],
    fold: usize,
    score_type: ClassificationScore,
    fit_predict_probs: &dyn Fn(
        &FdMatrix,
        &[usize],
        Option<&FdMatrix>,
        &FdMatrix,
        Option<&FdMatrix>,
    ) -> Option<(Vec<Vec<f64>>, Vec<Vec<f64>>)>,
) -> Result<(Vec<(usize, f64)>, Vec<Vec<f64>>), FdarError> {
    let train_data = subset_rows(data, train_idx);
    let train_y = subset_vec_usize(y, train_idx);
    let train_sc = scalar_train.map(|sc| subset_rows(sc, train_idx));
    let cal_data = subset_rows(data, test_idx);
    let cal_sc = scalar_train.map(|sc| subset_rows(sc, test_idx));

    // Single call: predict on combined [cal_data; test_data] to avoid double model fit
    let n_cal_fold = cal_data.nrows();
    let combined = vstack(&cal_data, test_data);
    let combined_sc = vstack_opt(cal_sc.as_ref(), scalar_test);
    let (all_probs, _) = fit_predict_probs(
        &train_data,
        &train_y,
        train_sc.as_ref(),
        &combined,
        combined_sc.as_ref(),
    )
    .ok_or_else(|| FdarError::ComputationFailed {
        operation: "cv_conformal_classification",
        detail: format!("fit_predict_probs closure returned None on fold {fold}"),
    })?;

    // Split predictions: first n_cal_fold are calibration, rest are test
    let cal_probs: Vec<Vec<f64>> = all_probs[..n_cal_fold].to_vec();
    let test_probs: Vec<Vec<f64>> = all_probs[n_cal_fold..].to_vec();

    // Calibration scores paired with original indices
    let cal_true = subset_vec_usize(y, test_idx);
    let cal_scores = compute_cal_scores(&cal_probs, &cal_true, score_type);
    let indexed_scores: Vec<(usize, f64)> = test_idx
        .iter()
        .enumerate()
        .filter(|&(local_i, _)| local_i < cal_scores.len())
        .map(|(local_i, &orig_i)| (orig_i, cal_scores[local_i]))
        .collect();

    Ok((indexed_scores, test_probs))
}

/// Aggregate per-fold conformal classification results into a final prediction.
///
/// Averages test probabilities across folds, determines predicted classes, and
/// builds the final [`ConformalClassificationResult`].
fn aggregate_conformal_results(
    all_cal_scores: Vec<f64>,
    test_probs_sum: &[Vec<f64>],
    n_models: usize,
    n_folds: usize,
    alpha: f64,
    score_type: ClassificationScore,
) -> Result<ConformalClassificationResult, FdarError> {
    if n_models == 0 {
        return Err(FdarError::ComputationFailed {
            operation: "cv_conformal_classification",
            detail: "no valid folds produced".to_string(),
        });
    }

    let test_probs_avg: Vec<Vec<f64>> = test_probs_sum
        .iter()
        .map(|probs| probs.iter().map(|&p| p / n_models as f64).collect())
        .collect();
    let test_pred_classes: Vec<usize> = test_probs_avg.iter().map(|p| argmax(p)).collect();

    Ok(build_classification_result(
        all_cal_scores,
        &test_probs_avg,
        test_pred_classes,
        alpha,
        ConformalMethod::CrossConformal { n_folds },
        score_type,
    ))
}

/// Cross-conformal (CV+) prediction sets for classification.
///
/// The `fit_predict_probs` closure takes `(train_data, train_y, train_sc, predict_data, predict_sc)`,
/// fits on `train_data`/`train_y`, and returns `Some((probs, _))` — probability vectors on
/// `predict_data`. Only the first element of the tuple is used.
///
/// # Errors
///
/// Returns [`FdarError::InvalidDimension`] if `data` has fewer than 4 observations,
/// `test_data` is empty, `y` length differs from the number of rows in `data`,
/// or `y` is empty (no classes can be determined).
/// Returns [`FdarError::InvalidParameter`] if `alpha` is not in (0, 1).
/// Returns [`FdarError::ComputationFailed`] if the `fit_predict_probs` closure returns
/// `None` on any fold, or no valid folds are produced.
#[must_use = "expensive computation whose result should not be discarded"]
pub fn cv_conformal_classification(
    data: &FdMatrix,
    y: &[usize],
    test_data: &FdMatrix,
    scalar_train: Option<&FdMatrix>,
    scalar_test: Option<&FdMatrix>,
    fit_predict_probs: impl Fn(
        &FdMatrix,
        &[usize],
        Option<&FdMatrix>,
        &FdMatrix,
        Option<&FdMatrix>,
    ) -> Option<(Vec<Vec<f64>>, Vec<Vec<f64>>)>,
    n_folds: usize,
    score_type: ClassificationScore,
    alpha: f64,
    seed: u64,
) -> Result<ConformalClassificationResult, FdarError> {
    let n = data.nrows();
    let n_test = test_data.nrows();
    if n < 4 {
        return Err(FdarError::InvalidDimension {
            parameter: "data",
            expected: "at least 4 observations".to_string(),
            actual: format!("{n}"),
        });
    }
    if n_test == 0 {
        return Err(FdarError::InvalidDimension {
            parameter: "test_data",
            expected: "at least 1 observation".to_string(),
            actual: "0".to_string(),
        });
    }
    if y.len() != n {
        return Err(FdarError::InvalidDimension {
            parameter: "y",
            expected: format!("{n}"),
            actual: format!("{}", y.len()),
        });
    }
    if alpha <= 0.0 || alpha >= 1.0 {
        return Err(FdarError::InvalidParameter {
            parameter: "alpha",
            message: format!("must be in (0, 1), got {alpha}"),
        });
    }
    let n_classes = y
        .iter()
        .copied()
        .max()
        .ok_or_else(|| FdarError::InvalidDimension {
            parameter: "y",
            expected: "non-empty label vector".to_string(),
            actual: "empty".to_string(),
        })?
        + 1;
    let n_folds = n_folds.max(2).min(n);

    let folds = create_folds(n, n_folds, seed);
    let mut all_cal_scores = vec![0.0; n];
    let mut test_probs_sum: Vec<Vec<f64>> = vec![vec![0.0; n_classes]; n_test];
    let mut n_models = 0usize;

    for fold in 0..n_folds {
        let (train_idx, test_idx) = fold_indices(&folds, fold);
        if train_idx.is_empty() || test_idx.is_empty() {
            continue;
        }

        let (indexed_scores, test_probs) = conformal_classif_fold(
            data,
            y,
            test_data,
            scalar_train,
            scalar_test,
            &train_idx,
            &test_idx,
            fold,
            score_type,
            &fit_predict_probs,
        )?;

        for (orig_i, score) in indexed_scores {
            all_cal_scores[orig_i] = score;
        }
        for j in 0..n_test.min(test_probs.len()) {
            for c in 0..n_classes.min(test_probs[j].len()) {
                test_probs_sum[j][c] += test_probs[j][c];
            }
        }
        n_models += 1;
    }

    aggregate_conformal_results(
        all_cal_scores,
        &test_probs_sum,
        n_models,
        n_folds,
        alpha,
        score_type,
    )
}

// ═══════════════════════════════════════════════════════════════════════════
// Jackknife+
// ═══════════════════════════════════════════════════════════════════════════

/// Jackknife+ prediction intervals for regression.
///
/// LOO-based conformal: for each i = 1..n, fits model on all data except i,
/// computes LOO residual and test predictions. Constructs intervals from the
/// distribution of signed residuals.
///
/// Requires n refits, so this is the most sample-efficient but most expensive method.
///
/// The `fit_predict` closure takes `(train_data, train_y, train_sc, predict_data, predict_sc)`
/// and returns `Some((predictions, _))` — predictions on `predict_data`.
///
/// # Errors
///
/// Returns [`FdarError::InvalidDimension`] if `data` has fewer than 4 observations,
/// `test_data` is empty, or `y` length differs from the number of rows in `data`.
/// Returns [`FdarError::InvalidParameter`] if `alpha` is not in (0, 1).
/// Returns [`FdarError::ComputationFailed`] if the `fit_predict` closure returns `None`
/// on any leave-one-out iteration.
#[must_use = "expensive computation whose result should not be discarded"]
pub fn jackknife_plus_regression(
    data: &FdMatrix,
    y: &[f64],
    test_data: &FdMatrix,
    scalar_train: Option<&FdMatrix>,
    scalar_test: Option<&FdMatrix>,
    fit_predict: impl Fn(
        &FdMatrix,
        &[f64],
        Option<&FdMatrix>,
        &FdMatrix,
        Option<&FdMatrix>,
    ) -> Option<(Vec<f64>, Vec<f64>)>,
    alpha: f64,
) -> Result<ConformalRegressionResult, FdarError> {
    let n = data.nrows();
    let n_test = test_data.nrows();
    if n < 4 {
        return Err(FdarError::InvalidDimension {
            parameter: "data",
            expected: "at least 4 observations".to_string(),
            actual: format!("{n}"),
        });
    }
    if n_test == 0 {
        return Err(FdarError::InvalidDimension {
            parameter: "test_data",
            expected: "at least 1 observation".to_string(),
            actual: "0".to_string(),
        });
    }
    if y.len() != n {
        return Err(FdarError::InvalidDimension {
            parameter: "y",
            expected: format!("{n}"),
            actual: format!("{}", y.len()),
        });
    }
    if alpha <= 0.0 || alpha >= 1.0 {
        return Err(FdarError::InvalidParameter {
            parameter: "alpha",
            message: format!("must be in (0, 1), got {alpha}"),
        });
    }

    let mut loo_residuals = vec![0.0; n];
    // For each test point, store predictions from all n LOO models
    let mut test_preds_all = vec![vec![0.0; n]; n_test];

    for i in 0..n {
        let train_idx: Vec<usize> = (0..n).filter(|&j| j != i).collect();
        let loo_idx = vec![i];

        let train_data = subset_rows(data, &train_idx);
        let train_y = subset_vec(y, &train_idx);
        let train_sc = scalar_train.map(|sc| subset_rows(sc, &train_idx));
        let loo_data = subset_rows(data, &loo_idx);
        let loo_sc = scalar_train.map(|sc| subset_rows(sc, &loo_idx));

        // Predict on LOO observation
        let (loo_pred, _) = fit_predict(
            &train_data,
            &train_y,
            train_sc.as_ref(),
            &loo_data,
            loo_sc.as_ref(),
        )
        .ok_or_else(|| FdarError::ComputationFailed {
            operation: "jackknife_plus_regression",
            detail: format!("fit_predict closure returned None on LOO iteration {i}"),
        })?;

        loo_residuals[i] = (y[i] - loo_pred[0]).abs();

        // Predict on test data
        let (test_preds, _) = fit_predict(
            &train_data,
            &train_y,
            train_sc.as_ref(),
            test_data,
            scalar_test,
        )
        .ok_or_else(|| FdarError::ComputationFailed {
            operation: "jackknife_plus_regression",
            detail: format!(
                "fit_predict closure returned None on test prediction for LOO iteration {i}"
            ),
        })?;

        for j in 0..n_test.min(test_preds.len()) {
            test_preds_all[j][i] = test_preds[j];
        }
    }

    // For each test point: construct interval from the distribution of
    // y_{-i}(x_test) +/- R_i across all i
    let q_lo = alpha / 2.0;
    let q_hi = 1.0 - alpha / 2.0;

    let mut predictions = vec![0.0; n_test];
    let mut lower = vec![0.0; n_test];
    let mut upper = vec![0.0; n_test];

    for j in 0..n_test {
        // Mean prediction
        predictions[j] = test_preds_all[j].iter().sum::<f64>() / n as f64;

        // Lower bounds: y_{-i}(x_test) - R_i
        let mut lower_vals: Vec<f64> = (0..n)
            .map(|i| test_preds_all[j][i] - loo_residuals[i])
            .collect();
        crate::helpers::sort_nan_safe(&mut lower_vals);
        // Lower bound: floor((n+1)*q_lo) as rank (Barber et al. 2021, Corollary 2)
        let lo_k = ((n + 1) as f64 * q_lo).floor() as usize;
        if lo_k == 0 {
            lower[j] = f64::NEG_INFINITY;
        } else {
            lower[j] = lower_vals[(lo_k - 1).min(n.saturating_sub(1))];
        }

        // Upper bounds: y_{-i}(x_test) + R_i
        let mut upper_vals: Vec<f64> = (0..n)
            .map(|i| test_preds_all[j][i] + loo_residuals[i])
            .collect();
        crate::helpers::sort_nan_safe(&mut upper_vals);
        let hi_k = ((n + 1) as f64 * q_hi).ceil() as usize;
        let hi_idx = if hi_k > n {
            n.saturating_sub(1)
        } else {
            (hi_k - 1).min(n.saturating_sub(1))
        };
        upper[j] = upper_vals[hi_idx];
    }

    // Coverage on LOO (using mean prediction)
    let residual_quantile = {
        let mut r = loo_residuals.clone();
        conformal_quantile(&mut r, alpha)
    };
    let coverage = empirical_coverage(&loo_residuals, residual_quantile);

    Ok(ConformalRegressionResult {
        predictions,
        lower,
        upper,
        residual_quantile,
        coverage,
        calibration_scores: loo_residuals,
        method: ConformalMethod::JackknifePlus,
    })
}