Skip to main content

rdrobust_core/
batch.rs

1//! Batched and multi-cutoff entry points.
2
3use rayon::prelude::*;
4
5use crate::rdrobust::{rdrobust_with, RdRobust, RdRobustOptions};
6
7/// One dataset in a batch: sharp design when `t` is `None`, fuzzy otherwise.
8///
9/// A `Dataset` carries everything a single [`crate::rdrobust::rdrobust_with`] call
10/// needs from the data side (the per-fit knobs live in the shared
11/// [`RdRobustOptions`]), so a batch fit is a true repeated `rdrobust`.
12pub struct Dataset<'a> {
13    /// Outcome variable, one value per observation.
14    pub y: &'a [f64],
15    /// Running (forcing) variable. For nearest-neighbor `vce`, must be sorted ascending.
16    pub x: &'a [f64],
17    /// Treatment-status variable for a fuzzy design; `None` runs a sharp design.
18    pub t: Option<&'a [f64]>,
19    /// Covariates flattened row-major as `n x dz`; `None` runs without covariate adjustment.
20    pub z: Option<&'a [f64]>,
21    /// Number of covariate columns in `z` (0 when `z` is `None`).
22    pub dz: usize,
23    /// Cluster ids; presence remaps the variance estimator to its cluster-robust form. `None` for no clustering.
24    pub cluster: Option<&'a [f64]>,
25    /// User weights multiplying the kernel; `None` for an unweighted fit.
26    pub weights: Option<&'a [f64]>,
27}
28
29/// Runs [`crate::rdrobust::rdrobust_with`] on many datasets in parallel.
30///
31/// Every dataset shares the same `opts` (including `opts.bwselect`), so each fit is
32/// a repeated `rdrobust` differing only in its data. The results preserve the input
33/// order of `datasets`.
34pub fn rdrobust_batch(datasets: &[Dataset], opts: &RdRobustOptions) -> Vec<RdRobust> {
35    datasets
36        .par_iter()
37        .map(|d| rdrobust_with(d.y, d.x, d.t, d.z, d.dz, d.cluster, d.weights, opts))
38        .collect()
39}
40
41/// Runs [`crate::rdrobust::rdrobust_with`] at many cutoffs on one dataset.
42///
43/// Each fit copies `opts` and overrides `opts.c` with the cutoff for that fit; every
44/// other knob (and the data) is shared. The results preserve the order of `cutoffs`.
45#[allow(clippy::too_many_arguments)]
46pub fn rdrobust_multi_cutoff(
47    y: &[f64],
48    x: &[f64],
49    fuzzy: Option<&[f64]>,
50    covs: Option<&[f64]>,
51    dz: usize,
52    cluster: Option<&[f64]>,
53    weights: Option<&[f64]>,
54    cutoffs: &[f64],
55    opts: &RdRobustOptions,
56) -> Vec<RdRobust> {
57    cutoffs
58        .par_iter()
59        .map(|&c| {
60            let mut o = *opts;
61            o.c = c;
62            rdrobust_with(y, x, fuzzy, covs, dz, cluster, weights, &o)
63        })
64        .collect()
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70    use crate::Vce;
71
72    fn dgp(seed: u64, n: usize) -> (Vec<f64>, Vec<f64>) {
73        let mut x: Vec<f64> = (0..n)
74            .map(|i| -1.0 + 2.0 * (i as f64) / (n as f64))
75            .collect();
76        x.sort_by(|a, b| a.partial_cmp(b).unwrap());
77        let y: Vec<f64> = x
78            .iter()
79            .enumerate()
80            .map(|(i, &xi)| {
81                let treat = if xi >= 0.0 { 1.0 } else { 0.0 };
82                0.5 * xi + 2.0 * treat + ((seed as f64 + i as f64) * 0.7).sin()
83            })
84            .collect();
85        (x, y)
86    }
87
88    #[test]
89    fn batch_equals_serial() {
90        let data: Vec<(Vec<f64>, Vec<f64>)> = (0..6).map(|s| dgp(s, 400)).collect();
91        let datasets: Vec<Dataset> = data
92            .iter()
93            .map(|(x, y)| Dataset {
94                y,
95                x,
96                t: None,
97                z: None,
98                dz: 0,
99                cluster: None,
100                weights: None,
101            })
102            .collect();
103        let opts = RdRobustOptions {
104            vce: Vce::Hc0,
105            ..Default::default()
106        };
107
108        let parallel = rdrobust_batch(&datasets, &opts);
109        let serial: Vec<RdRobust> = datasets
110            .iter()
111            .map(|d| rdrobust_with(d.y, d.x, d.t, d.z, d.dz, d.cluster, d.weights, &opts))
112            .collect();
113
114        assert_eq!(parallel.len(), serial.len());
115        for (a, b) in parallel.iter().zip(serial.iter()) {
116            assert_eq!(a.coef, b.coef);
117            assert_eq!(a.se, b.se);
118        }
119    }
120}