survival 1.0.17

A high-performance survival analysis library written in Rust with Python bindings
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
#[cfg(test)]
mod tests {
    use crate::regression::coxfit6::{CoxFit, Method as CoxMethod};
    use crate::surv_analysis::nelson_aalen::nelson_aalen;
    use crate::surv_analysis::survfitkm::compute_survfitkm;
    use crate::validation::logrank::{WeightType, weighted_logrank_test};
    use crate::validation::rmst::compute_rmst;
    use ndarray::{Array1, Array2};
    use serde::Deserialize;
    use std::fs;

    const STANDARD_TOL: f64 = 1e-3;
    const STAT_TOL: f64 = 0.05;

    fn rel_approx_eq(a: f64, b: f64, rel_tol: f64) -> bool {
        if a.is_nan() && b.is_nan() {
            return true;
        }
        let max_abs = a.abs().max(b.abs());
        if max_abs < 1e-10 {
            return true;
        }
        (a - b).abs() / max_abs < rel_tol
    }

    #[derive(Debug, Deserialize)]
    struct RExpectedValues {
        metadata: Metadata,
        aml: AmlData,
        lung: LungData,
        ovarian: OvarianData,
        edge_cases: EdgeCases,
        rmst: RmstData,
    }

    #[derive(Debug, Deserialize)]
    struct Metadata {
        survival_version: String,
        r_version: String,
        note: String,
    }

    #[derive(Debug, Deserialize)]
    struct AmlData {
        maintained: DataGroup,
        nonmaintained: DataGroup,
        combined: CombinedDataGroup,
        km_maintained: KaplanMeierResult,
        nelson_aalen_maintained: NelsonAalenResult,
        logrank: LogRankResult,
        wilcoxon: WilcoxonResult,
        coxph_breslow: CoxphResult,
        coxph_efron: CoxphEfronResult,
    }

    #[derive(Debug, Deserialize)]
    struct DataGroup {
        time: Vec<f64>,
        status: Vec<i32>,
    }

    #[derive(Debug, Deserialize)]
    struct CombinedDataGroup {
        time: Vec<f64>,
        status: Vec<i32>,
        group: Vec<i32>,
    }

    #[derive(Debug, Deserialize)]
    struct KaplanMeierResult {
        time: Vec<f64>,
        survival: Vec<f64>,
    }

    #[derive(Debug, Deserialize)]
    struct NelsonAalenResult {
        time: Vec<f64>,
        cumulative_hazard: Vec<f64>,
    }

    #[derive(Debug, Deserialize)]
    struct LogRankResult {
        chisq: f64,
        df: i32,
        p_value: f64,
    }

    #[derive(Debug, Deserialize)]
    struct WilcoxonResult {
        chisq: f64,
    }

    #[derive(Debug, Deserialize)]
    struct CoxphResult {
        coefficients: Vec<f64>,
        hazard_ratio: Vec<f64>,
        loglik: Vec<f64>,
    }

    #[derive(Debug, Deserialize)]
    struct CoxphEfronResult {
        coefficients: Vec<f64>,
        loglik: Vec<f64>,
    }

    #[derive(Debug, Deserialize)]
    struct LungData {
        data: LungDataFields,
        logrank_sex: LogRankSexResult,
    }

    #[derive(Debug, Deserialize)]
    struct LungDataFields {
        time: Vec<f64>,
        status: Vec<i32>,
        sex: Vec<i32>,
        age: Vec<f64>,
    }

    #[derive(Debug, Deserialize)]
    struct LogRankSexResult {
        chisq: f64,
    }

    #[derive(Debug, Deserialize)]
    struct OvarianData {
        data: OvarianDataFields,
        logrank: OvarianLogrank,
        km: OvarianKm,
    }

    #[derive(Debug, Deserialize)]
    struct OvarianDataFields {
        time: Vec<f64>,
        status: Vec<i32>,
        rx: Vec<i32>,
    }

    #[derive(Debug, Deserialize)]
    struct OvarianLogrank {
        chisq: f64,
    }

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

    #[derive(Debug, Deserialize)]
    struct EdgeCases {
        tied_events: EdgeCaseKm,
        simple_nelson_aalen: SimpleNelsonAalen,
        with_censoring: WithCensoring,
        identical_groups_logrank: IdenticalGroupsLogrank,
    }

