survival 1.1.29

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
#![allow(
    unused_variables,
    unused_imports,
    unused_mut,
    unused_assignments,
    clippy::too_many_arguments,
    clippy::needless_range_loop
)]

use pyo3::prelude::*;
use rayon::prelude::*;

#[derive(Debug, Clone)]
#[pyclass]
pub struct MSMResult {
    #[pyo3(get)]
    pub coefficients: Vec<f64>,
    #[pyo3(get)]
    pub std_errors: Vec<f64>,
    #[pyo3(get)]
    pub hazard_ratios: Vec<f64>,
    #[pyo3(get)]
    pub hr_ci_lower: Vec<f64>,
    #[pyo3(get)]
    pub hr_ci_upper: Vec<f64>,
    #[pyo3(get)]
    pub weights: Vec<f64>,
    #[pyo3(get)]
    pub effective_n: f64,
    #[pyo3(get)]
    pub log_likelihood: f64,
}

fn fit_propensity_model(treatment: &[i32], x: &[f64], n: usize, p: usize) -> Vec<f64> {
    let mut beta = vec![0.0; p];

    for _ in 0..100 {
        let mut gradient = vec![0.0; p];
        let mut hessian_diag = vec![0.0; p];

        for i in 0..n {
            let mut eta = 0.0;
            for j in 0..p {
                eta += x[i * p + j] * beta[j];
            }
            let prob = 1.0 / (1.0 + (-eta.clamp(-700.0, 700.0)).exp());
            let residual = treatment[i] as f64 - prob;

            for j in 0..p {
                gradient[j] += x[i * p + j] * residual;
                hessian_diag[j] += x[i * p + j] * x[i * p + j] * prob * (1.0 - prob);
            }
        }

        for j in 0..p {
            if hessian_diag[j].abs() > 1e-10 {
                beta[j] += gradient[j] / hessian_diag[j];
            }
        }
    }

    beta
}

fn compute_propensity_scores(x: &[f64], beta: &[f64], n: usize, p: usize) -> Vec<f64> {
    (0..n)
        .map(|i| {
            let mut eta = 0.0;
            for j in 0..p {
                eta += x[i * p + j] * beta[j];
            }
            1.0 / (1.0 + (-eta.clamp(-700.0, 700.0)).exp())
        })
        .collect()
}

fn compute_iptw_weights(
    treatment: &[i32],
    propensity: &[f64],
    stabilized: bool,
    trim: f64,
) -> Vec<f64> {
    let n = treatment.len();

    let trimmed_ps: Vec<f64> = propensity
        .iter()
        .map(|&p| p.clamp(trim, 1.0 - trim))
        .collect();

    let mut weights: Vec<f64> = (0..n)
        .map(|i| {
            if treatment[i] == 1 {
                1.0 / trimmed_ps[i]
            } else {
                1.0 / (1.0 - trimmed_ps[i])
            }
        })
        .collect();

    if stabilized {
        let prop_treated = treatment.iter().map(|&t| t as f64).sum::<f64>() / n as f64;
        for i in 0..n {
            if treatment[i] == 1 {
                weights[i] *= prop_treated;
            } else {
                weights[i] *= 1.0 - prop_treated;
            }
        }
    }

    weights
}

