Skip to main content

rdrobust_core/
lib.rs

1//! Pure-Rust numerical core for robust local-polynomial regression-discontinuity
2//! (RD) estimation: a faithful port of the Calonico-Cattaneo-Farrell-Titiunik
3//! `rdrobust` package (R source `R/rdrobust/R/{functions,rdrobust,rdbwselect,rdplot}.R`).
4//!
5//! # What it computes
6//!
7//! - [`rdrobust()`]: the sharp or fuzzy RD point estimate, with conventional and
8//!   bias-corrected coefficients, CCT robust variance, z-statistics, p-values, and
9//!   confidence intervals.
10//! - [`rdbwselect`]: MSE- and CER-optimal bandwidth selection (all ten selectors).
11//! - [`rdplot()`]: the binned-scatter quantities and the global polynomial curve.
12//! - [`rdrobust_batch`] and [`rdrobust_multi_cutoff`]: rayon-parallel fan-out over
13//!   independent fits for Monte-Carlo and many-cutoff workloads.
14//!
15//! Outputs match the R reference to ~1e-8 on continuous quantities and ~1e-11 on
16//! clustered variances, and exactly on discrete decisions (neighbor sets,
17//! mass-point grouping, bin counts).
18//!
19//! # Example
20//!
21//! ```
22//! use rdrobust_core::{rdrobust_batch, Dataset, RdRobustOptions};
23//!
24//! // A small sharp RD: the outcome jumps by about 2 at the cutoff c = 0.
25//! let x: Vec<f64> = (0..200).map(|i| -1.0 + 2.0 * (i as f64 + 0.5) / 200.0).collect();
26//! let y: Vec<f64> = x
27//!     .iter()
28//!     .enumerate()
29//!     .map(|(i, &xi)| 0.5 * xi + if xi >= 0.0 { 2.0 } else { 0.0 } + 0.3 * (i as f64).sin())
30//!     .collect();
31//!
32//! let opts = RdRobustOptions::default(); // R defaults: p=1, q=2, triangular kernel, nn variance
33//! let ds = Dataset { y: &y, x: &x, t: None, z: None, dz: 0, cluster: None, weights: None };
34//! let out = rdrobust_batch(&[ds], &opts);
35//!
36//! // Each result's rows are [Conventional, Bias-Corrected, Robust].
37//! assert_eq!(out.len(), 1);
38//! assert!(out[0].coef[0].is_finite());
39//! assert!(out[0].se[2] >= 0.0);
40//! ```
41//!
42//! # Scope and limitations
43//!
44//! The main output set (`coef`/`se`/`z`/`pv`/`ci`/`bws`) is complete. Per-side
45//! decompositions, fuzzy first-stage diagnostics, and the `rdplot` QS / covariate /
46//! CI extensions are not ported. The raw [`rdrobust`]/[`rdrobust_with`] entry points
47//! still return `NaN` on degenerate inputs; [`try_rdrobust_with`] adds a typed
48//! validation channel ([`RdError`]) that rejects those inputs up front. See
49//! `CHANGELOG.md` for the full list.
50
51#![deny(missing_docs)]
52#![forbid(unsafe_code)]
53
54pub(crate) mod batch;
55pub(crate) mod bw;
56pub(crate) mod bwselect;
57pub(crate) mod kernel;
58pub(crate) mod linalg;
59pub(crate) mod rdplot;
60pub(crate) mod rdrobust;
61mod stats;
62mod vce;
63
64pub use batch::{rdrobust_batch, rdrobust_multi_cutoff, Dataset};
65pub use bw::{rdrobust_bw, BwParts};
66pub use bwselect::{rdbwselect, Bws};
67pub use kernel::kweight;
68pub use rdplot::{rdplot, RdPlot};
69pub use rdrobust::{
70    rdrobust, rdrobust_with, try_rdrobust_with, RdError, RdRobust, RdRobustOptions,
71};
72
73/// Local-polynomial weighting kernel (mirrors `rdrobust_kweight`).
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Kernel {
76    /// `(1 - |u|) * 1{|u| <= 1}` -- the rdrobust default.
77    Triangular,
78    /// `0.75 * (1 - u^2) * 1{|u| <= 1}`.
79    Epanechnikov,
80    /// `0.5 * 1{|u| <= 1}`.
81    Uniform,
82}
83
84/// Variance-covariance estimator (mirrors the `vce` argument).
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Vce {
87    /// Nearest-neighbor (default), `nnmatch` neighbors per side.
88    NearestNeighbor,
89    /// Heteroskedasticity-consistent HC0.
90    Hc0,
91    /// Heteroskedasticity-consistent HC1.
92    Hc1,
93    /// Heteroskedasticity-consistent HC2.
94    Hc2,
95    /// Heteroskedasticity-consistent HC3.
96    Hc3,
97    /// Cluster-robust CRV1.
98    Cr1,
99    /// Cluster-robust CRV2.
100    Cr2,
101    /// Cluster-robust CRV3.
102    Cr3,
103}
104
105impl Vce {
106    /// HC order (`Hc0`->0 .. `Hc3`->3), `None` for non-HC variants.
107    pub(crate) fn hc_order(self) -> Option<u8> {
108        match self {
109            Vce::Hc0 => Some(0),
110            Vce::Hc1 => Some(1),
111            Vce::Hc2 => Some(2),
112            Vce::Hc3 => Some(3),
113            _ => None,
114        }
115    }
116
117    /// Cluster order (`Cr1`->1 .. `Cr3`->3), `None` for non-cluster variants.
118    pub(crate) fn cluster_order(self) -> Option<u8> {
119        match self {
120            Vce::Cr1 => Some(1),
121            Vce::Cr2 => Some(2),
122            Vce::Cr3 => Some(3),
123            _ => None,
124        }
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn kernel_variants_are_distinct() {
134        assert_ne!(Kernel::Triangular, Kernel::Uniform);
135        assert_ne!(Kernel::Epanechnikov, Kernel::Uniform);
136    }
137
138    #[test]
139    fn vce_carries_order() {
140        assert_eq!(Vce::Hc2, Vce::Hc2);
141        assert_ne!(Vce::Hc2, Vce::Hc3);
142        assert_eq!(Vce::Hc2.hc_order(), Some(2));
143        assert_eq!(Vce::Cr3.cluster_order(), Some(3));
144        assert_eq!(Vce::NearestNeighbor.hc_order(), None);
145    }
146}