rscopulas 0.2.2

Core Rust library for fitting, evaluating, and sampling copula models and vine copulas
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
use std::{fs, path::PathBuf};

use ndarray::Array2;
use rand::{SeedableRng, rngs::StdRng};
use serde::Deserialize;

use rscopulas::accel::is_device_available as accel_device_available;
use rscopulas::{
    CopulaError, CopulaModel, Device, EvalOptions, ExecPolicy, FitOptions, GaussianCopula,
    PairCopulaFamily, PairCopulaParams, PairCopulaSpec, PseudoObs, Rotation, SampleOptions,
    StudentTCopula, VineCopula, VineEdge, VineFitOptions, VineStructureKind, VineTree,
    paircopula::fit_pair_copula, stats::try_kendall_tau_matrix,
};

#[derive(Debug, Deserialize)]
struct PairFixture {
    u1: Vec<f64>,
    u2: Vec<f64>,
}

#[derive(Debug, Deserialize)]
struct GaussianLogPdfFixture {
    correlation: Vec<Vec<f64>>,
    inputs: Vec<Vec<f64>>,
}

#[derive(Debug, Deserialize)]
struct StudentTLogPdfFixture {
    correlation: Vec<Vec<f64>>,
    degrees_of_freedom: f64,
    inputs: Vec<Vec<f64>>,
}

#[derive(Debug, Deserialize)]
struct GaussianFitFixture {
    input_pobs: Vec<Vec<f64>>,
}

#[derive(Debug, Deserialize)]
struct VineLogPdfFixture {
    order: Vec<usize>,
    correlation: Vec<Vec<f64>>,
    inputs: Vec<Vec<f64>>,
}

#[derive(Debug, Deserialize)]
struct EdgeFixture {
    conditioned: [usize; 2],
    conditioning: Vec<usize>,
    family: String,
    rotation: String,
    params: Vec<f64>,
}

#[derive(Debug, Deserialize)]
struct TreeFixture {
    level: usize,
    edges: Vec<EdgeFixture>,
}

#[derive(Debug, Deserialize)]
struct RVineLogPdfFixture {
    truncation_level: Option<usize>,
    trees: Vec<TreeFixture>,
    inputs: Vec<Vec<f64>>,
}

#[test]
fn gaussian_log_pdf_auto_matches_forced_cpu() {
    let fixture: GaussianLogPdfFixture = load_copula_fixture("gaussian_log_pdf_d2_case01.json");
    let model =
        GaussianCopula::new(array2(&fixture.correlation)).expect("correlation should be valid");
    let data = PseudoObs::new(array2(&fixture.inputs)).expect("inputs should be valid");

    let auto = model
        .log_pdf(&data, &EvalOptions::default())
        .expect("auto log pdf should evaluate");
    let serial = model
        .log_pdf(&data, &serial_eval_options())
        .expect("serial log pdf should evaluate");

    assert_eq!(auto, serial);
}

#[test]
fn student_t_log_pdf_auto_matches_forced_cpu() {
    let fixture: StudentTLogPdfFixture = load_copula_fixture("student_t_log_pdf_d2_case01.json");
    let model = StudentTCopula::new(array2(&fixture.correlation), fixture.degrees_of_freedom)
        .expect("parameters should be valid");
    let data = PseudoObs::new(array2(&fixture.inputs)).expect("inputs should be valid");

    let auto = model
        .log_pdf(&data, &EvalOptions::default())
        .expect("auto log pdf should evaluate");
    let serial = model
        .log_pdf(&data, &serial_eval_options())
        .expect("serial log pdf should evaluate");

    assert_eq!(auto, serial);
}

#[test]
fn gaussian_fit_auto_matches_forced_cpu() {
    let fixture: GaussianFitFixture = load_copula_fixture("gaussian_fit_d2_case01.json");
    let data = PseudoObs::new(array2(&fixture.input_pobs)).expect("input should be valid");

    let auto = GaussianCopula::fit(&data, &FitOptions::default()).expect("auto fit should succeed");
    let serial =
        GaussianCopula::fit(&data, &serial_fit_options()).expect("serial fit should succeed");

    assert_eq!(auto.model.correlation(), serial.model.correlation());
    assert_eq!(auto.diagnostics.loglik, serial.diagnostics.loglik);
}

#[test]
fn kendall_tau_auto_matches_forced_cpu() {
    let fixture: GaussianFitFixture = load_copula_fixture("gaussian_fit_d2_case01.json");
    let data = PseudoObs::new(array2(&fixture.input_pobs)).expect("input should be valid");

    let auto =
        try_kendall_tau_matrix(&data, ExecPolicy::Auto).expect("auto tau matrix should succeed");
    let serial = try_kendall_tau_matrix(&data, ExecPolicy::Force(Device::Cpu))
        .expect("serial tau matrix should succeed");

    assert_eq!(auto, serial);
}

