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 (a cutoff outside the support, a fuzzy
48//! treatment with no first stage); [`try_rdrobust_with`] adds a typed validation
49//! channel ([`RdError`]) that rejects those inputs up front. See `CHANGELOG.md`
50//! for the full list.
51
52#![deny(missing_docs)]
53#![forbid(unsafe_code)]
54
55pub(crate) mod batch;
56pub(crate) mod bw;
57pub(crate) mod bwselect;
58pub(crate) mod kernel;
59pub(crate) mod linalg;
60pub(crate) mod rdplot;
61pub(crate) mod rdrobust;
62mod stats;
63mod vce;
64
65pub use batch::{rdrobust_batch, rdrobust_multi_cutoff, Dataset};
66pub use bw::{rdrobust_bw, BwParts};
67pub use bwselect::{rdbwselect, Bws};
68pub use kernel::kweight;
69pub use rdplot::{rdplot, RdPlot};
70pub use rdrobust::{
71    rdrobust, rdrobust_with, try_rdrobust_with, RdError, RdRobust, RdRobustOptions,
72};
73
74/// Local-polynomial weighting kernel (mirrors `rdrobust_kweight`).
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Kernel {
77    /// `(1 - |u|) * 1{|u| <= 1}` -- the rdrobust default.
78    Triangular,
79    /// `0.75 * (1 - u^2) * 1{|u| <= 1}`.
80    Epanechnikov,
81    /// `0.5 * 1{|u| <= 1}`.
82    Uniform,
83}
84
85/// Variance-covariance estimator (mirrors the `vce` argument).
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Vce {
88    /// Nearest-neighbor (default), `nnmatch` neighbors per side.
89    NearestNeighbor,
90    /// Heteroskedasticity-consistent HC0.
91    Hc0,
92    /// Heteroskedasticity-consistent HC1.
93    Hc1,
94    /// Heteroskedasticity-consistent HC2.
95    Hc2,
96    /// Heteroskedasticity-consistent HC3.
97    Hc3,
98    /// Cluster-robust CRV1.
99    Cr1,
100    /// Cluster-robust CRV2.
101    Cr2,
102    /// Cluster-robust CRV3.
103    Cr3,
104}
105
106impl Vce {
107    /// HC order (`Hc0`->0 .. `Hc3`->3), `None` for non-HC variants.
108    pub(crate) fn hc_order(self) -> Option<u8> {
109        match self {
110            Vce::Hc0 => Some(0),
111            Vce::Hc1 => Some(1),
112            Vce::Hc2 => Some(2),
113            Vce::Hc3 => Some(3),
114            _ => None,
115        }
116    }
117
118    /// Cluster order (`Cr1`->1 .. `Cr3`->3), `None` for non-cluster variants.
119    pub(crate) fn cluster_order(self) -> Option<u8> {
120        match self {
121            Vce::Cr1 => Some(1),
122            Vce::Cr2 => Some(2),
123            Vce::Cr3 => Some(3),
124            _ => None,
125        }
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn kernel_variants_are_distinct() {
135        assert_ne!(Kernel::Triangular, Kernel::Uniform);
136        assert_ne!(Kernel::Epanechnikov, Kernel::Uniform);
137    }
138
139    #[test]
140    fn vce_carries_order() {
141        assert_eq!(Vce::Hc2, Vce::Hc2);
142        assert_ne!(Vce::Hc2, Vce::Hc3);
143        assert_eq!(Vce::Hc2.hc_order(), Some(2));
144        assert_eq!(Vce::Cr3.cluster_order(), Some(3));
145        assert_eq!(Vce::NearestNeighbor.hc_order(), None);
146    }
147}