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    /// The cutoff `c` is not strictly inside the support of `x` (`min(x) < c < max(x)`).
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    /// The fuzzy first stage is constant on both sides of the cutoff with no jump,
401    /// so the treatment effect is not identified (R stops with the same diagnosis).
402    DegenerateFuzzy,
403}
404
405impl std::fmt::Display for RdError {
406    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407        match self {
408            RdError::TooFewObs => {
409                write!(f, "y and x must have at least two observations")
410            }
411            RdError::LengthMismatch {
412                name,
413                len,
414                expected,
415            } => write!(f, "{name} has length {len}, expected {expected}"),
416            RdError::NonFinite { name } => write!(f, "{name} must be finite"),
417            RdError::OneSidedCutoff => {
418                write!(f, "c must lie strictly inside the range of x")
419            }
420            RdError::InvalidOrder => write!(f, "q must be > p and deriv must be <= p"),
421            RdError::InvalidNnmatch => write!(f, "nnmatch must be >= 1"),
422            RdError::InvalidLevel => write!(f, "level must be in (0, 100)"),
423            RdError::NonPositiveBandwidth { name } => write!(f, "{name} must be positive"),
424            RdError::NonNegativeWeightRequired => write!(f, "weights must be non-negative"),
425            RdError::EmptyCovariates => write!(f, "covs must have at least one column"),
426            RdError::DegenerateFuzzy => write!(
427                f,
428                "fuzzy has no variation and no jump at the cutoff; the fuzzy estimator is not identified"
429            ),
430        }
431    }
432}
433
434impl std::error::Error for RdError {}
435
436/// Validate the [`try_rdrobust_with`] inputs and options without running the fit.
437/// Returns `Ok(())` when every check the Python binding enforces passes, otherwise
438/// the first failing [`RdError`]. `dz` is the row stride of `covs` (0 when `covs`
439/// is `None`); `n` is taken from `y`.
440#[allow(clippy::too_many_arguments)]
441fn validate_rdrobust_inputs(
442    y: &[f64],
443    x: &[f64],
444    fuzzy: Option<&[f64]>,
445    covs: Option<&[f64]>,
446    dz: usize,
447    cluster: Option<&[f64]>,
448    weights: Option<&[f64]>,
449    opts: &RdRobustOptions,
450) -> Result<(), RdError> {
451    let n = y.len();
452    if n < 2 {
453        return Err(RdError::TooFewObs);
454    }
455    let ensure_len = |name: &'static str, len: usize| -> Result<(), RdError> {
456        if len == n {
457            Ok(())
458        } else {
459            Err(RdError::LengthMismatch {
460                name,
461                len,
462                expected: n,
463            })
464        }
465    };
466    let ensure_finite = |name: &'static str, values: &[f64]| -> Result<(), RdError> {
467        if values.iter().all(|v| v.is_finite()) {
468            Ok(())
469        } else {
470            Err(RdError::NonFinite { name })
471        }
472    };
473
474    ensure_len("x", x.len())?;
475    ensure_finite("y", y)?;
476    ensure_finite("x", x)?;
477    if let Some(values) = fuzzy {
478        ensure_len("fuzzy", values.len())?;
479        ensure_finite("fuzzy", values)?;
480    }
481    if let Some(values) = cluster {
482        ensure_len("cluster", values.len())?;
483        ensure_finite("cluster", values)?;
484    }
485    if let Some(values) = weights {
486        ensure_len("weights", values.len())?;
487        ensure_finite("weights", values)?;
488        if values.iter().any(|&v| v < 0.0) {
489            return Err(RdError::NonNegativeWeightRequired);
490        }
491    }
492    if let Some(values) = covs {
493        if dz == 0 {
494            return Err(RdError::EmptyCovariates);
495        }
496        // Exact: `values.len() / dz` would silently accept a ragged slice.
497        if values.len() != n * dz {
498            return Err(RdError::LengthMismatch {
499                name: "covs",
500                len: values.len() / dz,
501                expected: n,
502            });
503        }
504        ensure_finite("covs", values)?;
505    }
506
507    if opts.q <= opts.p || opts.deriv > opts.p {
508        return Err(RdError::InvalidOrder);
509    }
510    if opts.nnmatch == 0 {
511        return Err(RdError::InvalidNnmatch);
512    }
513    if !(0.0..100.0).contains(&opts.level) {
514        return Err(RdError::InvalidLevel);
515    }
516    if let Some(r) = opts.rho {
517        if r <= 0.0 {
518            return Err(RdError::NonPositiveBandwidth { name: "rho" });
519        }
520    }
521    if let Some((hl, hr)) = opts.h {
522        if hl <= 0.0 || hr <= 0.0 {
523            return Err(RdError::NonPositiveBandwidth { name: "h" });
524        }
525    }
526    if let Some((bl, br)) = opts.b {
527        if bl <= 0.0 || br <= 0.0 {
528            return Err(RdError::NonPositiveBandwidth { name: "b" });
529        }
530    }
531
532    // R rejects `c <= min(x) | c >= max(x)` (rdrobust.R:244): the cutoff must lie
533    // strictly inside the support so both sides have a window of positive width.
534    // A cutoff at `max(x)` passes a plain "both sides non-empty" test but leaves
535    // the right side with zero range and every pilot fit empty (NaN output).
536    let x_min = x.iter().cloned().fold(f64::INFINITY, f64::min);
537    let x_max = x.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
538    if !(opts.c > x_min && opts.c < x_max) {
539        return Err(RdError::OneSidedCutoff);
540    }
541
542    // R stops when the first stage has no variation on either side and no jump
543    // (rdrobust.R:175-177): the fuzzy estimator divides by a zero first stage.
544    if let Some(tt) = fuzzy {
545        let side = |on_left: bool| -> Vec<f64> {
546            (0..n)
547                .filter(|&i| (x[i] < opts.c) == on_left)
548                .map(|i| tt[i])
549                .collect()
550        };
551        let (tl, tr) = (side(true), side(false));
552        let constant = |v: &[f64]| v.iter().all(|&u| u == v[0]);
553        if constant(&tl) && constant(&tr) && (tl[0] - tr[0]).abs() < f64::EPSILON.sqrt() {
554            return Err(RdError::DegenerateFuzzy);
555        }
556    }
557
558    Ok(())
559}
560
561/// Validated wrapper over [`rdrobust_with`]: run `validate_rdrobust_inputs` first
562/// and, when every check passes, forward verbatim to [`rdrobust_with`] and return
563/// `Ok(result)`. On any degenerate input or option it returns the first matching
564/// [`RdError`] instead of letting the raw path produce `NaN`. The numerics on valid
565/// inputs are identical to [`rdrobust_with`]; only the rejection of bad inputs differs.
566///
567/// `fuzzy`, `covs`, `dz`, `cluster`, and `weights` carry the same meaning as in
568/// [`rdrobust_with`]. `opts` holds every scalar/config knob via [`RdRobustOptions`].
569///
570/// # Example
571///
572/// ```
573/// use rdrobust_core::{try_rdrobust_with, RdError, RdRobustOptions};
574///
575/// // A small sharp RD with a jump of about 2 at the cutoff c = 0; x sorted ascending.
576/// let x: Vec<f64> = (0..200).map(|i| -1.0 + 2.0 * (i as f64 + 0.5) / 200.0).collect();
577/// let y: Vec<f64> = x
578///     .iter()
579///     .enumerate()
580///     .map(|(i, &xi)| 0.5 * xi + if xi >= 0.0 { 2.0 } else { 0.0 } + 0.3 * (i as f64).sin())
581///     .collect();
582///
583/// // Valid options (defaults have q = 2 > p = 1): an Ok result.
584/// let ok = RdRobustOptions::default();
585/// let out = try_rdrobust_with(&y, &x, None, None, 0, None, None, &ok).unwrap();
586/// assert!(out.coef[0].is_finite());
587///
588/// // q <= p (here q = p = 1) is rejected before any fit runs.
589/// let bad = RdRobustOptions { q: 1, ..Default::default() };
590/// let err = try_rdrobust_with(&y, &x, None, None, 0, None, None, &bad);
591/// assert_eq!(err, Err(RdError::InvalidOrder));
592/// ```
593#[allow(clippy::too_many_arguments)]
594pub fn try_rdrobust_with(
595    y: &[f64],
596    x: &[f64],
597    fuzzy: Option<&[f64]>,
598    covs: Option<&[f64]>,
599    dz: usize,
600    cluster: Option<&[f64]>,
601    weights: Option<&[f64]>,
602    opts: &RdRobustOptions,
603) -> Result<RdRobust, RdError> {
604    validate_rdrobust_inputs(y, x, fuzzy, covs, dz, cluster, weights, opts)?;
605    Ok(rdrobust_with(y, x, fuzzy, covs, dz, cluster, weights, opts))
606}
607
608/// Port of `rdrobust` (rdrobust.R:540-907) for the scoped option set: the RD
609/// point estimate (conventional and bias-corrected) with CCT robust variance and
610/// confidence intervals.
611///
612/// `h`/`b` as `Some((left, right))` supplies bandwidths directly; `None` selects
613/// them via [`rdbwselect`]. For `vce = nn`, `x` must be sorted ascending.
614///
615/// With fewer than 20 observations R skips bandwidth selection and uses the full
616/// support, `h = b = max(c - min(x), max(x) - c)`, on both sides (overriding any
617/// `h`, `b`, or `rho`); this port does the same.
618///
619/// The core takes every argument as a required positional; the "R-default" column
620/// below is the value the R/Python wrapper supplies when the user omits the arg.
621///
622/// # Arguments
623///
624/// * `y` - Outcome values, one per observation.
625/// * `x` - Running variable, one per observation (sorted ascending when `vce = nn`).
626/// * `t` - Fuzzy treatment status; `None` for a sharp design (R `fuzzy`, default NULL).
627/// * `z` - Covariates as a flattened row-major `n x dz` slice; `None` for no covariates (R `covs`, default NULL).
628/// * `dz` - Covariate column count (the row stride of `z`); 0 when `z` is `None`. Rust-core detail, no R default.
629/// * `c` - RD cutoff (R `c`, default 0).
630/// * `p` - Polynomial order for the point estimate (R `p`, default 1, or `deriv + 1`).
631/// * `q` - Polynomial order for the bias correction (R `q`, default `p + 1`, must exceed `p`).
632/// * `deriv` - Derivative order of the estimand: 0 = level, 1 = kink (R `deriv`, default 0).
633/// * `kernel` - Kernel for the local-polynomial weights (R `kernel`, default triangular).
634/// * `vce_kind` - Variance estimator before clustering remap: nn, hc0-hc3 (R `vce`, default nn).
635/// * `nnmatch` - Minimum neighbors for `vce = nn` (R `nnmatch`, default 3).
636/// * `covs_drop_coll` - Drop collinear covariates in the FWL partialling. This port
637///   defaults to false (R's default is true); the flag only switches the ginv versus
638///   Cholesky solve in the FWL step, and the projection onto col(Z) is unique, so it
639///   changes no coefficient. R `covs_drop`; the flag is estimate-identical, not a
640///   default-parity match.
641/// * `scaleregul` - Regularization scale in bandwidth selection; 0 removes it (R `scaleregul`, default 1).
642/// * `scalepar` - Scaling applied to the RD parameter (R `scalepar`, default 1).
643/// * `level` - Confidence-interval level in percent, e.g. 95 (R `level`, default 95).
644/// * `bwselect` - Bandwidth-selection method when `h` is `None`, e.g. `"mserd"` (R `bwselect`, default "mserd").
645/// * `cluster` - Cluster ids; presence remaps `vce_kind` to CR1/CRV2/CRV3 (R `cluster`, default NULL).
646/// * `weights` - User weights multiplying the kernel; `None` for unweighted (R `weights`, default NULL).
647/// * `masspoints` - Mass-point handling: `"off"`, `"check"`, or `"adjust"` (R `masspoints`, default "adjust").
648/// * `stdvars` - Standardize `x` and `y` before bandwidth selection (R `stdvars`, default true).
649/// * `bwrestrict` - Clamp selected bandwidths to the range of `x` (R `bwrestrict`, default true).
650/// * `bwcheck` - Minimum unique observations required in the pilot bandwidth; `None` to skip (R `bwcheck`, default NULL).
651/// * `rho` - Sets `b = h / rho`; `None` leaves `b` from `b`/selection (R `rho`, default NULL).
652/// * `sharpbw` - Force sharp-RD bandwidth selection in a fuzzy design (R `sharpbw`, default false).
653/// * `h` - Main bandwidths `(left, right)`; `None` triggers selection via [`rdbwselect`] (R `h`, default NULL).
654/// * `b` - Bias bandwidths `(left, right)`; `None` defaults to `h` (or `h / rho`) (R `b`, default NULL).
655///
656/// # Returns
657///
658/// An [`RdRobust`] with the three-row coef/se/z/pv/ci and the 2x2 bandwidths used.
659#[allow(clippy::too_many_arguments)]
660pub fn rdrobust(
661    y: &[f64],
662    x: &[f64],
663    t: Option<&[f64]>,
664    z: Option<&[f64]>,
665    dz: usize,
666    c: f64,
667    p: usize,
668    q: usize,
669    deriv: usize,
670    kernel: Kernel,
671    vce_kind: Vce,
672    nnmatch: usize,
673    covs_drop_coll: bool,
674    scaleregul: f64,
675    scalepar: f64,
676    level: f64,
677    bwselect: &str,
678    cluster: Option<&[f64]>,
679    weights: Option<&[f64]>,
680    masspoints: &str,
681    stdvars: bool,
682    bwrestrict: bool,
683    bwcheck: Option<usize>,
684    rho: Option<f64>,
685    sharpbw: bool,
686    h: Option<(f64, f64)>,
687    b: Option<(f64, f64)>,
688) -> RdRobust {
689    // perf_comp: a fuzzy design with one-sided (constant-T) compliance. R selects
690    // the bandwidth as if SHARP (treatment dropped) but estimates fuzzy at it
691    // (rdrobust.R:166-185, 581-591); `sharpbw=true` forces the same regardless.
692    let perf_comp = t.is_some_and(|tt| crate::bwselect::perf_comp(x, tt, c));
693    // treatment used for BANDWIDTH SELECTION (dropped -> sharp BW when perf_comp/sharpbw)
694    let bw_t = if perf_comp || sharpbw { None } else { t };
695
696    // Small samples (rdrobust.R:303-307): with fewer than 20 observations R skips
697    // data-driven selection entirely and uses the full support on both sides,
698    // h = b = max(range_l, range_r), overriding any user-supplied h/b/rho. The
699    // ranges are taken on the original x scale (R measures them on the stdvars
700    // scale but then applies them to the de-standardized data, which is a
701    // units mismatch; this port keeps the bandwidths in x units).
702    let h = if y.len() < 20 {
703        let x_min = x.iter().cloned().fold(f64::INFINITY, f64::min);
704        let x_max = x.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
705        let full = (c - x_min).abs().max((x_max - c).abs());
706        Some((full, full))
707    } else {
708        h
709    };
710    let (rho, b) = if y.len() < 20 { (None, None) } else { (rho, b) };
711
712    // bandwidths (rho: b = h/rho; rdrobust.R:296-300 manual-h path, 501-504 auto path)
713    let (h_l, h_r, b_l, b_r) = match h {
714        Some((hl, hr)) => {
715            let (bl, br) = match (rho, b) {
716                (Some(r), _) => (hl / r, hr / r),   // rho overrides any b
717                (None, Some((bl, br))) => (bl, br), // explicit b
718                (None, None) => (hl, hr),           // rho defaults to 1 -> b = h
719            };
720            (hl, hr, bl, br)
721        }
722        None => {
723            let bw = rdbwselect(
724                y,
725                x,
726                bw_t,
727                z,
728                dz,
729                c,
730                p,
731                q,
732                deriv,
733                kernel,
734                vce_kind,
735                nnmatch,
736                covs_drop_coll,
737                scaleregul,
738                bwselect,
739                cluster,
740                weights,
741                masspoints,
742                stdvars,
743                bwrestrict,
744                bwcheck,
745            );
746            match rho {
747                Some(r) => (bw.h_l, bw.h_r, bw.h_l / r, bw.h_r / r),
748                None => (bw.h_l, bw.h_r, bw.b_l, bw.b_r),
749            }
750        }
751    };
752
753    // A failed selection (NaN bandwidth: an empty pilot window or a 0/0 stage)
754    // yields NaN everywhere in R, since `w = K((x - c)/NaN)` is NA. A NaN
755    // bandwidth here would instead empty every window and fit zeros, so short-
756    // circuit to the same NaN outcome rather than report a spurious 0 +/- 0.
757    if [h_l, h_r, b_l, b_r].iter().any(|v| v.is_nan()) {
758        return RdRobust {
759            coef: [f64::NAN; 3],
760            se: [f64::NAN; 3],
761            z: [f64::NAN; 3],
762            pv: [f64::NAN; 3],
763            ci: [[f64::NAN; 2]; 3],
764            bws: [[h_l, h_r], [b_l, b_r]],
765        };
766    }
767
768    // split sides (x<c left, x>=c right); z is flattened row-major (n x dz)
769    let (mut yl, mut xl, mut tl, mut zl, mut cll, mut fwl) = (
770        Vec::new(),
771        Vec::new(),
772        Vec::new(),
773        Vec::new(),
774        Vec::new(),
775        Vec::new(),
776    );
777    let (mut yr, mut xr, mut tr, mut zr, mut clr, mut fwr) = (
778        Vec::new(),
779        Vec::new(),
780        Vec::new(),
781        Vec::new(),
782        Vec::new(),
783        Vec::new(),
784    );
785    for i in 0..y.len() {
786        if x[i] < c {
787            yl.push(y[i]);
788            xl.push(x[i]);
789            if let Some(tt) = t {
790                tl.push(tt[i]);
791            }
792            if let Some(zz) = z {
793                zl.extend_from_slice(&zz[i * dz..i * dz + dz]);
794            }
795            if let Some(cc) = cluster {
796                cll.push(cc[i]);
797            }
798            if let Some(ww) = weights {
799                fwl.push(ww[i]);
800            }
801        } else {
802            yr.push(y[i]);
803            xr.push(x[i]);
804            if let Some(tt) = t {
805                tr.push(tt[i]);
806            }
807            if let Some(zz) = z {
808                zr.extend_from_slice(&zz[i * dz..i * dz + dz]);
809            }
810            if let Some(cc) = cluster {
811                clr.push(cc[i]);
812            }
813            if let Some(ww) = weights {
814                fwr.push(ww[i]);
815            }
816        }
817    }
818    let tl_opt = t.map(|_| tl.as_slice());
819    let tr_opt = t.map(|_| tr.as_slice());
820    let zl_opt = z.map(|_| zl.as_slice());
821    let zr_opt = z.map(|_| zr.as_slice());
822    let fwl_opt = weights.map(|_| fwl.as_slice());
823    let fwr_opt = weights.map(|_| fwr.as_slice());
824    let cll_opt = cluster.map(|_| cll.as_slice());
825    let clr_opt = cluster.map(|_| clr.as_slice());
826
827    let fl = fit_side(
828        &yl, &xl, tl_opt, zl_opt, cll_opt, fwl_opt, dz, c, p, q, h_l, b_l, kernel, vce_kind,
829    );
830    let fr = fit_side(
831        &yr, &xr, tr_opt, zr_opt, clr_opt, fwr_opt, dz, c, p, q, h_r, b_r, kernel, vce_kind,
832    );
833
834    let fac = vce::factorial(deriv);
835    let beta_p_diff = &fr.beta_p - &fl.beta_p;
836    let beta_bc_diff = &fr.beta_bc - &fl.beta_bc;
837    let fuzzy = t.is_some();
838    let covs = dz > 0;
839
840    // tau + s_Y by (fuzzy, covs) (R:619-717)
841    let (tau_cl, tau_bc, s_y): (f64, f64, DVector<f64>) = match (fuzzy, covs) {
842        (false, false) => (
843            scalepar * fac * beta_p_diff[(deriv, 0)],
844            scalepar * fac * beta_bc_diff[(deriv, 0)],
845            DVector::from_element(1, 1.0),
846        ),
847        (true, false) => {
848            let tau_y_cl = scalepar * fac * beta_p_diff[(deriv, 0)];
849            let tau_t_cl = fac * beta_p_diff[(deriv, 1)];
850            let tau_y_bc = scalepar * fac * beta_bc_diff[(deriv, 0)];
851            let tau_t_bc = fac * beta_bc_diff[(deriv, 1)];
852            let tcl = tau_y_cl / tau_t_cl;
853            let s = DVector::from_vec(vec![1.0 / tau_t_cl, -(tau_y_cl / (tau_t_cl * tau_t_cl))]);
854            let b_f = DVector::from_vec(vec![tau_y_cl - tau_y_bc, tau_t_cl - tau_t_bc]);
855            let tbc = tcl - s.dot(&b_f);
856            (tcl, tbc, s)
857        }
858        (false, true) => {
859            // sharp + covariates: FWL gamma combined across sides (rdrobust.R:668-686).
860            // tau = scalepar * s_Y . beta_diff[deriv,:] (R:675, no factorial -> deriv=0).
861            let zwz = fl.zwz_p.as_ref().unwrap() + fr.zwz_p.as_ref().unwrap();
862            let zwy = fl.zwy_p.as_ref().unwrap() + fr.zwy_p.as_ref().unwrap();
863            let gamma = vce::gamma_from(&zwz, &zwy, covs_drop_coll); // dz x 1
864            let mut s = DVector::zeros(1 + dz);
865            s[0] = 1.0;
866            for j in 0..dz {
867                s[1 + j] = -gamma[(j, 0)];
868            }
869            let dot = |bd: &DMatrix<f64>| (0..s.len()).map(|k| s[k] * bd[(deriv, k)]).sum::<f64>();
870            (
871                scalepar * dot(&beta_p_diff),
872                scalepar * dot(&beta_bc_diff),
873                s,
874            )
875        }
876        (true, true) => {
877            // fuzzy + covariates (rdrobust.R:688-722): combined FWL gamma (col 0 = Y
878            // partial, col 1 = T partial), then the delta-method ratio over the
879            // covariate-adjusted Y/T derivative estimates.
880            let zwz = fl.zwz_p.as_ref().unwrap() + fr.zwz_p.as_ref().unwrap();
881            let zwy = fl.zwy_p.as_ref().unwrap() + fr.zwy_p.as_ref().unwrap();
882            let gamma = vce::gamma_from(&zwz, &zwy, covs_drop_coll); // dz x 2
883            let cz = 2; // Z block start in beta_diff (after Y, T)
884            let dot = |bd: &DMatrix<f64>, yt: usize, gcol: usize| -> f64 {
885                bd[(deriv, yt)]
886                    + (0..dz)
887                        .map(|j| -gamma[(j, gcol)] * bd[(deriv, cz + j)])
888                        .sum::<f64>()
889            };
890            let tau_y_cl = scalepar * fac * dot(&beta_p_diff, 0, 0);
891            let tau_t_cl = fac * dot(&beta_p_diff, 1, 1);
892            let tau_y_bc = scalepar * fac * dot(&beta_bc_diff, 0, 0);
893            let tau_t_bc = fac * dot(&beta_bc_diff, 1, 1);
894            let tcl = tau_y_cl / tau_t_cl;
895            let s_delta =
896                DVector::from_vec(vec![1.0 / tau_t_cl, -(tau_y_cl / (tau_t_cl * tau_t_cl))]);
897            let b_f = DVector::from_vec(vec![tau_y_cl - tau_y_bc, tau_t_cl - tau_t_bc]);
898            let tbc = tcl - s_delta.dot(&b_f);
899            let mut s = DVector::zeros(2 + dz);
900            s[0] = 1.0 / tau_t_cl;
901            s[1] = -(tau_y_cl / (tau_t_cl * tau_t_cl));
902            for j in 0..dz {
903                s[2 + j] = -(1.0 / tau_t_cl) * gamma[(j, 0)]
904                    + (tau_y_cl / (tau_t_cl * tau_t_cl)) * gamma[(j, 1)];
905            }
906            (tcl, tbc, s)
907        }
908    };
909
910    // variance: conventional uses res_h (p-fit) + (R_p*W_h) meat; robust uses
911    // res_b (q-fit; res_b=res_h for nn) + Q_q meat; both with invG_p (R:750-794).
912    // Clustering routes the meat through the CR1/CRV2/CRV3 path; the robust
913    // variance has four cases (h==b vs h!=b) x (CR1 vs CRV2/3) (R:769-795).
914    let has_cluster = cluster.is_some();
915    let kind = vce::cluster_kind(vce_kind);
916    let crv2 = kind == vce::ClusterKind::Crv2;
917    let hb_match = h_l == b_l && h_r == b_r;
918    let side_v = |f: &SideFit| -> (DMatrix<f64>, DMatrix<f64>) {
919        let res_h = vce::residuals(
920            &f.ex,
921            &f.r_p,
922            &f.inv_g_p,
923            &f.rp_wh,
924            &f.beta_p,
925            &f.d,
926            f.en,
927            vce_kind,
928            &f.edups,
929            &f.edupsid,
930            nnmatch,
931            has_cluster,
932        );
933        // nn shares res_b=res_h, but clustering remaps nn away (rdrobust.R:320),
934        // so a clustered fit always takes the q-fit residual branch.
935        let res_b = if matches!(vce_kind, Vce::NearestNeighbor) && !has_cluster {
936            res_h.clone()
937        } else {
938            vce::residuals(
939                &f.ex,
940                &f.r_q,
941                &f.inv_g_q,
942                &f.rq_wb,
943                &f.beta_q,
944                &f.d,
945                f.en,
946                vce_kind,
947                &f.edups,
948                &f.edupsid,
949                nnmatch,
950                has_cluster,
951            )
952        };
953        if !has_cluster {
954            let v_cl = vce::v_matrix(&f.inv_g_p, &f.rp_wh, &res_h, &s_y);
955            let v_rb = vce::v_matrix(&f.inv_g_p, &f.q_q, &res_b, &s_y);
956            return (v_cl, v_rb);
957        }
958        let groups = vce::cluster_idx(&f.ec);
959        // conventional: p-design at h, bread invG_p (R:769-770)
960        let v_cl = vce::v_cluster(
961            &f.inv_g_p,
962            &f.rp_wh,
963            &res_h,
964            &s_y,
965            &groups,
966            kind,
967            Some(&f.rp_swh),
968            None,
969        );
970        let v_rb = if hb_match {
971            match kind {
972                // h==b: direct q-regression (R:779-783); CR1 bread invG_q, no override
973                vce::ClusterKind::Cr1 => vce::v_cluster(
974                    &f.inv_g_q, &f.rq_wb, &res_b, &s_y, &groups, kind, None, None,
975                ),
976                _ => vce::v_cluster(
977                    &f.inv_g_q,
978                    &f.rq_wb,
979                    &res_b,
980                    &s_y,
981                    &groups,
982                    kind,
983                    Some(&f.rq_swb),
984                    None,
985                ),
986            }
987        } else {
988            match kind {
989                // h!=b CR1: Q_q sandwich, bread invG_p, k_override=q+1 (R:793-794)
990                vce::ClusterKind::Cr1 => vce::v_cluster(
991                    &f.inv_g_p,
992                    &f.q_q,
993                    &res_b,
994                    &s_y,
995                    &groups,
996                    kind,
997                    None,
998                    Some(q + 1),
999                ),
1000                // h!=b CRV2/3: decoupled two-stage qq-cluster meat (R:785-788)
1001                _ => {
1002                    let m = vce::vce_meat_qq_cluster(
1003                        &f.q_q, &f.r_q, &f.w_b, &f.inv_g_q, &res_b, &groups, crv2, &s_y,
1004                    );
1005                    &f.inv_g_p * (m * &f.inv_g_p)
1006                }
1007            }
1008        };
1009        (v_cl, v_rb)
1010    };
1011    let (v_cl_l, v_rb_l) = side_v(&fl);
1012    let (v_cl_r, v_rb_r) = side_v(&fr);
1013
1014    let scale2 = scalepar * scalepar * fac * fac;
1015    let v_tau_cl = scale2 * (v_cl_l[(deriv, deriv)] + v_cl_r[(deriv, deriv)]);
1016    let v_tau_rb = scale2 * (v_rb_l[(deriv, deriv)] + v_rb_r[(deriv, deriv)]);
1017    let se_cl = v_tau_cl.sqrt();
1018    let se_rb = v_tau_rb.sqrt();
1019
1020    // assemble coef / se / z / pv / ci (R:854-863)
1021    let coef = [tau_cl, tau_bc, tau_bc];
1022    let se = [se_cl, se_cl, se_rb];
1023    let quant = -qnorm((1.0 - level / 100.0) / 2.0);
1024    let mut z = [0.0; 3];
1025    let mut pv = [0.0; 3];
1026    let mut ci = [[0.0; 2]; 3];
1027    for i in 0..3 {
1028        z[i] = coef[i] / se[i];
1029        pv[i] = 2.0 * pnorm(-z[i].abs());
1030        ci[i] = [coef[i] - quant * se[i], coef[i] + quant * se[i]];
1031    }
1032
1033    RdRobust {
1034        coef,
1035        se,
1036        z,
1037        pv,
1038        ci,
1039        bws: [[h_l, h_r], [b_l, b_r]],
1040    }
1041}
1042
1043#[cfg(test)]
1044mod tests {
1045    use super::*;
1046
1047    fn dgp(n: usize) -> (Vec<f64>, Vec<f64>) {
1048        let x: Vec<f64> = (0..n)
1049            .map(|i| -1.0 + 2.0 * (i as f64 + 0.5) / n as f64)
1050            .collect();
1051        let y: Vec<f64> = x
1052            .iter()
1053            .enumerate()
1054            .map(|(i, &xi)| 0.5 * xi + if xi >= 0.0 { 2.0 } else { 0.0 } + 0.3 * (i as f64).sin())
1055            .collect();
1056        (x, y)
1057    }
1058
1059    #[test]
1060    fn cutoff_must_be_strictly_inside_support() {
1061        let (x, y) = dgp(200);
1062        let at = |c: f64| {
1063            try_rdrobust_with(
1064                &y,
1065                &x,
1066                None,
1067                None,
1068                0,
1069                None,
1070                None,
1071                &RdRobustOptions {
1072                    c,
1073                    ..Default::default()
1074                },
1075            )
1076        };
1077        assert_eq!(at(x[x.len() - 1]).map(|_| ()), Err(RdError::OneSidedCutoff));
1078        assert_eq!(at(x[0]).map(|_| ()), Err(RdError::OneSidedCutoff));
1079        assert_eq!(at(2.0).map(|_| ()), Err(RdError::OneSidedCutoff));
1080        assert!(at(0.0).is_ok());
1081        assert!(at(x[1]).is_ok());
1082    }
1083
1084    #[test]
1085    fn cutoff_at_max_x_does_not_panic_in_raw_path() {
1086        // The raw path has no validation; an empty pilot window must not panic
1087        // (debug-mode `n - 1` underflow in the nn residual). The right side is a
1088        // single point with zero range, so selection fails and, as in R, the
1089        // whole result is NaN rather than a spurious 0 +/- 0.
1090        let (x, y) = dgp(200);
1091        let c = x[x.len() - 1];
1092        let out = rdrobust_with(
1093            &y,
1094            &x,
1095            None,
1096            None,
1097            0,
1098            None,
1099            None,
1100            &RdRobustOptions {
1101                c,
1102                ..Default::default()
1103            },
1104        );
1105        assert!(out.coef.iter().chain(out.se.iter()).all(|v| v.is_nan()));
1106        assert!(out.bws[0][0].is_nan());
1107    }
1108
1109    #[test]
1110    fn ragged_covariates_rejected() {
1111        let (x, y) = dgp(100);
1112        let z = vec![0.0; 2 * 100 - 1];
1113        let err = try_rdrobust_with(
1114            &y,
1115            &x,
1116            None,
1117            Some(&z),
1118            2,
1119            None,
1120            None,
1121            &RdRobustOptions::default(),
1122        );
1123        assert!(matches!(
1124            err,
1125            Err(RdError::LengthMismatch { name: "covs", .. })
1126        ));
1127    }
1128
1129    #[test]
1130    fn degenerate_fuzzy_rejected_but_one_sided_compliance_allowed() {
1131        let (x, y) = dgp(200);
1132        let flat = vec![0.5; 200];
1133        let err = try_rdrobust_with(
1134            &y,
1135            &x,
1136            Some(&flat),
1137            None,
1138            0,
1139            None,
1140            None,
1141            &RdRobustOptions::default(),
1142        );
1143        assert_eq!(err.map(|_| ()), Err(RdError::DegenerateFuzzy));
1144        // constant on both sides WITH a jump is a (sharp-like) fuzzy design R accepts
1145        let step: Vec<f64> = x
1146            .iter()
1147            .map(|&v| if v >= 0.0 { 1.0 } else { 0.0 })
1148            .collect();
1149        let out = try_rdrobust_with(
1150            &y,
1151            &x,
1152            Some(&step),
1153            None,
1154            0,
1155            None,
1156            None,
1157            &RdRobustOptions::default(),
1158        )
1159        .unwrap();
1160        let sharp = rdrobust_with(
1161            &y,
1162            &x,
1163            None,
1164            None,
1165            0,
1166            None,
1167            None,
1168            &RdRobustOptions::default(),
1169        );
1170        assert!((out.coef[0] - sharp.coef[0]).abs() < 1e-12);
1171        assert_eq!(out.bws, sharp.bws);
1172    }
1173
1174    #[test]
1175    fn fewer_than_twenty_obs_use_full_support() {
1176        let x: Vec<f64> = (0..12).map(|i| -0.8 + 2.0 * i as f64 / 11.0).collect();
1177        let y: Vec<f64> = x
1178            .iter()
1179            .map(|&v| 0.3 * v + if v >= 0.0 { 1.0 } else { 0.0 })
1180            .collect();
1181        let full = (x[11] - 0.0).abs().max((0.0 - x[0]).abs());
1182        for opts in [
1183            RdRobustOptions::default(),
1184            RdRobustOptions {
1185                h: Some((0.1, 0.1)),
1186                ..Default::default()
1187            },
1188            RdRobustOptions {
1189                h: Some((0.1, 0.1)),
1190                rho: Some(0.5),
1191                ..Default::default()
1192            },
1193        ] {
1194            let out = rdrobust_with(&y, &x, None, None, 0, None, None, &opts);
1195            assert_eq!(out.bws, [[full, full], [full, full]]);
1196            assert!(out.coef[0].is_finite() && out.se[2].is_finite());
1197        }
1198        // at n = 20 selection runs again
1199        let (x20, y20) = dgp(20);
1200        let out = rdrobust_with(
1201            &y20,
1202            &x20,
1203            None,
1204            None,
1205            0,
1206            None,
1207            None,
1208            &RdRobustOptions::default(),
1209        );
1210        assert!(out.bws[0][0] < 1.0);
1211    }
1212}