#[test]
fn pair_fit_auto_matches_forced_cpu_for_base_and_rotation() {
    for fixture_name in ["pair_clayton_case01.json", "pair_clayton_rot90_case01.json"] {
        let fixture: PairFixture = load_vine_fixture(fixture_name);
        let auto = fit_pair_copula(
            &fixture.u1,
            &fixture.u2,
            &pair_fit_options(ExecPolicy::Auto),
        )
        .expect("auto pair fit should succeed");
        let serial = fit_pair_copula(
            &fixture.u1,
            &fixture.u2,
            &pair_fit_options(ExecPolicy::Force(Device::Cpu)),
        )
        .expect("serial pair fit should succeed");

        assert_eq!(auto.spec, serial.spec);
        assert_eq!(auto.cond_on_first, serial.cond_on_first);
        assert_eq!(auto.cond_on_second, serial.cond_on_second);
        assert!((auto.loglik - serial.loglik).abs() < 1e-12);
    }
}

#[test]
fn gaussian_c_and_d_vine_auto_match_forced_cpu() {
    for fixture_name in [
        (
            "gaussian_c_vine_log_pdf_d4_case01.json",
            VineStructureKind::C,
        ),
        (
            "gaussian_d_vine_log_pdf_d4_case01.json",
            VineStructureKind::D,
        ),
    ] {
        let fixture: VineLogPdfFixture = load_vine_fixture(fixture_name.0);
        let model = match fixture_name.1 {
            VineStructureKind::C => {
                VineCopula::gaussian_c_vine(fixture.order.clone(), array2(&fixture.correlation))
            }
            VineStructureKind::D => {
                VineCopula::gaussian_d_vine(fixture.order.clone(), array2(&fixture.correlation))
            }
            VineStructureKind::R => unreachable!("only C and D vines are exercised here"),
        }
        .expect("vine model should build");
        let data = PseudoObs::new(array2(&fixture.inputs)).expect("inputs should be valid");

        let auto = model
            .log_pdf(&data, &EvalOptions::default())
            .expect("auto vine log pdf should evaluate");
        let serial = model
            .log_pdf(&data, &serial_eval_options())
            .expect("serial vine log pdf should evaluate");

        assert_eq!(auto, serial);
    }
}

#[test]
fn mixed_r_vine_auto_matches_forced_cpu() {
    let fixture: RVineLogPdfFixture = load_vine_fixture("mixed_r_vine_log_pdf_d5_case01.json");
    let model = build_r_vine_model(&fixture.trees, fixture.truncation_level);
    let data = PseudoObs::new(array2(&fixture.inputs)).expect("inputs should be valid");

    let auto = model
        .log_pdf(&data, &EvalOptions::default())
        .expect("auto log pdf should evaluate");
    let serial = model
        .log_pdf(&data, &serial_eval_options())
        .expect("serial log pdf should evaluate");

    assert_eq!(auto, serial);
}

#[test]
fn forced_metal_gaussian_pair_fit_matches_cpu_with_tolerance() {
    if !accel_device_available(rscopulas::accel::Device::Metal) {
        return;
    }

    let fixture: PairFixture = load_vine_fixture("pair_gaussian_case01.json");
    let serial = fit_pair_copula(
        &fixture.u1,
        &fixture.u2,
        &gaussian_only_pair_fit_options(ExecPolicy::Force(Device::Cpu)),
    )
    .expect("serial gaussian pair fit should succeed");
    let metal = fit_pair_copula(
        &fixture.u1,
        &fixture.u2,
        &gaussian_only_pair_fit_options(ExecPolicy::Force(Device::Metal)),
    )
    .expect("metal gaussian pair fit should succeed");

    assert_eq!(metal.spec, serial.spec);
    assert!((metal.loglik - serial.loglik).abs() < 1e-4);
    assert_close_slice(&metal.cond_on_first, &serial.cond_on_first, 1e-5);
    assert_close_slice(&metal.cond_on_second, &serial.cond_on_second, 1e-5);
}

