Skip to main content

rdrobust_core/
bwselect.rs

1//! Bandwidth selector -- port of `rdbwselect` (R rdbwselect.R), the orchestration
2//! that runs ~14 `rdrobust_bw` pilot fits and combines their `V`/`B`/`R` into the
3//! MSE/CER-optimal `h`/`b` bandwidths.
4//!
5//! Implemented: sharp/fuzzy, covariates, clusters, user weights, nn/hc0-hc3, all 10
6//! selectors + CER, and the prep options (`stdvars` rescaling, mass-point
7//! `M`-counts, `bwrestrict` range clamps, `bwcheck` floor). Implements the
8//! `vcache`: each side's 3 distinct `(o,nu)` V-fits are computed once and reused
9//! across the 7 pilots (`compute_vfit` + `assemble_from_vfit`), bit-identical to
10//! the per-call form.
11//!
12//! Parity gate: continuous `h`/`b` to ~1e-8 vs R, exact on the discrete selector
13//! branch.
14
15use crate::bw::{assemble_from_vfit, compute_vfit, VFit};
16use crate::{Kernel, Vce};
17
18/// Selected bandwidths: `h`/`b` for the left and right sides (common selectors
19/// duplicate the scalar into both sides).
20#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct Bws {
22    /// Main bandwidth `h` (point-estimate window), left side.
23    pub h_l: f64,
24    /// Main bandwidth `h` (point-estimate window), right side.
25    pub h_r: f64,
26    /// Bias (pilot) bandwidth `b` (bias-correction window), left side.
27    pub b_l: f64,
28    /// Bias (pilot) bandwidth `b` (bias-correction window), right side.
29    pub b_r: f64,
30}
31
32/// Pilot kernel constant `C_c` (rdbwselect.R:265-274).
33fn c_c(kernel: Kernel) -> f64 {
34    match kernel {
35        Kernel::Epanechnikov => 2.34,
36        Kernel::Uniform => 1.843,
37        Kernel::Triangular => 2.576,
38    }
39}
40
41/// Sample standard deviation (ddof = 1), R `sd`.
42fn sd(x: &[f64]) -> f64 {
43    let n = x.len() as f64;
44    let mean = x.iter().sum::<f64>() / n;
45    (x.iter().map(|&v| (v - mean) * (v - mean)).sum::<f64>() / (n - 1.0)).sqrt()
46}
47
48/// R quantile type 2 on a SORTED slice (rdbwselect.R:117 `quantile(.,type=2)`):
49/// j = floor(n p) (1-based); if the fractional part g>0, return x_(j+1); if g==0,
50/// average x_(j) and x_(j+1).
51fn quantile_type2(sorted: &[f64], p: f64) -> f64 {
52    let n = sorted.len();
53    let np = n as f64 * p;
54    let j = np.floor() as usize; // 1-based floor index
55    let g = np - j as f64;
56    if g > 0.0 {
57        sorted[j.min(n - 1)] // x_(j+1), 0-based = sorted[j]
58    } else {
59        let lo = j.max(1) - 1; // x_(j)
60        let hi = j.min(n - 1); // x_(j+1)
61        0.5 * (sorted[lo] + sorted[hi])
62    }
63}
64
65/// One-sided ("perfect") compliance test, R `var(T_l)==0 | var(T_r)==0`
66/// (rdrobust.R:179, rdbwselect.R:342): the treatment is constant on at least one
67/// side of the cutoff. Tested as exact equality to the side's first value, which
68/// is what a zero sample variance means and avoids a floating-point mean that
69/// may not reproduce a constant exactly. An empty side counts as constant.
70pub(crate) fn perf_comp(x: &[f64], t: &[f64], c: f64) -> bool {
71    let constant = |on_left: bool| -> bool {
72        let mut first: Option<f64> = None;
73        (0..t.len())
74            .filter(|&i| (x[i] < c) == on_left)
75            .all(|i| *first.get_or_insert(t[i]) == t[i])
76    };
77    constant(true) || constant(false)
78}
79
80/// R `min(a, b)`: NaN-propagating, unlike `f64::min`, which drops a NaN operand.
81/// A pilot stage that fails (empty window, 0/0) must surface as NaN rather than
82/// be silently replaced by the clamp bound.
83fn r_min(a: f64, b: f64) -> f64 {
84    if a.is_nan() || b.is_nan() {
85        f64::NAN
86    } else {
87        a.min(b)
88    }
89}
90
91/// R `max(a, b)`: NaN-propagating counterpart of [`r_min`].
92fn r_max(a: f64, b: f64) -> f64 {
93    if a.is_nan() || b.is_nan() {
94        f64::NAN
95    } else {
96        a.max(b)
97    }
98}
99
100/// Median of three values (R `median` of an odd count = the middle; NaN if any is NaN).
101fn median3(a: f64, b: f64, c: f64) -> f64 {
102    if a.is_nan() || b.is_nan() || c.is_nan() {
103        return f64::NAN;
104    }
105    let mut v = [a, b, c];
106    v.sort_by(|x, y| x.total_cmp(y));
107    v[1]
108}
109
110/// Select the RD bandwidths `h` (point estimate) and `b` (bias correction) by
111/// running the ~14 `rdrobust_bw` pilot fits and combining their `V`/`B`/`R` per the
112/// chosen criterion (R rdbwselect.R). `x` must be sorted ascending when `vce = nn`.
113///
114/// # Arguments
115///
116/// - `y`, `x`: outcome and running variable (length n; `x` sorted for nn).
117/// - `t`: treatment take-up for a fuzzy design; `None` for sharp. When `t` is
118///   constant on either side (one-sided compliance), R drops it and selects a
119///   sharp bandwidth (rdbwselect.R:334-346); this port does the same.
120/// - `z`, `dz`: covariates as a flat row-major `n x dz` slice, and the column count
121///   (`None` / `0` for no covariates).
122/// - `c`: the cutoff.
123/// - `p`: local-polynomial order of the point estimate (R default 1).
124/// - `q`: order of the bias-correction fit (R default 2, `q > p`).
125/// - `deriv`: derivative order of the estimand (R default 0).
126/// - `kernel`: weighting kernel (drives the pilot constants).
127/// - `vce`: variance estimator used in the pilot `V` (a `cluster` vector remaps it).
128/// - `nnmatch`: neighbors per side for nearest-neighbor variance.
129/// - `covs_drop_coll`: drop collinear covariate columns (ginv path) vs Cholesky.
130/// - `scaleregul`: regularization scale on the bias-bandwidth denominator (R default 1).
131/// - `bwselect`: selector name -- `mserd`, `msetwo`, `msesum`, `msecomb1`,
132///   `msecomb2`, `cerrd`, `certwo`, `cersum`, `cercomb1`, or `cercomb2`.
133/// - `cluster`: cluster ids; their presence remaps `vce` to CR1/CRV2/CRV3 and uses
134///   the cluster count in the CER rate.
135/// - `weights`: user weights `W` (multiplied into the kernel weights).
136/// - `masspoints`: `"adjust"` uses the unique-point count `M` for pilot rates and
137///   may auto-set `bwcheck`; `"off"` disables both.
138/// - `stdvars`: standardize `x`/`y`/`c` before selection, then rescale the chosen
139///   bandwidths by the `x` standard deviation.
140/// - `bwrestrict`: clamp each pilot stage to the side's support range.
141/// - `bwcheck`: floor the pilot and final bandwidths at the k-th nearest unique
142///   distance (`None` to disable).
143#[allow(clippy::too_many_arguments)]
144pub fn rdbwselect(
145    y: &[f64],
146    x: &[f64],
147    t: Option<&[f64]>,
148    z: Option<&[f64]>,
149    dz: usize,
150    c: f64,
151    p: usize,
152    q: usize,
153    deriv: usize,
154    kernel: Kernel,
155    vce: Vce,
156    nnmatch: usize,
157    covs_drop_coll: bool,
158    scaleregul: f64,
159    bwselect: &str,
160    cluster: Option<&[f64]>,
161    weights: Option<&[f64]>,
162    masspoints: &str,
163    stdvars: bool,
164    bwrestrict: bool,
165    bwcheck: Option<usize>,
166) -> Bws {
167    let n = y.len();
168
169    // One-sided compliance: select as sharp (R `perf_comp`, rdbwselect.R:334-346).
170    let t = t.filter(|tt| !perf_comp(x, tt, c));
171
172    // stdvars (rdrobust.R:146-153): run selection on standardized x/y/c, then
173    // multiply the chosen bandwidths by x_sd at the end. No-op when stdvars=false.
174    let (x_sd, y_sd) = if stdvars { (sd(x), sd(y)) } else { (1.0, 1.0) };
175    let xv: Vec<f64> = x.iter().map(|v| v / x_sd).collect();
176    let yv: Vec<f64> = y.iter().map(|v| v / y_sd).collect();
177    let x = xv.as_slice();
178    let y = yv.as_slice();
179    let c = c / x_sd;
180
181    // BWp = min(sd(x), IQR_type2(x)/1.349); c_bw = C_c * BWp * N^(-1/5) (or M^-1/5).
182    let mut xs = x.to_vec();
183    xs.sort_by(|a, b| a.total_cmp(b));
184    let x_iq = quantile_type2(&xs, 0.75) - quantile_type2(&xs, 0.25);
185    let bwp = sd(x).min(x_iq / 1.349);
186
187    // split L (x<c) / R (x>=c), preserving (sorted) order; z flat row-major (n x dz)
188    let (mut yl, mut xl, mut tl, mut zl, mut cll, mut fwl) = (
189        Vec::new(),
190        Vec::new(),
191        Vec::new(),
192        Vec::new(),
193        Vec::new(),
194        Vec::new(),
195    );
196    let (mut yr, mut xr, mut tr, mut zr, mut clr, mut fwr) = (
197        Vec::new(),
198        Vec::new(),
199        Vec::new(),
200        Vec::new(),
201        Vec::new(),
202        Vec::new(),
203    );
204    for i in 0..n {
205        if x[i] < c {
206            yl.push(y[i]);
207            xl.push(x[i]);
208            if let Some(tt) = t {
209                tl.push(tt[i]);
210            }
211            if let Some(zz) = z {
212                zl.extend_from_slice(&zz[i * dz..i * dz + dz]);
213            }
214            if let Some(cc) = cluster {
215                cll.push(cc[i]);
216            }
217            if let Some(ww) = weights {
218                fwl.push(ww[i]);
219            }
220        } else {
221            yr.push(y[i]);
222            xr.push(x[i]);
223            if let Some(tt) = t {
224                tr.push(tt[i]);
225            }
226            if let Some(zz) = z {
227                zr.extend_from_slice(&zz[i * dz..i * dz + dz]);
228            }
229            if let Some(cc) = cluster {
230                clr.push(cc[i]);
231            }
232            if let Some(ww) = weights {
233                fwr.push(ww[i]);
234            }
235        }
236    }
237    let tl_opt = t.map(|_| tl.as_slice());
238    let tr_opt = t.map(|_| tr.as_slice());
239    let zl_opt = z.map(|_| zl.as_slice());
240    let zr_opt = z.map(|_| zr.as_slice());
241    let cll_opt = cluster.map(|_| cll.as_slice());
242    let clr_opt = cluster.map(|_| clr.as_slice());
243    let fwl_opt = weights.map(|_| fwl.as_slice());
244    let fwr_opt = weights.map(|_| fwr.as_slice());
245
246    // distinct-cluster counts per side -> the CER bandwidth factor (rdrobust.R:477)
247    let n_unique = |v: &[f64]| -> usize {
248        let mut s = v.to_vec();
249        s.sort_by(|a, b| a.total_cmp(b));
250        s.dedup();
251        s.len()
252    };
253    let g_l = cluster.map(|_| n_unique(&cll));
254    let g_r = cluster.map(|_| n_unique(&clr));
255    let range_l = (c - xs[0]).abs();
256    let range_r = (c - xs[n - 1]).abs();
257
258    // ----- masspoints / bwrestrict / bwcheck prep (spec 10; rdrobust.R:361-406) -----
259    let nl = xl.len();
260    let nr = xr.len();
261    let mp_on = masspoints == "check" || masspoints == "adjust";
262    let (m_l, m_r) = if mp_on || bwcheck.is_some() {
263        (n_unique(&xl), n_unique(&xr))
264    } else {
265        (nl, nr)
266    };
267    let m = m_l + m_r;
268    // auto-set bwcheck=10 when adjust detects mass points (>=20% duplicates)
269    let mut bwcheck_eff = bwcheck;
270    if mp_on {
271        let mass_l = 1.0 - m_l as f64 / nl as f64;
272        let mass_r = 1.0 - m_r as f64 / nr as f64;
273        if (mass_l >= 0.2 || mass_r >= 0.2) && masspoints == "adjust" && bwcheck.is_none() {
274            bwcheck_eff = Some(10);
275        }
276    }
277    // pilot bandwidth: M^(-1/5) under masspoints=adjust, else N^(-1/5)
278    let pilot_pow = if masspoints == "adjust" {
279        m as f64
280    } else {
281        n as f64
282    };
283    let mut c_bw = c_c(kernel) * bwp * pilot_pow.powf(-1.0 / 5.0);
284    // bwrestrict clamp bounds (reused for all per-stage clamps)
285    let bw_max_l = range_l;
286    let bw_max_r = range_r;
287    let bw_max = bw_max_l.max(bw_max_r);
288    if bwrestrict {
289        c_bw = r_min(c_bw, bw_max);
290    }
291    // bwcheck floor: distance to the k-th nearest unique point per side
292    let (bw_min_l, bw_min_r) = match bwcheck_eff {
293        Some(bc) => {
294            let mut ul = xl.clone();
295            ul.sort_by(|a, b| a.total_cmp(b));
296            ul.dedup();
297            let mut ur = xr.clone();
298            ur.sort_by(|a, b| a.total_cmp(b));
299            ur.dedup();
300            // X_uniq_l descending (closest to c last); X_uniq_r ascending
301            let bcl = bc.min(m_l);
302            let bcr = bc.min(m_r);
303            let lhs = (ul[ul.len() - bcl] - c).abs(); // descending[bcl-1] = ascending[len-bcl]
304            let rhs = (ur[bcr - 1] - c).abs();
305            (lhs, rhs)
306        }
307        None => (0.0, 0.0),
308    };
309    if bwcheck_eff.is_some() {
310        c_bw = r_max(r_max(c_bw, bw_min_l), bw_min_r);
311    }
312    // per-stage clamp helpers (no-ops when the option is off)
313    let restrict = |v: f64, bmax: f64| if bwrestrict { r_min(v, bmax) } else { v };
314    let floor_side = |v: f64, bmin: f64| {
315        if bwcheck_eff.is_some() {
316            r_max(v, bmin)
317        } else {
318            v
319        }
320    };
321    let floor_comb = |v: f64| {
322        if bwcheck_eff.is_some() {
323            r_max(r_max(v, bw_min_l), bw_min_r)
324        } else {
325            v
326        }
327    };
328
329    // vcache (functions.R:213-231): the V-fit depends only on (o,nu) since h_V=c_bw
330    // is fixed across pilots. The 7 pilot calls per side use only 3 distinct (o,nu)
331    // V-fits -- precompute each once, then run the B-fit per pilot via h_B.
332    let mk_vfit = |yy: &[f64], xx: &[f64], tt, zz, cc, ww, o, nu| {
333        compute_vfit(
334            yy,
335            xx,
336            tt,
337            zz,
338            dz,
339            c,
340            o,
341            nu,
342            c_bw,
343            vce,
344            nnmatch,
345            covs_drop_coll,
346            kernel,
347            cc,
348            ww,
349        )
350    };
351    let vd_l = mk_vfit(&yl, &xl, tl_opt, zl_opt, cll_opt, fwl_opt, q + 1, q + 1);
352    let vb_l = mk_vfit(&yl, &xl, tl_opt, zl_opt, cll_opt, fwl_opt, q, p + 1);
353    let vh_l = mk_vfit(&yl, &xl, tl_opt, zl_opt, cll_opt, fwl_opt, p, deriv);
354    let vd_r = mk_vfit(&yr, &xr, tr_opt, zr_opt, clr_opt, fwr_opt, q + 1, q + 1);
355    let vb_r = mk_vfit(&yr, &xr, tr_opt, zr_opt, clr_opt, fwr_opt, q, p + 1);
356    let vh_r = mk_vfit(&yr, &xr, tr_opt, zr_opt, clr_opt, fwr_opt, p, deriv);
357
358    // one pilot B-fit + assembly against a cached V-fit (h_V = c_bw fixed)
359    let asm = |vf: &VFit, yy: &[f64], xx: &[f64], tt, zz, cc, ww, o, nu, o_b, h_b, scale| {
360        assemble_from_vfit(
361            vf, yy, xx, tt, zz, dz, c, o, nu, o_b, c_bw, h_b, scale, vce, nnmatch, kernel, cc, ww,
362        )
363    };
364
365    // ----- d-stage (o=q+1, scale=0, no regularization) -----
366    let cdl = asm(
367        &vd_l,
368        &yl,
369        &xl,
370        tl_opt,
371        zl_opt,
372        cll_opt,
373        fwl_opt,
374        q + 1,
375        q + 1,
376        q + 2,
377        range_l,
378        0.0,
379    );
380    let cdr = asm(
381        &vd_r,
382        &yr,
383        &xr,
384        tr_opt,
385        zr_opt,
386        clr_opt,
387        fwr_opt,
388        q + 1,
389        q + 1,
390        q + 2,
391        range_r,
392        0.0,
393    );
394    let rate_d = cdl.rate;
395    let d_bw_l = (cdl.v / cdl.b.powi(2)).powf(rate_d);
396    let d_bw_r = (cdr.v / cdr.b.powi(2)).powf(rate_d);
397    let d_bw_s = ((cdl.v + cdr.v) / (cdr.b + cdl.b).powi(2)).powf(rate_d);
398    let d_bw_d = ((cdl.v + cdr.v) / (cdr.b - cdl.b).powi(2)).powf(rate_d);
399    // d-stage clamps: bwrestrict cap then bwcheck floor (TWO per-side, SUM/RD combined)
400    let d_bw_l = floor_side(restrict(d_bw_l, bw_max_l), bw_min_l);
401    let d_bw_r = floor_side(restrict(d_bw_r, bw_max_r), bw_min_r);
402    let d_bw_s = floor_comb(restrict(d_bw_s, bw_max));
403    let d_bw_d = floor_comb(restrict(d_bw_d, bw_max));
404
405    // helper for the regularized b/h combine (RD uses Br-Bl, SUM uses Br+Bl)
406    let reg_two =
407        |cv: f64, cb: f64, cr: f64, rate: f64| (cv / (cb.powi(2) + scaleregul * cr)).powf(rate);
408    let reg_comb = |vl: f64, vr: f64, b_combined: f64, rl: f64, rr: f64, rate: f64| {
409        ((vl + vr) / (b_combined.powi(2) + scaleregul * (rl + rr))).powf(rate)
410    };
411
412    // ----- TWO (per-side h_B = d_bw_l/_r) -----
413    let cbl = asm(
414        &vb_l,
415        &yl,
416        &xl,
417        tl_opt,
418        zl_opt,
419        cll_opt,
420        fwl_opt,
421        q,
422        p + 1,
423        q + 1,
424        d_bw_l,
425        scaleregul,
426    );
427    let cbr = asm(
428        &vb_r,
429        &yr,
430        &xr,
431        tr_opt,
432        zr_opt,
433        clr_opt,
434        fwr_opt,
435        q,
436        p + 1,
437        q + 1,
438        d_bw_r,
439        scaleregul,
440    );
441    let rate_b = cbl.rate;
442    let b_bw_l = restrict(reg_two(cbl.v, cbl.b, cbl.r, rate_b), bw_max_l);
443    let b_bw_r = restrict(reg_two(cbr.v, cbr.b, cbr.r, rate_b), bw_max_r);
444    let chl = asm(
445        &vh_l, &yl, &xl, tl_opt, zl_opt, cll_opt, fwl_opt, p, deriv, q, b_bw_l, scaleregul,
446    );
447    let chr = asm(
448        &vh_r, &yr, &xr, tr_opt, zr_opt, clr_opt, fwr_opt, p, deriv, q, b_bw_r, scaleregul,
449    );
450    let rate_h = chl.rate;
451    let h_bw_l = restrict(reg_two(chl.v, chl.b, chl.r, rate_h), bw_max_l);
452    let h_bw_r = restrict(reg_two(chr.v, chr.b, chr.r, rate_h), bw_max_r);
453
454    // ----- SUM (shared h_B = d_bw_s, Br+Bl) -----
455    let cbl_s = asm(
456        &vb_l,
457        &yl,
458        &xl,
459        tl_opt,
460        zl_opt,
461        cll_opt,
462        fwl_opt,
463        q,
464        p + 1,
465        q + 1,
466        d_bw_s,
467        scaleregul,
468    );
469    let cbr_s = asm(
470        &vb_r,
471        &yr,
472        &xr,
473        tr_opt,
474        zr_opt,
475        clr_opt,
476        fwr_opt,
477        q,
478        p + 1,
479        q + 1,
480        d_bw_s,
481        scaleregul,
482    );
483    let b_bw_s = restrict(
484        reg_comb(
485            cbl_s.v,
486            cbr_s.v,
487            cbr_s.b + cbl_s.b,
488            cbl_s.r,
489            cbr_s.r,
490            rate_b,
491        ),
492        bw_max,
493    );
494    let chl_s = asm(
495        &vh_l, &yl, &xl, tl_opt, zl_opt, cll_opt, fwl_opt, p, deriv, q, b_bw_s, scaleregul,
496    );
497    let chr_s = asm(
498        &vh_r, &yr, &xr, tr_opt, zr_opt, clr_opt, fwr_opt, p, deriv, q, b_bw_s, scaleregul,
499    );
500    let h_bw_s = restrict(
501        reg_comb(
502            chl_s.v,
503            chr_s.v,
504            chr_s.b + chl_s.b,
505            chl_s.r,
506            chr_s.r,
507            rate_h,
508        ),
509        bw_max,
510    );
511
512    // ----- RD (shared h_B = d_bw_d, Br-Bl) -----
513    let cbl_d = asm(
514        &vb_l,
515        &yl,
516        &xl,
517        tl_opt,
518        zl_opt,
519        cll_opt,
520        fwl_opt,
521        q,
522        p + 1,
523        q + 1,
524        d_bw_d,
525        scaleregul,
526    );
527    let cbr_d = asm(
528        &vb_r,
529        &yr,
530        &xr,
531        tr_opt,
532        zr_opt,
533        clr_opt,
534        fwr_opt,
535        q,
536        p + 1,
537        q + 1,
538        d_bw_d,
539        scaleregul,
540    );
541    let b_bw_d = restrict(
542        reg_comb(
543            cbl_d.v,
544            cbr_d.v,
545            cbr_d.b - cbl_d.b,
546            cbl_d.r,
547            cbr_d.r,
548            rate_b,
549        ),
550        bw_max,
551    );
552    let chl_d = asm(
553        &vh_l, &yl, &xl, tl_opt, zl_opt, cll_opt, fwl_opt, p, deriv, q, b_bw_d, scaleregul,
554    );
555    let chr_d = asm(
556        &vh_r, &yr, &xr, tr_opt, zr_opt, clr_opt, fwr_opt, p, deriv, q, b_bw_d, scaleregul,
557    );
558    let h_bw_d = restrict(
559        reg_comb(
560            chl_d.v,
561            chr_d.v,
562            chr_d.b - chl_d.b,
563            chl_d.r,
564            chr_d.r,
565            rate_h,
566        ),
567        bw_max,
568    );
569
570    // ----- combine + CER -----
571    let (h_rd, b_rd) = (h_bw_d, b_bw_d);
572    let (h_sum, b_sum) = (h_bw_s, b_bw_s);
573    let h_c1 = r_min(h_rd, h_sum);
574    let b_c1 = r_min(b_rd, b_sum);
575    let h_c2_l = median3(h_rd, h_sum, h_bw_l);
576    let h_c2_r = median3(h_rd, h_sum, h_bw_r);
577    let b_c2_l = median3(b_rd, b_sum, b_bw_l);
578    let b_c2_r = median3(b_rd, b_sum, b_bw_r);
579    let pf = p as f64;
580    // CER rate factor: cluster count (g_l+g_r) replaces N when clustered (R:476-477)
581    let cer_base = match (g_l, g_r) {
582        (Some(gl), Some(gr)) => (gl + gr) as f64,
583        _ => n as f64,
584    };
585    let cer_h = cer_base.powf(-(pf / ((3.0 + pf) * (3.0 + 2.0 * pf))));
586    let cer_b = 1.0;
587
588    let common = |h: f64, b: f64| Bws {
589        h_l: h,
590        h_r: h,
591        b_l: b,
592        b_r: b,
593    };
594    let bws = match bwselect {
595        "mserd" | "" => common(h_rd, b_rd),
596        "msesum" => common(h_sum, b_sum),
597        "msetwo" => Bws {
598            h_l: h_bw_l,
599            h_r: h_bw_r,
600            b_l: b_bw_l,
601            b_r: b_bw_r,
602        },
603        "msecomb1" => common(h_c1, b_c1),
604        "msecomb2" => Bws {
605            h_l: h_c2_l,
606            h_r: h_c2_r,
607            b_l: b_c2_l,
608            b_r: b_c2_r,
609        },
610        "cerrd" => common(h_rd * cer_h, b_rd * cer_b),
611        "cersum" => common(h_sum * cer_h, b_sum * cer_b),
612        "certwo" => Bws {
613            h_l: h_bw_l * cer_h,
614            h_r: h_bw_r * cer_h,
615            b_l: b_bw_l * cer_b,
616            b_r: b_bw_r * cer_b,
617        },
618        "cercomb1" => common(h_c1 * cer_h, b_c1 * cer_b),
619        "cercomb2" => Bws {
620            h_l: h_c2_l * cer_h,
621            h_r: h_c2_r * cer_h,
622            b_l: b_c2_l * cer_b,
623            b_r: b_c2_r * cer_b,
624        },
625        other => panic!("unknown bwselect {other}"),
626    };
627    // de-standardize: bandwidths return on the original x scale (rdrobust.R:467-469)
628    Bws {
629        h_l: bws.h_l * x_sd,
630        h_r: bws.h_r * x_sd,
631        b_l: bws.b_l * x_sd,
632        b_r: bws.b_r * x_sd,
633    }
634}
635
636#[cfg(test)]
637mod tests {
638    use super::*;
639
640    #[test]
641    fn quantile_type2_even_n_averages() {
642        // n=4, p=0.5: np=2, g=0 -> avg of x_(2),x_(3)
643        let s = [1.0, 2.0, 3.0, 4.0];
644        assert_eq!(quantile_type2(&s, 0.5), 2.5);
645    }
646
647    #[test]
648    fn median3_picks_middle() {
649        assert_eq!(median3(3.0, 1.0, 2.0), 2.0);
650        assert!(median3(3.0, f64::NAN, 2.0).is_nan());
651    }
652
653    #[test]
654    fn clamps_propagate_nan_like_r() {
655        assert!(r_min(f64::NAN, 1.0).is_nan());
656        assert!(r_max(1.0, f64::NAN).is_nan());
657        assert_eq!(r_min(2.0, 1.0), 1.0);
658        assert_eq!(r_max(2.0, 1.0), 2.0);
659    }
660
661    #[test]
662    fn perf_comp_detects_constant_side_exactly() {
663        let x = [-0.5, -0.25, 0.25, 0.5];
664        // constant left (0.1 repeated: a float mean would not reproduce it exactly)
665        assert!(perf_comp(&x, &[0.1, 0.1, 0.0, 1.0], 0.0));
666        // constant right
667        assert!(perf_comp(&x, &[0.0, 1.0, 0.3, 0.3], 0.0));
668        // varying on both sides
669        assert!(!perf_comp(&x, &[0.0, 1.0, 0.0, 1.0], 0.0));
670    }
671}