fn weighted_cox_fit(
    time: &[f64],
    status: &[i32],
    x: &[f64],
    weights: &[f64],
    n: usize,
    p: usize,
) -> (Vec<f64>, Vec<f64>, f64) {
    let mut beta = vec![0.0; p];
    let mut loglik = f64::NEG_INFINITY;

    for _ in 0..100 {
        let mut gradient = vec![0.0; p];
        let mut hessian_diag = vec![0.0; p];

        let mut indices: Vec<usize> = (0..n).collect();
        indices.sort_by(|&a, &b| {
            time[b]
                .partial_cmp(&time[a])
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        let eta: Vec<f64> = (0..n)
            .map(|i| {
                let mut e = 0.0;
                for j in 0..p {
                    e += x[i * p + j] * beta[j];
                }
                e.clamp(-700.0, 700.0)
            })
            .collect();

        let exp_eta: Vec<f64> = eta.iter().map(|&e| e.exp()).collect();

        let mut risk_sum = 0.0;
        let mut weighted_x = vec![0.0; p];
        let mut weighted_x_sq = vec![0.0; p];
        let mut ll = 0.0;

        for &i in &indices {
            let w = weights[i] * exp_eta[i];
            risk_sum += w;

            for j in 0..p {
                weighted_x[j] += w * x[i * p + j];
                weighted_x_sq[j] += w * x[i * p + j] * x[i * p + j];
            }

            if status[i] == 1 && risk_sum > 0.0 {
                ll += weights[i] * (eta[i] - risk_sum.ln());

                for j in 0..p {
                    let x_bar = weighted_x[j] / risk_sum;
                    let x_sq_bar = weighted_x_sq[j] / risk_sum;

                    gradient[j] += weights[i] * (x[i * p + j] - x_bar);
                    hessian_diag[j] += weights[i] * (x_sq_bar - x_bar * x_bar);
                }
            }
        }

        loglik = ll;

        let mut max_change: f64 = 0.0;
        for j in 0..p {
            if hessian_diag[j].abs() > 1e-10 {
                let update = gradient[j] / hessian_diag[j];
                beta[j] += update;
                max_change = max_change.max(update.abs());
            }
        }

        if max_change < 1e-6 {
            break;
        }
    }

    let std_errors: Vec<f64> = {
        let mut se = vec![0.0; p];
        let eta: Vec<f64> = (0..n)
            .map(|i| {
                let mut e = 0.0;
                for j in 0..p {
                    e += x[i * p + j] * beta[j];
                }
                e.clamp(-700.0, 700.0)
            })
            .collect();
        let exp_eta: Vec<f64> = eta.iter().map(|&e| e.exp()).collect();

        let mut indices: Vec<usize> = (0..n).collect();
        indices.sort_by(|&a, &b| {
            time[b]
                .partial_cmp(&time[a])
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        let mut risk_sum = 0.0;
        let mut weighted_x = vec![0.0; p];
        let mut weighted_x_sq = vec![0.0; p];
        let mut info = vec![0.0; p];

        for &i in &indices {
            let w = weights[i] * exp_eta[i];
            risk_sum += w;

            for j in 0..p {
                weighted_x[j] += w * x[i * p + j];
                weighted_x_sq[j] += w * x[i * p + j] * x[i * p + j];
            }

            if status[i] == 1 && risk_sum > 0.0 {
                for j in 0..p {
                    let x_bar = weighted_x[j] / risk_sum;
                    let x_sq_bar = weighted_x_sq[j] / risk_sum;
                    info[j] += weights[i] * (x_sq_bar - x_bar * x_bar);
                }
            }
        }

        for j in 0..p {
            se[j] = if info[j] > 1e-10 {
                (1.0 / info[j]).sqrt()
            } else {
                f64::INFINITY
            };
        }
        se
    };

    (beta, std_errors, loglik)
}

#[pyfunction]
#[pyo3(signature = (time, status, treatment, x_outcome, x_propensity, n_obs, n_outcome_vars, n_propensity_vars, stabilized=true, trim=None))]
pub fn marginal_structural_model(
    time: Vec<f64>,
    status: Vec<i32>,
    treatment: Vec<i32>,
    x_outcome: Vec<f64>,
    x_propensity: Vec<f64>,
    n_obs: usize,
    n_outcome_vars: usize,
    n_propensity_vars: usize,
    stabilized: bool,
    trim: Option<f64>,
) -> PyResult<MSMResult> {
    if time.len() != n_obs || status.len() != n_obs || treatment.len() != n_obs {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "Input arrays must have length n_obs",
        ));
    }

    let trim_val = trim.unwrap_or(0.01);

    let ps_beta = fit_propensity_model(&treatment, &x_propensity, n_obs, n_propensity_vars);
    let propensity = compute_propensity_scores(&x_propensity, &ps_beta, n_obs, n_propensity_vars);

    let weights = compute_iptw_weights(&treatment, &propensity, stabilized, trim_val);

    let effective_n =
        weights.iter().sum::<f64>().powi(2) / weights.iter().map(|&w| w.powi(2)).sum::<f64>();

    let p = n_outcome_vars + 1;
    let x_full: Vec<f64> = (0..n_obs)
        .flat_map(|i| {
            let mut row = vec![treatment[i] as f64];
            row.extend((0..n_outcome_vars).map(|j| x_outcome[i * n_outcome_vars + j]));
            row
        })
        .collect();

    let (coefficients, std_errors, log_likelihood) =
        weighted_cox_fit(&time, &status, &x_full, &weights, n_obs, p);

    let hazard_ratios: Vec<f64> = coefficients.iter().map(|&b| b.exp()).collect();

    let z = 1.96;
    let hr_ci_lower: Vec<f64> = coefficients
        .iter()
        .zip(std_errors.iter())
        .map(|(&b, &se)| (b - z * se).exp())
        .collect();

    let hr_ci_upper: Vec<f64> = coefficients
        .iter()
        .zip(std_errors.iter())
        .map(|(&b, &se)| (b + z * se).exp())
        .collect();

    Ok(MSMResult {
        coefficients,
        std_errors,
        hazard_ratios,
        hr_ci_lower,
        hr_ci_upper,
        weights,
        effective_n,
        log_likelihood,
    })
}

#[pyfunction]
#[pyo3(signature = (treatment_history, x_time_varying, n_obs, n_times, n_vars, stabilized=true, trim=None))]
pub fn compute_longitudinal_iptw(
    treatment_history: Vec<i32>,
    x_time_varying: Vec<f64>,
    n_obs: usize,
    n_times: usize,
    n_vars: usize,
    stabilized: bool,
    trim: Option<f64>,
) -> PyResult<Vec<f64>> {
    if treatment_history.len() != n_obs * n_times {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "treatment_history length mismatch",
        ));
    }
    if x_time_varying.len() != n_obs * n_times * n_vars {
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "x_time_varying dimensions mismatch",
        ));
    }

    let trim_val = trim.unwrap_or(0.01);

    let mut cumulative_weights = vec![1.0; n_obs];

    for t in 0..n_times {
        let treatment_t: Vec<i32> = (0..n_obs)
            .map(|i| treatment_history[i * n_times + t])
            .collect();

        let x_t: Vec<f64> = {
            let mut result = Vec::with_capacity(n_obs * n_vars);
            for i in 0..n_obs {
                for j in 0..n_vars {
                    result.push(x_time_varying[i * n_times * n_vars + t * n_vars + j]);
                }
            }
            result
        };

        let ps_beta = fit_propensity_model(&treatment_t, &x_t, n_obs, n_vars);
        let propensity = compute_propensity_scores(&x_t, &ps_beta, n_obs, n_vars);

        for i in 0..n_obs {
            let ps = propensity[i].clamp(trim_val, 1.0 - trim_val);
            let weight = if treatment_t[i] == 1 {
                1.0 / ps
            } else {
                1.0 / (1.0 - ps)
            };
            cumulative_weights[i] *= weight;
        }
    }

    if stabilized {
        let mean_weight = cumulative_weights.iter().sum::<f64>() / n_obs as f64;
        for w in &mut cumulative_weights {
            *w /= mean_weight;
        }
    }

    Ok(cumulative_weights)
}

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

    #[test]
    fn test_propensity_model() {
        let treatment = vec![1, 0, 1, 0, 1, 0];
        let x = vec![0.5, 0.3, 0.7, 0.2, 0.8, 0.4];
        let beta = fit_propensity_model(&treatment, &x, 6, 1);
        assert_eq!(beta.len(), 1);
    }

    #[test]
    fn test_iptw_weights() {
        let treatment = vec![1, 0, 1, 0];
        let propensity = vec![0.6, 0.4, 0.7, 0.3];
        let weights = compute_iptw_weights(&treatment, &propensity, true, 0.01);
        assert_eq!(weights.len(), 4);
        assert!(weights.iter().all(|&w| w > 0.0));
    }

    #[test]
    fn test_msm_basic() {
        let time = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let status = vec![1, 1, 0, 1, 0, 1];
        let treatment = vec![1, 0, 1, 0, 1, 0];
        let x_outcome = vec![0.5, 0.3, 0.7, 0.2, 0.8, 0.4];
        let x_propensity = vec![1.0, 0.5, 1.0, 0.3, 1.0, 0.7, 1.0, 0.2, 1.0, 0.8, 1.0, 0.4];

        let result = marginal_structural_model(
            time,
            status,
            treatment,
            x_outcome,
            x_propensity,
            6,
            1,
            2,
            true,
            Some(0.05),
        )
        .unwrap();

        assert!(!result.coefficients.is_empty());
        assert!(!result.hazard_ratios.is_empty());
    }
}