#[test]
fn forced_metal_gaussian_vines_match_cpu_with_tolerance() {
    if !accel_device_available(rscopulas::accel::Device::Metal) {
        return;
    }

    for fixture_name in [
        (
            "gaussian_c_vine_log_pdf_d4_case01.json",
            VineStructureKind::C,
        ),
        (
            "gaussian_d_vine_log_pdf_d4_case01.json",
            VineStructureKind::D,
        ),
    ] {
        let fixture: VineLogPdfFixture = load_vine_fixture(fixture_name.0);
        let model = match fixture_name.1 {
            VineStructureKind::C => {
                VineCopula::gaussian_c_vine(fixture.order.clone(), array2(&fixture.correlation))
            }
            VineStructureKind::D => {
                VineCopula::gaussian_d_vine(fixture.order.clone(), array2(&fixture.correlation))
            }
            VineStructureKind::R => unreachable!("only C and D vines are exercised here"),
        }
        .expect("vine model should build");
        let data = PseudoObs::new(array2(&fixture.inputs)).expect("inputs should be valid");

        let serial = model
            .log_pdf(&data, &serial_eval_options())
            .expect("serial vine log pdf should evaluate");
        let metal = model
            .log_pdf(
                &data,
                &EvalOptions {
                    exec: ExecPolicy::Force(Device::Metal),
                    ..EvalOptions::default()
                },
            )
            .expect("metal vine log pdf should evaluate");

        assert_close_slice(&metal, &serial, 1e-3);
    }
}

#[test]
fn forced_metal_mixed_r_vine_falls_back_to_cpu() {
    if !accel_device_available(rscopulas::accel::Device::Metal) {
        return;
    }

    let fixture: RVineLogPdfFixture = load_vine_fixture("mixed_r_vine_log_pdf_d5_case01.json");
    let model = build_r_vine_model(&fixture.trees, fixture.truncation_level);
    let data = PseudoObs::new(array2(&fixture.inputs)).expect("inputs should be valid");

    let serial = model
        .log_pdf(&data, &serial_eval_options())
        .expect("serial log pdf should evaluate");
    let metal = model
        .log_pdf(
            &data,
            &EvalOptions {
                exec: ExecPolicy::Force(Device::Metal),
                ..EvalOptions::default()
            },
        )
        .expect("metal fallback log pdf should evaluate");

    assert_eq!(metal, serial);
}

#[cfg(all(feature = "cuda", any(target_os = "linux", target_os = "windows")))]
#[test]
fn forced_cuda_gaussian_vines_match_cpu_when_available() {
    if !accel_device_available(rscopulas::accel::Device::Cuda(0)) {
        return;
    }

    let fixture: VineLogPdfFixture = load_vine_fixture("gaussian_c_vine_log_pdf_d4_case01.json");
    let model = VineCopula::gaussian_c_vine(fixture.order, array2(&fixture.correlation))
        .expect("vine model should build");
    let data = PseudoObs::new(array2(&fixture.inputs)).expect("inputs should be valid");

    let serial = model
        .log_pdf(&data, &serial_eval_options())
        .expect("serial vine log pdf should evaluate");
    let cuda = model
        .log_pdf(
            &data,
            &EvalOptions {
                exec: ExecPolicy::Force(Device::Cuda(0)),
                ..EvalOptions::default()
            },
        )
        .expect("cuda vine log pdf should evaluate");

    assert_close_slice(&cuda, &serial, 1e-10);
}

#[test]
fn unsupported_accelerator_requests_surface_backend_errors() {
    let fixture: GaussianLogPdfFixture = load_copula_fixture("gaussian_log_pdf_d2_case01.json");
    let model =
        GaussianCopula::new(array2(&fixture.correlation)).expect("correlation should be valid");
    let data = PseudoObs::new(array2(&fixture.inputs)).expect("inputs should be valid");

    for exec in [
        ExecPolicy::Force(Device::Cuda(0)),
        ExecPolicy::Force(Device::Metal),
    ] {
        let error = model
            .log_pdf(
                &data,
                &EvalOptions {
                    exec,
                    ..EvalOptions::default()
                },
            )
            .expect_err("unsupported accelerator request should fail");
        assert!(matches!(error, CopulaError::Backend(_)));
    }
}

#[test]
fn sample_force_cpu_matches_auto_for_gaussian() {
    let fixture: GaussianLogPdfFixture = load_copula_fixture("gaussian_log_pdf_d2_case01.json");
    let model =
        GaussianCopula::new(array2(&fixture.correlation)).expect("correlation should be valid");
    let mut auto_rng = StdRng::seed_from_u64(1234);
    let mut serial_rng = StdRng::seed_from_u64(1234);

    let auto = model
        .sample(128, &mut auto_rng, &SampleOptions::default())
        .expect("auto sampling should succeed");
    let serial = model
        .sample(
            128,
            &mut serial_rng,
            &SampleOptions {
                exec: ExecPolicy::Force(Device::Cpu),
            },
        )
        .expect("serial sampling should succeed");

    assert_eq!(auto, serial);
}