    #[derive(Debug, Deserialize)]
    struct EdgeCaseKm {
        time: Vec<f64>,
        survival: Vec<f64>,
    }

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

    #[derive(Debug, Deserialize)]
    struct WithCensoring {
        time: Vec<f64>,
        cumulative_hazard: Vec<f64>,
    }

    #[derive(Debug, Deserialize)]
    struct IdenticalGroupsLogrank {
        chisq: f64,
    }

    #[derive(Debug, Deserialize)]
    struct RmstData {
        aml_maintained_tau30: f64,
        aml_nonmaintained_tau30: f64,
    }

    fn load_expected_values() -> RExpectedValues {
        let json_path = concat!(env!("CARGO_MANIFEST_DIR"), "/test/r_expected_values.json");
        let json_content =
            fs::read_to_string(json_path).expect("Failed to read r_expected_values.json");
        serde_json::from_str(&json_content).expect("Failed to parse r_expected_values.json")
    }

    #[test]
    fn test_aml_logrank_exact() {
        let expected = load_expected_values();
        let aml = &expected.aml;

        let result = weighted_logrank_test(
            &aml.combined.time,
            &aml.combined.status,
            &aml.combined.group,
            WeightType::LogRank,
        );

        assert!(
            rel_approx_eq(result.statistic, aml.logrank.chisq, STAT_TOL),
            "Log-rank chi-squared: expected {}, got {}",
            aml.logrank.chisq,
            result.statistic
        );

        assert!(
            rel_approx_eq(result.p_value, aml.logrank.p_value, STAT_TOL),
            "Log-rank p-value: expected {}, got {}",
            aml.logrank.p_value,
            result.p_value
        );

        assert_eq!(
            result.df, aml.logrank.df as usize,
            "Degrees of freedom mismatch"
        );
    }

    #[test]
    fn test_aml_wilcoxon_exact() {
        let expected = load_expected_values();
        let aml = &expected.aml;

        let result = weighted_logrank_test(
            &aml.combined.time,
            &aml.combined.status,
            &aml.combined.group,
            WeightType::Wilcoxon,
        );

        assert!(
            rel_approx_eq(result.statistic, aml.wilcoxon.chisq, STAT_TOL),
            "Wilcoxon chi-squared: expected {}, got {}",
            aml.wilcoxon.chisq,
            result.statistic
        );
    }

    #[test]
    fn test_aml_km_maintained_exact() {
        let expected = load_expected_values();
        let aml = &expected.aml;

        let status_f64: Vec<f64> = aml.maintained.status.iter().map(|&s| s as f64).collect();
        let weights = vec![1.0; aml.maintained.time.len()];
        let position = vec![0i32; aml.maintained.time.len()];

        let result = compute_survfitkm(
            &aml.maintained.time,
            &status_f64,
            &weights,
            None,
            &position,
            false,
            0,
        );

        for (i, &r_surv) in aml.km_maintained.survival.iter().enumerate() {
            if i < result.estimate.len() {
                assert!(
                    rel_approx_eq(result.estimate[i], r_surv, STANDARD_TOL),
                    "KM survival at time {}: expected {}, got {}",
                    aml.km_maintained.time[i],
                    r_surv,
                    result.estimate[i]
                );
            }
        }
    }

    #[test]
    fn test_aml_nelson_aalen_exact() {
        let expected = load_expected_values();
        let aml = &expected.aml;

        let result = nelson_aalen(&aml.maintained.time, &aml.maintained.status, None, 0.95);

        for (i, &our_time) in result.time.iter().enumerate() {
            if let Some(pos) = aml
                .nelson_aalen_maintained
                .time
                .iter()
                .position(|&t| (t - our_time).abs() < 0.01)
            {
                let r_cumhaz = aml.nelson_aalen_maintained.cumulative_hazard[pos];
                assert!(
                    rel_approx_eq(result.cumulative_hazard[i], r_cumhaz, STANDARD_TOL),
                    "Nelson-Aalen cumhaz at time {}: expected {}, got {}",
                    our_time,
                    r_cumhaz,
                    result.cumulative_hazard[i]
                );
            }
        }
    }

