Skip to main content

rdrobust_core/
rdrobust.rs

1//! Main RD estimator, a port of `rdrobust` (R rdrobust.R:540-907): the
2//! point estimate (conventional + bias-corrected) with CCT robust variance and
3//! confidence intervals.
4//!
5//! Implemented: sharp/fuzzy, covariates, clusters (CR1/CRV2/CRV3), nn/hc0-hc3, user
6//! weights, `rho`, `perf_comp`/`sharpbw`, the prep options (`masspoints`,
7//! `stdvars`, `bwrestrict`, `bwcheck`), and manual/auto bandwidths.
8//!
9//! Parity gate: coef/se/ci to ~1e-8 vs R (~1e-11 for clusters).
10
11use nalgebra::{DMatrix, DVector};
12
13use crate::bwselect::rdbwselect;
14use crate::kernel::eff_weight;
15use crate::linalg::{qr_xx_inv, vander};
16use crate::stats::{pnorm, qnorm};
17use crate::vce;
18use crate::{Kernel, Vce};
19
20/// Headline `rdrobust` results, one row per inference method (rows are
21/// Conventional, Bias-Corrected, Robust; ports rdrobust.R:854-863).
22///
23/// The three rows are not three independent estimates. The point estimate
24/// repeats (`coef = [tau_cl, tau_bc, tau_bc]`: Bias-Corrected and Robust share
25/// `tau_bc`) and the standard error repeats (`se = [se_cl, se_cl, se_rb]`:
26/// Conventional and Bias-Corrected share `se_cl`). `z`, `pv`, and `ci` follow
27/// row-wise from `coef` and `se`.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct RdRobust {
30    /// Point estimates by row: `[tau_cl, tau_bc, tau_bc]` (Conventional uses the
31    /// p-fit estimate; Bias-Corrected and Robust both use the bias-corrected one).
32    pub coef: [f64; 3],
33    /// Standard errors by row: `[se_cl, se_cl, se_rb]` (Conventional and
34    /// Bias-Corrected share the conventional SE; Robust uses the CCT robust SE).
35    pub se: [f64; 3],
36    /// z-statistics by row, `coef[i] / se[i]`.
37    pub z: [f64; 3],
38    /// Two-sided normal p-values by row, `2 * Phi(-|z[i]|)`.
39    pub pv: [f64; 3],
40    /// Confidence intervals by row, each `[lower, upper]` at `level`% using the
41    /// matching row's `coef` and `se`.
42    pub ci: [[f64; 2]; 3],
43    /// Bandwidths used: rows are `h` (point estimate) then `b` (bias correction),
44    /// columns are left then right, i.e. `[[h_l, h_r], [b_l, b_r]]`.
45    pub bws: [[f64; 2]; 2],
46}
47
48/// Per-side fit pieces at the common window (the larger of the h- and b-windows).
49struct SideFit {
50    r_p: DMatrix<f64>, // Vandermonde order p, n x (p+1)
51    r_q: DMatrix<f64>, // Vandermonde order q, n x (q+1)
52    inv_g_p: DMatrix<f64>,
53    inv_g_q: DMatrix<f64>,
54    rp_wh: DMatrix<f64>,   // R_p * W_h (row-scaled) -- conventional meat design
55    rp_swh: DMatrix<f64>,  // R_p * sqrt(W_h) -- crv2/crv3 conventional sqrtRX
56    rq_wb: DMatrix<f64>,   // R_q * W_b (row-scaled) -- robust hc residual design
57    rq_swb: DMatrix<f64>,  // R_q * sqrt(W_b) -- crv2/crv3 h==b robust sqrtRX
58    w_b: Vec<f64>,         // in-window W_b kernel weights (for qq_cluster)
59    q_q: DMatrix<f64>,     // bias-correction design, n x (p+1)
60    d: DMatrix<f64>,       // response design [Y] or [Y, T]
61    beta_p: DMatrix<f64>,  // (p+1) x ncols
62    beta_q: DMatrix<f64>,  // (q+1) x ncols
63    beta_bc: DMatrix<f64>, // (p+1) x ncols
64    zwz_p: Option<DMatrix<f64>>, // covariate FWL inputs (per side; combined in main)
65    zwy_p: Option<DMatrix<f64>>,
66    ex: Vec<f64>,
67    ec: Vec<f64>, // windowed cluster ids (empty if no clustering)
68    en: usize,
69    edups: Vec<usize>,
70    edupsid: Vec<usize>,
71}
72
73/// Fit one side at bandwidths (h, b): build the common window, the p/q fits, the
74/// bias-correction design Q_q, and the three coefficient matrices.
75#[allow(clippy::too_many_arguments)]
76fn fit_side(
77    y: &[f64],
78    x: &[f64],
79    t: Option<&[f64]>,
80    z: Option<&[f64]>,
81    cl: Option<&[f64]>,
82    wt: Option<&[f64]>,
83    dz: usize,
84    c: f64,
85    p: usize,
86    q: usize,
87    h: f64,
88    b: f64,
89    kernel: Kernel,
90    vce_kind: Vce,
91) -> SideFit {
92    let w_h_full = eff_weight(x, c, h, kernel, wt);
93    let w_b_full = eff_weight(x, c, b, kernel, wt);
94    // common window: the larger bandwidth's support (R:546-548)
95    let ind: Vec<usize> = if h > b {
96        (0..x.len()).filter(|&i| w_h_full[i] > 0.0).collect()
97    } else {
98        (0..x.len()).filter(|&i| w_b_full[i] > 0.0).collect()
99    };
100    let en = ind.len();
101    let ex: Vec<f64> = ind.iter().map(|&i| x[i]).collect();
102    let ec: Vec<f64> = cl.map_or(Vec::new(), |c| ind.iter().map(|&i| c[i]).collect());
103    let w_h: Vec<f64> = ind.iter().map(|&i| w_h_full[i]).collect();
104    let w_b: Vec<f64> = ind.iter().map(|&i| w_b_full[i]).collect();
105
106    let (edups, edupsid) = match vce_kind {
107        Vce::NearestNeighbor => {
108            let (du, ds) = vce::compute_dups_dupsid(x); // full side (sorted)
109            (
110                ind.iter().map(|&i| du[i]).collect(),
111                ind.iter().map(|&i| ds[i]).collect(),
112            )
113        }
114        _ => (Vec::new(), Vec::new()),
115    };
116
117    let u: Vec<f64> = ex.iter().map(|&xi| xi - c).collect();
118    let r_q = vander(&u, q);
119    let r_p = r_q.columns(0, p + 1).into_owned();
120
121    // row-scaled designs
122    let row_scale = |m: &DMatrix<f64>, w: &[f64]| {
123        let mut out = m.clone();
124        for i in 0..en {
125            for j in 0..m.ncols() {
126                out[(i, j)] *= w[i];
127            }
128        }
129        out
130    };
131    let sqrt_w = |w: &[f64]| w.iter().map(|v| v.sqrt()).collect::<Vec<_>>();
132    let rp_swh = row_scale(&r_p, &sqrt_w(&w_h));
133    let rq_swb = row_scale(&r_q, &sqrt_w(&w_b));
134    let inv_g_p = qr_xx_inv(&rp_swh);
135    let inv_g_q = qr_xx_inv(&rq_swb);
136    let rp_wh = row_scale(&r_p, &w_h);
137    let rq_wb = row_scale(&r_q, &w_b);
138
139    // L = (R_p*W_h)' u^(p+1) ; vcorr = W_b * col_{p+1}(R_q invG_q) ;
140    // Q_q[k,i] = (R_p*W_h)[k,i] - h^(p+1) * vcorr[k] * L[i]   (R:572-577)
141    let u_pow = DVector::from_iterator(en, u.iter().map(|&uu| (uu / h).powi((p + 1) as i32)));
142    let l_vec = rp_wh.transpose() * &u_pow; // (p+1)
143    let rq_ig = &r_q * &inv_g_q; // n x (q+1)
144    let hp1 = h.powi((p + 1) as i32);
145    let mut q_q = rp_wh.clone();
146    for k in 0..en {
147        let vcorr = w_b[k] * rq_ig[(k, p + 1)];
148        for i in 0..=p {
149            q_q[(k, i)] -= hp1 * vcorr * l_vec[i];
150        }
151    }
152
153    // response design [Y, T?, Z..] and the three fits
154    let dt = t.is_some() as usize;
155    let mut d = DMatrix::zeros(en, 1 + dt + dz);
156    for (r, &i) in ind.iter().enumerate() {
157        d[(r, 0)] = y[i];
158    }
159    if let Some(tt) = t {
160        for (r, &i) in ind.iter().enumerate() {
161            d[(r, 1)] = tt[i];
162        }
163    }
164    if let Some(zz) = z {
165        for (r, &i) in ind.iter().enumerate() {
166            for j in 0..dz {
167                d[(r, 1 + dt + j)] = zz[i * dz + j];
168            }
169        }
170    }
171    let beta_p = &inv_g_p * (rp_wh.transpose() * &d);
172    let beta_q = &inv_g_q * (rq_wb.transpose() * &d);
173    let beta_bc = &inv_g_p * (q_q.transpose() * &d);
174
175    // per-side covariate partialling inputs (combined across sides in `rdrobust`)
176    let (zwz_p, zwy_p) = if dz > 0 {
177        let (zwz, zwy) = vce::partialling(&rp_wh, &inv_g_p, &d, &w_h, dt, dz);
178        (Some(zwz), Some(zwy))
179    } else {
180        (None, None)
181    };
182
183    SideFit {
184        r_p,
185        r_q,
186        inv_g_p,
187        inv_g_q,
188        rp_wh,
189        rp_swh,
190        rq_wb,
191        rq_swb,
192        w_b,
193        q_q,
194        d,
195        beta_p,
196        beta_q,
197        beta_bc,
198        zwz_p,
199        zwy_p,
200        ex,
201        ec,
202        en,
203        edups,
204        edupsid,
205    }
206}
207
208/// Scalar/config options for [`rdrobust_with`], a typed alternative to the raw
209/// [`rdrobust`] positional arguments. The data inputs (`y`, `x`, `fuzzy`, `covs`,
210/// `dz`, `cluster`, `weights`) stay separate; this struct carries everything else.
211///
212/// [`Default`] matches the R/Python wrapper defaults, so `RdRobustOptions {
213/// p: 2, q: 3, ..Default::default() }` overrides one knob and leaves the rest at
214/// their R defaults. Each field forwards to the matching positional argument of
215/// [`rdrobust`]; see that function for the per-argument semantics.
216#[derive(Debug, Clone, Copy)]
217pub struct RdRobustOptions {
218    /// RD cutoff on the running variable (R `c`, default 0).
219    pub c: f64,
220    /// Polynomial order for the point estimate (R `p`, default 1).
221    pub p: usize,
222    /// Polynomial order for the bias correction; must exceed `p` (R `q`, default 2).
223    pub q: usize,
224    /// Derivative order of the estimand: 0 = level, 1 = kink (R `deriv`, default 0).
225    pub deriv: usize,
226    /// Kernel for the local-polynomial weights (R `kernel`, default triangular).
227    pub kernel: Kernel,
228    /// Variance estimator before any cluster remap (R `vce`, default nn).
229    pub vce: Vce,
230    /// Minimum neighbors for `vce = nn` (R `nnmatch`, default 3).
231    pub nnmatch: usize,
232    /// Drop collinear covariates in the FWL partialling (R `covs_drop`, default false here).
233    pub covs_drop_coll: bool,
234    /// Regularization scale in bandwidth selection; 0 removes it (R `scaleregul`, default 1).
235    pub scaleregul: f64,
236    /// Scaling applied to the RD parameter (R `scalepar`, default 1).
237    pub scalepar: f64,
238    /// Confidence-interval level in percent, e.g. 95 (R `level`, default 95).
239    pub level: f64,
240    /// Bandwidth-selection method when `h` is `None`, e.g. `"mserd"` (R `bwselect`, default "mserd").
241    pub bwselect: &'static str,
242    /// Mass-point handling: `"off"`, `"check"`, or `"adjust"` (R `masspoints`, default "adjust").
243    pub masspoints: &'static str,
244    /// Standardize `x` and `y` before bandwidth selection (R `stdvars`, default true).
245    pub stdvars: bool,
246    /// Clamp selected bandwidths to the range of `x` (R `bwrestrict`, default true).
247    pub bwrestrict: bool,
248    /// Minimum unique observations in the pilot bandwidth; `None` skips the check (R `bwcheck`, default NULL).
249    pub bwcheck: Option<usize>,
250    /// Sets `b = h / rho`; `None` leaves `b` from `b`/selection (R `rho`, default NULL).
251    pub rho: Option<f64>,
252    /// Force sharp-RD bandwidth selection in a fuzzy design (R `sharpbw`, default false).
253    pub sharpbw: bool,
254    /// Main bandwidths `(left, right)`; `None` triggers selection (R `h`, default NULL).
255    pub h: Option<(f64, f64)>,
256    /// Bias bandwidths `(left, right)`; `None` defaults to `h` (or `h / rho`) (R `b`, default NULL).
257    pub b: Option<(f64, f64)>,
258}
259
260impl Default for RdRobustOptions {
261    /// R/Python wrapper defaults: `c=0, p=1, q=2, deriv=0`, triangular kernel, nn
262    /// variance, `nnmatch=3`, `scaleregul=1`, `scalepar=1`, `level=95`,
263    /// `bwselect="mserd"`, `masspoints="adjust"`, `stdvars`/`bwrestrict` on, and the
264    /// remaining knobs off/unset.
265    fn default() -> Self {
266        Self {
267            c: 0.0,
268            p: 1,
269            q: 2,
270            deriv: 0,
271            kernel: Kernel::Triangular,
272            vce: Vce::NearestNeighbor,
273            nnmatch: 3,
274            covs_drop_coll: false,
275            scaleregul: 1.0,
276            scalepar: 1.0,
277            level: 95.0,
278            bwselect: "mserd",
279            masspoints: "adjust",
280            stdvars: true,
281            bwrestrict: true,
282            bwcheck: None,
283            rho: None,
284            sharpbw: false,
285            h: None,
286            b: None,
287        }
288    }
289}
290
291/// Ergonomic, options-struct entry point to [`rdrobust`]: the seven data inputs
292/// stay explicit while every scalar/config knob lives in [`RdRobustOptions`], so a
293/// caller no longer threads 27 positional arguments (where swapping two
294/// bools/strings silently changes the estimate).
295///
296/// This forwards verbatim to the raw [`rdrobust`]; it changes ergonomics, not
297/// numerics. `fuzzy` is the treatment status (`None` = sharp), `covs` the
298/// flattened row-major `n x dz` covariate slice (`None` = no covariates, `dz = 0`).
299///
300/// # Example
301///
302/// ```
303/// use rdrobust_core::{rdrobust_with, RdRobustOptions};
304///
305/// // A small sharp RD with a jump of about 2 at the cutoff c = 0; x sorted ascending.
306/// let x: Vec<f64> = (0..200).map(|i| -1.0 + 2.0 * (i as f64 + 0.5) / 200.0).collect();
307/// let y: Vec<f64> = x
308///     .iter()
309///     .enumerate()
310///     .map(|(i, &xi)| 0.5 * xi + if xi >= 0.0 { 2.0 } else { 0.0 } + 0.3 * (i as f64).sin())
311///     .collect();
312///
313/// // Override just the polynomial orders (q must exceed p); keep every other R default.
314/// let opts = RdRobustOptions { p: 2, q: 3, ..Default::default() };
315/// let out = rdrobust_with(&y, &x, None, None, 0, None, None, &opts);
316///
317/// assert!(out.coef[0].is_finite());
318/// ```
319#[allow(clippy::too_many_arguments)]
320pub fn rdrobust_with(
321    y: &[f64],
322    x: &[f64],
323    fuzzy: Option<&[f64]>,
324    covs: Option<&[f64]>,
325    dz: usize,
326    cluster: Option<&[f64]>,
327    weights: Option<&[f64]>,
328    opts: &RdRobustOptions,
329) -> RdRobust {
330    rdrobust(
331        y,
332        x,
333        fuzzy,
334        covs,
335        dz,
336        opts.c,
337        opts.p,
338        opts.q,
339        opts.deriv,
340        opts.kernel,
341        opts.vce,
342        opts.nnmatch,
343        opts.covs_drop_coll,
344        opts.scaleregul,
345        opts.scalepar,
346        opts.level,
347        opts.bwselect,
348        cluster,
349        weights,
350        opts.masspoints,
351        opts.stdvars,
352        opts.bwrestrict,
353        opts.bwcheck,
354        opts.rho,
355        opts.sharpbw,
356        opts.h,
357        opts.b,
358    )
359}
360
361/// Validation failure for [`try_rdrobust_with`]: a degenerate input or option that
362/// the raw [`rdrobust`]/[`rdrobust_with`] path would otherwise carry into `NaN`
363/// results. Each variant mirrors a check the Python binding already performs, with
364/// the same message text, so the two channels agree on what they reject.
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub enum RdError {
367    /// Fewer than two observations in `y`/`x`.
368    TooFewObs,
369    /// A length-`n` input has a length other than `expected` (the length of `y`).
370    LengthMismatch {
371        /// The offending input's name (`"x"`, `"fuzzy"`, `"cluster"`, `"weights"`, `"covs"`).
372        name: &'static str,
373        /// The actual length supplied.
374        len: usize,
375        /// The expected length (the length of `y`).
376        expected: usize,
377    },
378    /// An input contains a non-finite value (NaN or infinity).
379    NonFinite {
380        /// The offending input's name (`"y"`, `"x"`, `"fuzzy"`, `"cluster"`, `"weights"`, `"covs"`).
381        name: &'static str,
382    },
383    /// No observations on one side of the cutoff `c`.
384    OneSidedCutoff,
385    /// Invalid polynomial/derivative orders: `q <= p` or `deriv > p`.
386    InvalidOrder,
387    /// `nnmatch` is less than 1.
388    InvalidNnmatch,
389    /// `level` is outside the open interval `(0, 100)`.
390    InvalidLevel,
391    /// A bandwidth-like scalar (`h`, `b`, or `rho`) is not strictly positive.
392    NonPositiveBandwidth {
393        /// The offending scalar's name (`"h"`, `"b"`, or `"rho"`).
394        name: &'static str,
395    },
396    /// A weight is negative.
397    NonNegativeWeightRequired,
398    /// Covariates were supplied (`covs` is `Some`) but with zero columns (`dz == 0`).
399    EmptyCovariates,
400}
401
402impl std::fmt::Display for RdError {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        match self {
405            RdError::TooFewObs => {
406                write!(f, "y and x must have at least two observations")
407            }
408            RdError::LengthMismatch {
409                name,
410                len,
411                expected,
412            } => write!(f, "{name} has length {len}, expected {expected}"),
413            RdError::NonFinite { name } => write!(f, "{name} must be finite"),
414            RdError::OneSidedCutoff => {
415                write!(f, "x must contain observations on both sides of the cutoff")
416            }
417            RdError::InvalidOrder => write!(f, "q must be > p and deriv must be <= p"),
418            RdError::InvalidNnmatch => write!(f, "nnmatch must be >= 1"),
419            RdError::InvalidLevel => write!(f, "level must be in (0, 100)"),
420            RdError::NonPositiveBandwidth { name } => write!(f, "{name} must be positive"),
421            RdError::NonNegativeWeightRequired => write!(f, "weights must be non-negative"),
422            RdError::EmptyCovariates => write!(f, "covs must have at least one column"),
423        }
424    }
425}
426
427impl std::error::Error for RdError {}
428
429/// Validate the [`try_rdrobust_with`] inputs and options without running the fit.
430/// Returns `Ok(())` when every check the Python binding enforces passes, otherwise
431/// the first failing [`RdError`]. `dz` is the row stride of `covs` (0 when `covs`
432/// is `None`); `n` is taken from `y`.
433#[allow(clippy::too_many_arguments)]
434fn validate_rdrobust_inputs(
435    y: &[f64],
436    x: &[f64],
437    fuzzy: Option<&[f64]>,
438    covs: Option<&[f64]>,
439    dz: usize,
440    cluster: Option<&[f64]>,
441    weights: Option<&[f64]>,
442    opts: &RdRobustOptions,
443) -> Result<(), RdError> {
444    let n = y.len();
445    if n < 2 {
446        return Err(RdError::TooFewObs);
447    }
448    let ensure_len = |name: &'static str, len: usize| -> Result<(), RdError> {
449        if len == n {
450            Ok(())
451        } else {
452            Err(RdError::LengthMismatch {
453                name,
454                len,
455                expected: n,
456            })
457        }
458    };
459    let ensure_finite = |name: &'static str, values: &[f64]| -> Result<(), RdError> {
460        if values.iter().all(|v| v.is_finite()) {
461            Ok(())
462        } else {
463            Err(RdError::NonFinite { name })
464        }
465    };
466
467    ensure_len("x", x.len())?;
468    ensure_finite("y", y)?;
469    ensure_finite("x", x)?;
470    if let Some(values) = fuzzy {
471        ensure_len("fuzzy", values.len())?;
472        ensure_finite("fuzzy", values)?;
473    }
474    if let Some(values) = cluster {
475        ensure_len("cluster", values.len())?;
476        ensure_finite("cluster", values)?;
477    }
478    if let Some(values) = weights {
479        ensure_len("weights", values.len())?;
480        ensure_finite("weights", values)?;
481        if values.iter().any(|&v| v < 0.0) {
482            return Err(RdError::NonNegativeWeightRequired);
483        }
484    }
485    if let Some(values) = covs {
486        if dz == 0 {
487            return Err(RdError::EmptyCovariates);
488        }
489        ensure_len("covs", values.len() / dz)?;
490        ensure_finite("covs", values)?;
491    }
492
493    if opts.q <= opts.p || opts.deriv > opts.p {
494        return Err(RdError::InvalidOrder);
495    }
496    if opts.nnmatch == 0 {
497        return Err(RdError::InvalidNnmatch);
498    }
499    if !(0.0..100.0).contains(&opts.level) {
500        return Err(RdError::InvalidLevel);
501    }
502    if let Some(r) = opts.rho {
503        if r <= 0.0 {
504            return Err(RdError::NonPositiveBandwidth { name: "rho" });
505        }
506    }
507    if let Some((hl, hr)) = opts.h {
508        if hl <= 0.0 || hr <= 0.0 {
509            return Err(RdError::NonPositiveBandwidth { name: "h" });
510        }
511    }
512    if let Some((bl, br)) = opts.b {
513        if bl <= 0.0 || br <= 0.0 {
514            return Err(RdError::NonPositiveBandwidth { name: "b" });
515        }
516    }
517
518    let left = x.iter().filter(|&&v| v < opts.c).count();
519    if left == 0 || left == n {
520        return Err(RdError::OneSidedCutoff);
521    }
522
523    Ok(())
524}
525
526/// Validated wrapper over [`rdrobust_with`]: run `validate_rdrobust_inputs` first
527/// and, when every check passes, forward verbatim to [`rdrobust_with`] and return
528/// `Ok(result)`. On any degenerate input or option it returns the first matching
529/// [`RdError`] instead of letting the raw path produce `NaN`. The numerics on valid
530/// inputs are identical to [`rdrobust_with`]; only the rejection of bad inputs differs.
531///
532/// `fuzzy`, `covs`, `dz`, `cluster`, and `weights` carry the same meaning as in
533/// [`rdrobust_with`]. `opts` holds every scalar/config knob via [`RdRobustOptions`].
534///
535/// # Example
536///
537/// ```
538/// use rdrobust_core::{try_rdrobust_with, RdError, RdRobustOptions};
539///
540/// // A small sharp RD with a jump of about 2 at the cutoff c = 0; x sorted ascending.
541/// let x: Vec<f64> = (0..200).map(|i| -1.0 + 2.0 * (i as f64 + 0.5) / 200.0).collect();
542/// let y: Vec<f64> = x
543///     .iter()
544///     .enumerate()
545///     .map(|(i, &xi)| 0.5 * xi + if xi >= 0.0 { 2.0 } else { 0.0 } + 0.3 * (i as f64).sin())
546///     .collect();
547///
548/// // Valid options (defaults have q = 2 > p = 1): an Ok result.
549/// let ok = RdRobustOptions::default();
550/// let out = try_rdrobust_with(&y, &x, None, None, 0, None, None, &ok).unwrap();
551/// assert!(out.coef[0].is_finite());
552///
553/// // q <= p (here q = p = 1) is rejected before any fit runs.
554/// let bad = RdRobustOptions { q: 1, ..Default::default() };
555/// let err = try_rdrobust_with(&y, &x, None, None, 0, None, None, &bad);
556/// assert_eq!(err, Err(RdError::InvalidOrder));
557/// ```
558#[allow(clippy::too_many_arguments)]
559pub fn try_rdrobust_with(
560    y: &[f64],
561    x: &[f64],
562    fuzzy: Option<&[f64]>,
563    covs: Option<&[f64]>,
564    dz: usize,
565    cluster: Option<&[f64]>,
566    weights: Option<&[f64]>,
567    opts: &RdRobustOptions,
568) -> Result<RdRobust, RdError> {
569    validate_rdrobust_inputs(y, x, fuzzy, covs, dz, cluster, weights, opts)?;
570    Ok(rdrobust_with(y, x, fuzzy, covs, dz, cluster, weights, opts))
571}
572
573/// Port of `rdrobust` (rdrobust.R:540-907) for the scoped option set: the RD
574/// point estimate (conventional and bias-corrected) with CCT robust variance and
575/// confidence intervals.
576///
577/// `h`/`b` as `Some((left, right))` supplies bandwidths directly; `None` selects
578/// them via [`rdbwselect`]. For `vce = nn`, `x` must be sorted ascending.
579///
580/// The core takes every argument as a required positional; the "R-default" column
581/// below is the value the R/Python wrapper supplies when the user omits the arg.
582///
583/// # Arguments
584///
585/// * `y` - Outcome values, one per observation.
586/// * `x` - Running variable, one per observation (sorted ascending when `vce = nn`).
587/// * `t` - Fuzzy treatment status; `None` for a sharp design (R `fuzzy`, default NULL).
588/// * `z` - Covariates as a flattened row-major `n x dz` slice; `None` for no covariates (R `covs`, default NULL).
589/// * `dz` - Covariate column count (the row stride of `z`); 0 when `z` is `None`. Rust-core detail, no R default.
590/// * `c` - RD cutoff (R `c`, default 0).
591/// * `p` - Polynomial order for the point estimate (R `p`, default 1, or `deriv + 1`).
592/// * `q` - Polynomial order for the bias correction (R `q`, default `p + 1`, must exceed `p`).
593/// * `deriv` - Derivative order of the estimand: 0 = level, 1 = kink (R `deriv`, default 0).
594/// * `kernel` - Kernel for the local-polynomial weights (R `kernel`, default triangular).
595/// * `vce_kind` - Variance estimator before clustering remap: nn, hc0-hc3 (R `vce`, default nn).
596/// * `nnmatch` - Minimum neighbors for `vce = nn` (R `nnmatch`, default 3).
597/// * `covs_drop_coll` - Drop collinear covariates in the FWL partialling. This port
598///   defaults to false (R's default is true); the flag only switches the ginv versus
599///   Cholesky solve in the FWL step, and the projection onto col(Z) is unique, so it
600///   changes no coefficient. R `covs_drop`; the flag is estimate-identical, not a
601///   default-parity match.
602/// * `scaleregul` - Regularization scale in bandwidth selection; 0 removes it (R `scaleregul`, default 1).
603/// * `scalepar` - Scaling applied to the RD parameter (R `scalepar`, default 1).
604/// * `level` - Confidence-interval level in percent, e.g. 95 (R `level`, default 95).
605/// * `bwselect` - Bandwidth-selection method when `h` is `None`, e.g. `"mserd"` (R `bwselect`, default "mserd").
606/// * `cluster` - Cluster ids; presence remaps `vce_kind` to CR1/CRV2/CRV3 (R `cluster`, default NULL).
607/// * `weights` - User weights multiplying the kernel; `None` for unweighted (R `weights`, default NULL).
608/// * `masspoints` - Mass-point handling: `"off"`, `"check"`, or `"adjust"` (R `masspoints`, default "adjust").
609/// * `stdvars` - Standardize `x` and `y` before bandwidth selection (R `stdvars`, default true).
610/// * `bwrestrict` - Clamp selected bandwidths to the range of `x` (R `bwrestrict`, default true).
611/// * `bwcheck` - Minimum unique observations required in the pilot bandwidth; `None` to skip (R `bwcheck`, default NULL).
612/// * `rho` - Sets `b = h / rho`; `None` leaves `b` from `b`/selection (R `rho`, default NULL).
613/// * `sharpbw` - Force sharp-RD bandwidth selection in a fuzzy design (R `sharpbw`, default false).
614/// * `h` - Main bandwidths `(left, right)`; `None` triggers selection via [`rdbwselect`] (R `h`, default NULL).
615/// * `b` - Bias bandwidths `(left, right)`; `None` defaults to `h` (or `h / rho`) (R `b`, default NULL).
616///
617/// # Returns
618///
619/// An [`RdRobust`] with the three-row coef/se/z/pv/ci and the 2x2 bandwidths used.
620#[allow(clippy::too_many_arguments)]
621pub fn rdrobust(
622    y: &[f64],
623    x: &[f64],
624    t: Option<&[f64]>,
625    z: Option<&[f64]>,
626    dz: usize,
627    c: f64,
628    p: usize,
629    q: usize,
630    deriv: usize,
631    kernel: Kernel,
632    vce_kind: Vce,
633    nnmatch: usize,
634    covs_drop_coll: bool,
635    scaleregul: f64,
636    scalepar: f64,
637    level: f64,
638    bwselect: &str,
639    cluster: Option<&[f64]>,
640    weights: Option<&[f64]>,
641    masspoints: &str,
642    stdvars: bool,
643    bwrestrict: bool,
644    bwcheck: Option<usize>,
645    rho: Option<f64>,
646    sharpbw: bool,
647    h: Option<(f64, f64)>,
648    b: Option<(f64, f64)>,
649) -> RdRobust {
650    // perf_comp: a fuzzy design with one-sided (constant-T) compliance. R selects
651    // the bandwidth as if SHARP (treatment dropped) but estimates fuzzy at it
652    // (rdrobust.R:166-185, 581-591); `sharpbw=true` forces the same regardless.
653    let perf_comp = match t {
654        Some(tt) => {
655            let var_side = |on_left: bool| -> f64 {
656                let v: Vec<f64> = (0..tt.len())
657                    .filter(|&i| (x[i] < c) == on_left)
658                    .map(|i| tt[i])
659                    .collect();
660                if v.len() < 2 {
661                    return 0.0;
662                }
663                let mean = v.iter().sum::<f64>() / v.len() as f64;
664                v.iter().map(|&u| (u - mean) * (u - mean)).sum::<f64>()
665            };
666            var_side(true) == 0.0 || var_side(false) == 0.0
667        }
668        None => false,
669    };
670    // treatment used for BANDWIDTH SELECTION (dropped -> sharp BW when perf_comp/sharpbw)
671    let bw_t = if perf_comp || sharpbw { None } else { t };
672
673    // bandwidths (rho: b = h/rho; rdrobust.R:296-300 manual-h path, 501-504 auto path)
674    let (h_l, h_r, b_l, b_r) = match h {
675        Some((hl, hr)) => {
676            let (bl, br) = match (rho, b) {
677                (Some(r), _) => (hl / r, hr / r),   // rho overrides any b
678                (None, Some((bl, br))) => (bl, br), // explicit b
679                (None, None) => (hl, hr),           // rho defaults to 1 -> b = h
680            };
681            (hl, hr, bl, br)
682        }
683        None => {
684            let bw = rdbwselect(
685                y,
686                x,
687                bw_t,
688                z,
689                dz,
690                c,
691                p,
692                q,
693                deriv,
694                kernel,
695                vce_kind,
696                nnmatch,
697                covs_drop_coll,
698                scaleregul,
699                bwselect,
700                cluster,
701                weights,
702                masspoints,
703                stdvars,
704                bwrestrict,
705                bwcheck,
706            );
707            match rho {
708                Some(r) => (bw.h_l, bw.h_r, bw.h_l / r, bw.h_r / r),
709                None => (bw.h_l, bw.h_r, bw.b_l, bw.b_r),
710            }
711        }
712    };
713
714    // split sides (x<c left, x>=c right); z is flattened row-major (n x dz)
715    let (mut yl, mut xl, mut tl, mut zl, mut cll, mut fwl) = (
716        Vec::new(),
717        Vec::new(),
718        Vec::new(),
719        Vec::new(),
720        Vec::new(),
721        Vec::new(),
722    );
723    let (mut yr, mut xr, mut tr, mut zr, mut clr, mut fwr) = (
724        Vec::new(),
725        Vec::new(),
726        Vec::new(),
727        Vec::new(),
728        Vec::new(),
729        Vec::new(),
730    );
731    for i in 0..y.len() {
732        if x[i] < c {
733            yl.push(y[i]);
734            xl.push(x[i]);
735            if let Some(tt) = t {
736                tl.push(tt[i]);
737            }
738            if let Some(zz) = z {
739                zl.extend_from_slice(&zz[i * dz..i * dz + dz]);
740            }
741            if let Some(cc) = cluster {
742                cll.push(cc[i]);
743            }
744            if let Some(ww) = weights {
745                fwl.push(ww[i]);
746            }
747        } else {
748            yr.push(y[i]);
749            xr.push(x[i]);
750            if let Some(tt) = t {
751                tr.push(tt[i]);
752            }
753            if let Some(zz) = z {
754                zr.extend_from_slice(&zz[i * dz..i * dz + dz]);
755            }
756            if let Some(cc) = cluster {
757                clr.push(cc[i]);
758            }
759            if let Some(ww) = weights {
760                fwr.push(ww[i]);
761            }
762        }
763    }
764    let tl_opt = t.map(|_| tl.as_slice());
765    let tr_opt = t.map(|_| tr.as_slice());
766    let zl_opt = z.map(|_| zl.as_slice());
767    let zr_opt = z.map(|_| zr.as_slice());
768    let fwl_opt = weights.map(|_| fwl.as_slice());
769    let fwr_opt = weights.map(|_| fwr.as_slice());
770    let cll_opt = cluster.map(|_| cll.as_slice());
771    let clr_opt = cluster.map(|_| clr.as_slice());
772
773    let fl = fit_side(
774        &yl, &xl, tl_opt, zl_opt, cll_opt, fwl_opt, dz, c, p, q, h_l, b_l, kernel, vce_kind,
775    );
776    let fr = fit_side(
777        &yr, &xr, tr_opt, zr_opt, clr_opt, fwr_opt, dz, c, p, q, h_r, b_r, kernel, vce_kind,
778    );
779
780    let fac = vce::factorial(deriv);
781    let beta_p_diff = &fr.beta_p - &fl.beta_p;
782    let beta_bc_diff = &fr.beta_bc - &fl.beta_bc;
783    let fuzzy = t.is_some();
784    let covs = dz > 0;
785
786    // tau + s_Y by (fuzzy, covs) (R:619-717)
787    let (tau_cl, tau_bc, s_y): (f64, f64, DVector<f64>) = match (fuzzy, covs) {
788        (false, false) => (
789            scalepar * fac * beta_p_diff[(deriv, 0)],
790            scalepar * fac * beta_bc_diff[(deriv, 0)],
791            DVector::from_element(1, 1.0),
792        ),
793        (true, false) => {
794            let tau_y_cl = scalepar * fac * beta_p_diff[(deriv, 0)];
795            let tau_t_cl = fac * beta_p_diff[(deriv, 1)];
796            let tau_y_bc = scalepar * fac * beta_bc_diff[(deriv, 0)];
797            let tau_t_bc = fac * beta_bc_diff[(deriv, 1)];
798            let tcl = tau_y_cl / tau_t_cl;
799            let s = DVector::from_vec(vec![1.0 / tau_t_cl, -(tau_y_cl / (tau_t_cl * tau_t_cl))]);
800            let b_f = DVector::from_vec(vec![tau_y_cl - tau_y_bc, tau_t_cl - tau_t_bc]);
801            let tbc = tcl - s.dot(&b_f);
802            (tcl, tbc, s)
803        }
804        (false, true) => {
805            // sharp + covariates: FWL gamma combined across sides (rdrobust.R:668-686).
806            // tau = scalepar * s_Y . beta_diff[deriv,:] (R:675, no factorial -> deriv=0).
807            let zwz = fl.zwz_p.as_ref().unwrap() + fr.zwz_p.as_ref().unwrap();
808            let zwy = fl.zwy_p.as_ref().unwrap() + fr.zwy_p.as_ref().unwrap();
809            let gamma = vce::gamma_from(&zwz, &zwy, covs_drop_coll); // dz x 1
810            let mut s = DVector::zeros(1 + dz);
811            s[0] = 1.0;
812            for j in 0..dz {
813                s[1 + j] = -gamma[(j, 0)];
814            }
815            let dot = |bd: &DMatrix<f64>| (0..s.len()).map(|k| s[k] * bd[(deriv, k)]).sum::<f64>();
816            (
817                scalepar * dot(&beta_p_diff),
818                scalepar * dot(&beta_bc_diff),
819                s,
820            )
821        }
822        (true, true) => {
823            // fuzzy + covariates (rdrobust.R:688-722): combined FWL gamma (col 0 = Y
824            // partial, col 1 = T partial), then the delta-method ratio over the
825            // covariate-adjusted Y/T derivative estimates.
826            let zwz = fl.zwz_p.as_ref().unwrap() + fr.zwz_p.as_ref().unwrap();
827            let zwy = fl.zwy_p.as_ref().unwrap() + fr.zwy_p.as_ref().unwrap();
828            let gamma = vce::gamma_from(&zwz, &zwy, covs_drop_coll); // dz x 2
829            let cz = 2; // Z block start in beta_diff (after Y, T)
830            let dot = |bd: &DMatrix<f64>, yt: usize, gcol: usize| -> f64 {
831                bd[(deriv, yt)]
832                    + (0..dz)
833                        .map(|j| -gamma[(j, gcol)] * bd[(deriv, cz + j)])
834                        .sum::<f64>()
835            };
836            let tau_y_cl = scalepar * fac * dot(&beta_p_diff, 0, 0);
837            let tau_t_cl = fac * dot(&beta_p_diff, 1, 1);
838            let tau_y_bc = scalepar * fac * dot(&beta_bc_diff, 0, 0);
839            let tau_t_bc = fac * dot(&beta_bc_diff, 1, 1);
840            let tcl = tau_y_cl / tau_t_cl;
841            let s_delta =
842                DVector::from_vec(vec![1.0 / tau_t_cl, -(tau_y_cl / (tau_t_cl * tau_t_cl))]);
843            let b_f = DVector::from_vec(vec![tau_y_cl - tau_y_bc, tau_t_cl - tau_t_bc]);
844            let tbc = tcl - s_delta.dot(&b_f);
845            let mut s = DVector::zeros(2 + dz);
846            s[0] = 1.0 / tau_t_cl;
847            s[1] = -(tau_y_cl / (tau_t_cl * tau_t_cl));
848            for j in 0..dz {
849                s[2 + j] = -(1.0 / tau_t_cl) * gamma[(j, 0)]
850                    + (tau_y_cl / (tau_t_cl * tau_t_cl)) * gamma[(j, 1)];
851            }
852            (tcl, tbc, s)
853        }
854    };
855
856    // variance: conventional uses res_h (p-fit) + (R_p*W_h) meat; robust uses
857    // res_b (q-fit; res_b=res_h for nn) + Q_q meat; both with invG_p (R:750-794).
858    // Clustering routes the meat through the CR1/CRV2/CRV3 path; the robust
859    // variance has four cases (h==b vs h!=b) x (CR1 vs CRV2/3) (R:769-795).
860    let has_cluster = cluster.is_some();
861    let kind = vce::cluster_kind(vce_kind);
862    let crv2 = kind == vce::ClusterKind::Crv2;
863    let hb_match = h_l == b_l && h_r == b_r;
864    let side_v = |f: &SideFit| -> (DMatrix<f64>, DMatrix<f64>) {
865        let res_h = vce::residuals(
866            &f.ex,
867            &f.r_p,
868            &f.inv_g_p,
869            &f.rp_wh,
870            &f.beta_p,
871            &f.d,
872            f.en,
873            vce_kind,
874            &f.edups,
875            &f.edupsid,
876            nnmatch,
877            has_cluster,
878        );
879        // nn shares res_b=res_h, but clustering remaps nn away (rdrobust.R:320),
880        // so a clustered fit always takes the q-fit residual branch.
881        let res_b = if matches!(vce_kind, Vce::NearestNeighbor) && !has_cluster {
882            res_h.clone()
883        } else {
884            vce::residuals(
885                &f.ex,
886                &f.r_q,
887                &f.inv_g_q,
888                &f.rq_wb,
889                &f.beta_q,
890                &f.d,
891                f.en,
892                vce_kind,
893                &f.edups,
894                &f.edupsid,
895                nnmatch,
896                has_cluster,
897            )
898        };
899        if !has_cluster {
900            let v_cl = vce::v_matrix(&f.inv_g_p, &f.rp_wh, &res_h, &s_y);
901            let v_rb = vce::v_matrix(&f.inv_g_p, &f.q_q, &res_b, &s_y);
902            return (v_cl, v_rb);
903        }
904        let groups = vce::cluster_idx(&f.ec);
905        // conventional: p-design at h, bread invG_p (R:769-770)
906        let v_cl = vce::v_cluster(
907            &f.inv_g_p,
908            &f.rp_wh,
909            &res_h,
910            &s_y,
911            &groups,
912            kind,
913            Some(&f.rp_swh),
914            None,
915        );
916        let v_rb = if hb_match {
917            match kind {
918                // h==b: direct q-regression (R:779-783); CR1 bread invG_q, no override
919                vce::ClusterKind::Cr1 => vce::v_cluster(
920                    &f.inv_g_q, &f.rq_wb, &res_b, &s_y, &groups, kind, None, None,
921                ),
922                _ => vce::v_cluster(
923                    &f.inv_g_q,
924                    &f.rq_wb,
925                    &res_b,
926                    &s_y,
927                    &groups,
928                    kind,
929                    Some(&f.rq_swb),
930                    None,
931                ),
932            }
933        } else {
934            match kind {
935                // h!=b CR1: Q_q sandwich, bread invG_p, k_override=q+1 (R:793-794)
936                vce::ClusterKind::Cr1 => vce::v_cluster(
937                    &f.inv_g_p,
938                    &f.q_q,
939                    &res_b,
940                    &s_y,
941                    &groups,
942                    kind,
943                    None,
944                    Some(q + 1),
945                ),
946                // h!=b CRV2/3: decoupled two-stage qq-cluster meat (R:785-788)
947                _ => {
948                    let m = vce::vce_meat_qq_cluster(
949                        &f.q_q, &f.r_q, &f.w_b, &f.inv_g_q, &res_b, &groups, crv2, &s_y,
950                    );
951                    &f.inv_g_p * (m * &f.inv_g_p)
952                }
953            }
954        };
955        (v_cl, v_rb)
956    };
957    let (v_cl_l, v_rb_l) = side_v(&fl);
958    let (v_cl_r, v_rb_r) = side_v(&fr);
959
960    let scale2 = scalepar * scalepar * fac * fac;
961    let v_tau_cl = scale2 * (v_cl_l[(deriv, deriv)] + v_cl_r[(deriv, deriv)]);
962    let v_tau_rb = scale2 * (v_rb_l[(deriv, deriv)] + v_rb_r[(deriv, deriv)]);
963    let se_cl = v_tau_cl.sqrt();
964    let se_rb = v_tau_rb.sqrt();
965
966    // assemble coef / se / z / pv / ci (R:854-863)
967    let coef = [tau_cl, tau_bc, tau_bc];
968    let se = [se_cl, se_cl, se_rb];
969    let quant = -qnorm((1.0 - level / 100.0) / 2.0);
970    let mut z = [0.0; 3];
971    let mut pv = [0.0; 3];
972    let mut ci = [[0.0; 2]; 3];
973    for i in 0..3 {
974        z[i] = coef[i] / se[i];
975        pv[i] = 2.0 * pnorm(-z[i].abs());
976        ci[i] = [coef[i] - quant * se[i], coef[i] + quant * se[i]];
977    }
978
979    RdRobust {
980        coef,
981        se,
982        z,
983        pv,
984        ci,
985        bws: [[h_l, h_r], [b_l, b_r]],
986    }
987}