fn pair_fit_options(exec: ExecPolicy) -> VineFitOptions {
    VineFitOptions {
        base: FitOptions {
            exec,
            ..FitOptions::default()
        },
        family_set: vec![
            PairCopulaFamily::Independence,
            PairCopulaFamily::Gaussian,
            PairCopulaFamily::StudentT,
            PairCopulaFamily::Clayton,
            PairCopulaFamily::Frank,
            PairCopulaFamily::Gumbel,
        ],
        include_rotations: true,
        ..VineFitOptions::default()
    }
}

fn gaussian_only_pair_fit_options(exec: ExecPolicy) -> VineFitOptions {
    VineFitOptions {
        base: FitOptions {
            exec,
            ..FitOptions::default()
        },
        family_set: vec![PairCopulaFamily::Gaussian],
        include_rotations: false,
        ..VineFitOptions::default()
    }
}

fn serial_eval_options() -> EvalOptions {
    EvalOptions {
        exec: ExecPolicy::Force(Device::Cpu),
        ..EvalOptions::default()
    }
}

fn serial_fit_options() -> FitOptions {
    FitOptions {
        exec: ExecPolicy::Force(Device::Cpu),
        ..FitOptions::default()
    }
}

fn build_r_vine_model(trees: &[TreeFixture], truncation_level: Option<usize>) -> VineCopula {
    let trees = trees
        .iter()
        .map(|tree| VineTree {
            level: tree.level,
            edges: tree
                .edges
                .iter()
                .map(|edge| VineEdge {
                    tree: tree.level,
                    conditioned: (edge.conditioned[0], edge.conditioned[1]),
                    conditioning: edge.conditioning.clone(),
                    copula: PairCopulaSpec {
                        family: parse_family(&edge.family),
                        rotation: parse_rotation(&edge.rotation),
                        params: parse_params(&edge.params),
                    },
                })
                .collect(),
        })
        .collect::<Vec<_>>();

    VineCopula::from_trees(VineStructureKind::R, trees, truncation_level)
        .expect("fixture trees should form a valid vine")
}

fn parse_family(value: &str) -> PairCopulaFamily {
    match value {
        "Independence" | "independence" => PairCopulaFamily::Independence,
        "Gaussian" | "gaussian" => PairCopulaFamily::Gaussian,
        "StudentT" | "student_t" => PairCopulaFamily::StudentT,
        "Clayton" | "clayton" => PairCopulaFamily::Clayton,
        "Frank" | "frank" => PairCopulaFamily::Frank,
        "Gumbel" | "gumbel" => PairCopulaFamily::Gumbel,
        other => panic!("unexpected family {other}"),
    }
}

fn parse_rotation(value: &str) -> Rotation {
    match value {
        "R0" => Rotation::R0,
        "R90" => Rotation::R90,
        "R180" => Rotation::R180,
        "R270" => Rotation::R270,
        other => panic!("unexpected rotation {other}"),
    }
}

fn parse_params(values: &[f64]) -> PairCopulaParams {
    match values {
        [] => PairCopulaParams::None,
        [value] => PairCopulaParams::One(*value),
        [first, second] => PairCopulaParams::Two(*first, *second),
        _ => panic!("unexpected parameter arity"),
    }
}

fn copula_fixture_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/reference/r-copula/v1_1_3")
}

fn vine_fixture_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/reference/vinecopula/v2")
}

fn load_copula_fixture<T: for<'de> Deserialize<'de>>(name: &str) -> T {
    let path = copula_fixture_dir().join(name);
    let bytes = fs::read(path).expect("fixture should exist");
    serde_json::from_slice(&bytes).expect("fixture should deserialize")
}

fn load_vine_fixture<T: for<'de> Deserialize<'de>>(name: &str) -> T {
    let path = vine_fixture_dir().join(name);
    let bytes = fs::read(path).expect("fixture should exist");
    serde_json::from_slice(&bytes).expect("fixture should deserialize")
}

fn array2(rows: &[Vec<f64>]) -> Array2<f64> {
    let nrows = rows.len();
    let ncols = rows.first().map_or(0, Vec::len);
    let data = rows
        .iter()
        .flat_map(|row| row.iter().copied())
        .collect::<Vec<_>>();
    Array2::from_shape_vec((nrows, ncols), data).expect("rows should form a matrix")
}

fn assert_close_slice(left: &[f64], right: &[f64], tol: f64) {
    assert_eq!(left.len(), right.len());
    for (idx, (lhs, rhs)) in left.iter().zip(right.iter()).enumerate() {
        assert!(
            (lhs - rhs).abs() <= tol,
            "values differed at index {idx}: left={lhs}, right={rhs}, tol={tol}"
        );
    }
}