    #[test]
    fn test_aml_coxph_breslow_exact() {
        let expected = load_expected_values();
        let aml = &expected.aml;

        let n = aml.combined.time.len();

        let mut indices: Vec<usize> = (0..n).collect();
        indices.sort_by(|&a, &b| {
            aml.combined.time[a]
                .partial_cmp(&aml.combined.time[b])
                .unwrap()
        });

        let time: Vec<f64> = indices.iter().map(|&i| aml.combined.time[i]).collect();
        let status: Vec<i32> = indices.iter().map(|&i| aml.combined.status[i]).collect();
        let group: Vec<i32> = indices.iter().map(|&i| aml.combined.group[i]).collect();

        let mut covar = Array2::<f64>::zeros((n, 1));
        for i in 0..n {
            covar[[i, 0]] = group[i] as f64;
        }

        let mut cox_fit = CoxFit::new(
            Array1::from_vec(time),
            Array1::from_vec(status),
            covar,
            Array1::zeros(n),
            Array1::zeros(n),
            Array1::from_elem(n, 1.0),
            CoxMethod::Breslow,
            25,
            1e-9,
            1e-9,
            vec![true],
            vec![0.0],
        )
        .expect("Cox fit init failed");

        cox_fit.fit().expect("Cox fit failed");
        let (beta, _means, _u, _imat, loglik, _sctest, _flag, _iter) = cox_fit.results();

        let r_coef = aml.coxph_breslow.coefficients[0];
        let r_hr = aml.coxph_breslow.hazard_ratio[0];

        assert!(
            rel_approx_eq(beta[0].abs(), r_coef.abs(), STAT_TOL),
            "Cox coefficient magnitude: expected {}, got {}",
            r_coef.abs(),
            beta[0].abs()
        );

        let hr = beta[0].exp();
        let hr_match = rel_approx_eq(hr, r_hr, STAT_TOL) || rel_approx_eq(hr, 1.0 / r_hr, STAT_TOL);
        assert!(
            hr_match,
            "Cox hazard ratio: expected {} or {}, got {}",
            r_hr,
            1.0 / r_hr,
            hr
        );

        let r_loglik_final = aml.coxph_breslow.loglik[1];
        assert!(
            rel_approx_eq(loglik[1], r_loglik_final, STAT_TOL),
            "Cox log-likelihood: expected {}, got {}",
            r_loglik_final,
            loglik[1]
        );
    }

    #[test]
    fn test_aml_coxph_efron_exact() {
        let expected = load_expected_values();
        let aml = &expected.aml;

        let n = aml.combined.time.len();

        let mut indices: Vec<usize> = (0..n).collect();
        indices.sort_by(|&a, &b| {
            aml.combined.time[a]
                .partial_cmp(&aml.combined.time[b])
                .unwrap()
        });

        let time: Vec<f64> = indices.iter().map(|&i| aml.combined.time[i]).collect();
        let status: Vec<i32> = indices.iter().map(|&i| aml.combined.status[i]).collect();
        let group: Vec<i32> = indices.iter().map(|&i| aml.combined.group[i]).collect();

        let mut covar = Array2::<f64>::zeros((n, 1));
        for i in 0..n {
            covar[[i, 0]] = group[i] as f64;
        }

        let mut cox_fit = CoxFit::new(
            Array1::from_vec(time),
            Array1::from_vec(status),
            covar,
            Array1::zeros(n),
            Array1::zeros(n),
            Array1::from_elem(n, 1.0),
            CoxMethod::Efron,
            25,
            1e-9,
            1e-9,
            vec![true],
            vec![0.0],
        )
        .expect("Cox fit init failed");

        cox_fit.fit().expect("Cox fit failed");
        let (beta, _means, _u, _imat, loglik, _sctest, _flag, _iter) = cox_fit.results();

        let r_coef = aml.coxph_efron.coefficients[0];
        let r_loglik = aml.coxph_efron.loglik[1];

        assert!(
            rel_approx_eq(beta[0].abs(), r_coef.abs(), STAT_TOL),
            "Efron coefficient: expected {}, got {}",
            r_coef,
            beta[0]
        );

        assert!(
            rel_approx_eq(loglik[1], r_loglik, STAT_TOL),
            "Efron log-likelihood: expected {}, got {}",
            r_loglik,
            loglik[1]
        );
    }

    #[test]
    fn test_lung_coxph_exact() {
        let expected = load_expected_values();
        let lung = &expected.lung;

        let n = lung.data.time.len();
        let mut covar = Array2::<f64>::zeros((n, 2));
        for i in 0..n {
            covar[[i, 0]] = lung.data.age[i];
            covar[[i, 1]] = lung.data.sex[i] as f64;
        }

        let mut cox_fit = CoxFit::new(
            Array1::from_vec(lung.data.time.clone()),
            Array1::from_vec(lung.data.status.clone()),
            covar,
            Array1::zeros(n),
            Array1::zeros(n),
            Array1::from_elem(n, 1.0),
            CoxMethod::Breslow,
            25,
            1e-9,
            1e-9,
            vec![true, true],
            vec![0.0, 0.0],
        )
        .expect("Cox fit init failed");

        cox_fit.fit().expect("Cox fit failed");
        let (beta, _means, _u, _imat, _loglik, _sctest, _flag, iter) = cox_fit.results();

        assert!(iter < 25, "Cox fit should converge");
        assert!(beta[0].is_finite(), "Age coefficient should be finite");
        assert!(beta[1].is_finite(), "Sex coefficient should be finite");
    }

    #[test]
    fn test_lung_logrank_sex_exact() {
        let expected = load_expected_values();
        let lung = &expected.lung;

        let result = weighted_logrank_test(
            &lung.data.time,
            &lung.data.status,
            &lung.data.sex,
            WeightType::LogRank,
        );

        assert!(
            rel_approx_eq(result.statistic, lung.logrank_sex.chisq, STAT_TOL),
            "Lung logrank chi-squared: expected {}, got {}",
            lung.logrank_sex.chisq,
            result.statistic
        );
    }

    #[test]
    fn test_ovarian_logrank_exact() {
        let expected = load_expected_values();
        let ovarian = &expected.ovarian;

        let result = weighted_logrank_test(
            &ovarian.data.time,
            &ovarian.data.status,
            &ovarian.data.rx,
            WeightType::LogRank,
        );

        assert!(
            rel_approx_eq(result.statistic, ovarian.logrank.chisq, STAT_TOL),
            "Ovarian logrank chi-squared: expected {}, got {}",
            ovarian.logrank.chisq,
            result.statistic
        );
    }

    #[test]
    fn test_ovarian_km_exact() {
        let expected = load_expected_values();
        let ovarian = &expected.ovarian;

        let status_f64: Vec<f64> = ovarian.data.status.iter().map(|&s| s as f64).collect();
        let weights = vec![1.0; ovarian.data.time.len()];
        let position = vec![0i32; ovarian.data.time.len()];

        let result = compute_survfitkm(
            &ovarian.data.time,
            &status_f64,
            &weights,
            None,
            &position,
            false,
            0,
        );

        for (i, &r_surv) in ovarian.km.survival.iter().take(5).enumerate() {
            if i < result.estimate.len() {
                assert!(
                    rel_approx_eq(result.estimate[i], r_surv, STANDARD_TOL),
                    "Ovarian KM survival at index {}: expected {}, got {}",
                    i,
                    r_surv,
                    result.estimate[i]
                );
            }
        }
    }

    #[test]
    fn test_edge_case_simple_nelson_aalen_exact() {
        let expected = load_expected_values();
        let edge = &expected.edge_cases.simple_nelson_aalen;

        let time = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let status = vec![1, 1, 1, 1, 1];

        let result = nelson_aalen(&time, &status, None, 0.95);

        for (i, &r_cumhaz) in edge.cumulative_hazard.iter().enumerate() {
            assert!(
                rel_approx_eq(result.cumulative_hazard[i], r_cumhaz, STANDARD_TOL),
                "Simple NA cumhaz at {}: expected {}, got {}",
                i,
                r_cumhaz,
                result.cumulative_hazard[i]
            );
        }
    }

    #[test]
    fn test_edge_case_with_censoring_exact() {
        let expected = load_expected_values();
        let edge = &expected.edge_cases.with_censoring;

        let time = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let status = vec![1, 0, 1, 0, 1, 0];

        let result = nelson_aalen(&time, &status, None, 0.95);

        assert_eq!(
            result.time.len(),
            edge.time.len(),
            "Number of event times mismatch"
        );

        for (i, &r_cumhaz) in edge.cumulative_hazard.iter().enumerate() {
            if i < result.cumulative_hazard.len() {
                assert!(
                    rel_approx_eq(result.cumulative_hazard[i], r_cumhaz, STANDARD_TOL),
                    "Censored NA cumhaz at {}: expected {}, got {}",
                    i,
                    r_cumhaz,
                    result.cumulative_hazard[i]
                );
            }
        }
    }

    #[test]
    fn test_edge_case_tied_events_exact() {
        let expected = load_expected_values();
        let edge = &expected.edge_cases.tied_events;

        let time = vec![5.0, 5.0, 5.0, 10.0, 10.0, 15.0];
        let status_f64 = vec![1.0, 1.0, 0.0, 1.0, 1.0, 1.0];
        let weights = vec![1.0; 6];
        let position = vec![0i32; 6];

        let result = compute_survfitkm(&time, &status_f64, &weights, None, &position, false, 0);

        assert_eq!(
            result.time.len(),
            edge.time.len(),
            "Tied events: number of time points mismatch"
        );

        for (i, &r_surv) in edge.survival.iter().enumerate() {
            if i < result.estimate.len() {
                assert!(
                    rel_approx_eq(result.estimate[i], r_surv, STANDARD_TOL),
                    "Tied events survival at {}: expected {}, got {}",
                    i,
                    r_surv,
                    result.estimate[i]
                );
            }
        }
    }

    #[test]
    fn test_edge_case_identical_groups_exact() {
        let expected = load_expected_values();
        let edge = &expected.edge_cases.identical_groups_logrank;

        let time = vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0];
        let status = vec![1, 1, 1, 1, 1, 1];
        let group = vec![0, 0, 0, 1, 1, 1];

        let result = weighted_logrank_test(&time, &status, &group, WeightType::LogRank);

        assert!(
            rel_approx_eq(result.statistic, edge.chisq, STAT_TOL),
            "Identical groups chi-squared: expected {}, got {}",
            edge.chisq,
            result.statistic
        );
        assert!(
            result.p_value > 0.9,
            "Identical groups p-value should be ~1, got {}",
            result.p_value
        );
    }

    #[test]
    fn test_rmst_aml_maintained_exact() {
        let expected = load_expected_values();
        let aml = &expected.aml;

        let result = compute_rmst(&aml.maintained.time, &aml.maintained.status, 30.0, 0.95);

        assert!(
            rel_approx_eq(result.rmst, expected.rmst.aml_maintained_tau30, STAT_TOL),
            "RMST maintained tau=30: expected {}, got {}",
            expected.rmst.aml_maintained_tau30,
            result.rmst
        );
    }

    #[test]
    fn test_rmst_aml_nonmaintained_exact() {
        let expected = load_expected_values();
        let aml = &expected.aml;

        let result = compute_rmst(
            &aml.nonmaintained.time,
            &aml.nonmaintained.status,
            30.0,
            0.95,
        );

        assert!(
            rel_approx_eq(result.rmst, expected.rmst.aml_nonmaintained_tau30, STAT_TOL),
            "RMST nonmaintained tau=30: expected {}, got {}",
            expected.rmst.aml_nonmaintained_tau30,
            result.rmst
        );
    }

    #[test]
    fn test_expected_values_loaded() {
        let expected = load_expected_values();

        assert!(
            !expected.metadata.survival_version.is_empty(),
            "survival_version should not be empty"
        );
        assert!(
            !expected.metadata.r_version.is_empty(),
            "r_version should not be empty"
        );
        assert!(
            !expected.metadata.note.is_empty(),
            "note should not be empty"
        );

        assert_eq!(expected.aml.maintained.time.len(), 11);
        assert_eq!(expected.aml.nonmaintained.time.len(), 12);
        assert_eq!(expected.aml.combined.time.len(), 23);
    }
}