rd-stream 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rd_stream/_engine.py ADDED
@@ -0,0 +1,755 @@
1
+ """rdrobust's estimator, over one side of the cutoff at a time.
2
+
3
+ `Side` holds one side's units in order of distance from the cutoff (see
4
+ _kernels.py). `select_bandwidths` is rdbwselect's three-step plug-in
5
+ (Calonico, Cattaneo and Titiunik 2014; Calonico, Cattaneo and Farrell 2020)
6
+ for all ten selectors, and `estimate` the local-polynomial fit with its
7
+ conventional and robust bias-corrected variances, both as R's rdrobust 4.1.1
8
+ computes them, for sharp designs without covariates.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import copy
14
+ import math
15
+ from dataclasses import dataclass
16
+
17
+ import numpy as np
18
+
19
+ from . import _cluster
20
+ from . import _kernels as K
21
+ from ._moments import kernel_poly, moments_mixed
22
+
23
+ SQRT_EPS = math.sqrt(np.finfo(float).eps)
24
+ SELECTORS = ("mserd", "msetwo", "msesum", "msecomb1", "msecomb2",
25
+ "cerrd", "certwo", "cersum", "cercomb1", "cercomb2")
26
+ _C_C = {K.TRIANGULAR: 2.576, K.EPANECHNIKOV: 2.34, K.UNIFORM: 1.843}
27
+ _DUMMY_I = np.zeros(1, np.int64)
28
+ _DUMMY_F = np.zeros(1)
29
+ _RADIUS_MARGIN = 1 - 1e-10 # held rows cover d <= radius; windows stay a little inside
30
+
31
+
32
+ class NeedWider(Exception):
33
+ """A step needs rows beyond those held (``memory="window"``): `radius`,
34
+ in units of the running variable, is the distance from the cutoff it
35
+ needs (None: more, by how much unknown)."""
36
+
37
+ def __init__(self, radius=None):
38
+ super().__init__(radius)
39
+ self.radius = radius
40
+
41
+
42
+ class FullSums:
43
+ """Power sums over one whole side, for fits whose window holds every
44
+ unit of the side and that need no residuals (rdbwselect's range fit for
45
+ C_d), when the rows held cover only a window near the cutoff.
46
+
47
+ Sw[m] = sum f u^m and SD[m, j] = sum f u^m D_j with u = d / D, D the
48
+ side's largest distance from the cutoff in the units of the side's t."""
49
+
50
+ def __init__(self, Sw, SD, D, d_max, sgn):
51
+ self.Sw, self.SD, self.D, self.d_max, self.sgn = Sw, SD, D, d_max, sgn
52
+
53
+ def scaled(self, x_sd, y_sd):
54
+ SD = self.SD.copy()
55
+ SD[:, 0] /= y_sd
56
+ return FullSums(self.Sw, SD, self.D / x_sd, self.d_max / x_sd, self.sgn)
57
+
58
+ def columns(self, cols):
59
+ return FullSums(self.Sw, np.ascontiguousarray(self.SD[:, cols]), self.D, self.d_max,
60
+ self.sgn)
61
+
62
+ def moments_w(self, h, kern, A):
63
+ from ._moments import _combine
64
+ return _combine(self.Sw[:, None], kernel_poly(kern, h, self.D), self.D, A,
65
+ self.sgn)[:, 0]
66
+
67
+ def moments_D(self, h, kern, A):
68
+ from ._moments import _combine
69
+ return _combine(self.SD, kernel_poly(kern, h, self.D), self.D, A, self.sgn)
70
+
71
+
72
+ class Side:
73
+ """One side's units, nearest the cutoff first.
74
+
75
+ Rows: x with the response matrix D (columns y, then the treatment take-up
76
+ for a fuzzy design), optional sampling weights f and cluster codes cl.
77
+ Collapsed units: x with counts cnt, column sums SD and within-value
78
+ cross-products M2 (units x columns x columns). `sy` and `m2` are the
79
+ current combined response D s (`combine`), which the variance passes use.
80
+ """
81
+
82
+ def __init__(self, x, c, *, D=None, f=None, cl=None, n_clusters=0,
83
+ cnt=None, SD=None, M2=None, x_sd=1.0, y_sd=1.0, dT=0):
84
+ self.dT = dT # 1 with a take-up column (fuzzy), after y
85
+ # the window path (memory="window"): the units held are those within
86
+ # radius_raw of the cutoff; n_side and M_side count the whole side
87
+ self.x_scale = x_sd
88
+ self.radius_raw = math.inf
89
+ self.radius = math.inf
90
+ self.full = None
91
+ self.prefer_full = False # a slab-backed side takes C_d's sums from `full`
92
+ self.x = x
93
+ self.c = c
94
+ self.t = x / x_sd - c / x_sd if x_sd != 1.0 else x - c
95
+ self.d = np.abs(self.t)
96
+ self.rows = cnt is None
97
+ if self.rows:
98
+ D = D.reshape(x.shape[0], -1)
99
+ if y_sd != 1.0:
100
+ D = D.copy()
101
+ D[:, 0] /= y_sd
102
+ self.D = D
103
+ self.M2 = None
104
+ self.cnt, self.cntf = _DUMMY_I, _DUMMY_F
105
+ self.nobs = x.shape[0]
106
+ else:
107
+ SD = SD.reshape(x.shape[0], -1)
108
+ if y_sd != 1.0:
109
+ SD = SD.copy()
110
+ SD[:, 0] /= y_sd
111
+ M2 = M2.copy()
112
+ M2[:, 0, :] /= y_sd
113
+ M2[:, :, 0] /= y_sd
114
+ self.D, self.M2 = SD, M2
115
+ self.cnt = cnt
116
+ self.cntf = cnt.astype(np.float64)
117
+ self.cum = np.cumsum(cnt)
118
+ self.nobs = int(self.cum[-1]) if cnt.shape[0] else 0
119
+ self.ncol = self.D.shape[1]
120
+ self.dZ = self.ncol - 1 - dT # covariates, after y and the take-up
121
+ self.sy = np.ascontiguousarray(self.D[:, 0])
122
+ self.m2 = _DUMMY_F if self.rows else np.ascontiguousarray(self.M2[:, 0, 0])
123
+ self.f = f
124
+ self.cl = cl
125
+ self.n_clusters = n_clusters
126
+ self._clo = [None] # the rows ordered by cluster, shared with copies of the side
127
+ self.run_start = K.runs(self.d)
128
+ self.M = self.run_start.shape[0] - 1 # distinct values of x held
129
+ self.n_units = x.shape[0]
130
+ self.n_side, self.M_side = self.nobs, self.M # the whole side's
131
+
132
+ def held_window(self, radius_raw, full, n_side, M_side):
133
+ """Mark the side as holding only the units within `radius_raw` of the
134
+ cutoff (raw units), with the whole side's power sums and counts."""
135
+ self.radius_raw = radius_raw
136
+ self.radius = radius_raw / self.x_scale
137
+ self.full = full
138
+ self.n_side, self.M_side = int(n_side), int(M_side)
139
+ return self
140
+
141
+ def scaled(self, x_sd, y_sd):
142
+ """The same side with x and y divided by their standard deviations
143
+ (rdrobust's stdvars, for the bandwidth step; the take-up is not
144
+ scaled)."""
145
+ if self.rows:
146
+ out = Side(self.x, self.c, D=self.D, f=self.f, cl=self.cl,
147
+ n_clusters=self.n_clusters, x_sd=x_sd, y_sd=y_sd, dT=self.dT)
148
+ else:
149
+ out = Side(self.x, self.c, cnt=self.cnt, SD=self.D, M2=self.M2, x_sd=x_sd,
150
+ y_sd=y_sd, dT=self.dT)
151
+ out._clo = self._clo
152
+ if math.isfinite(self.radius_raw):
153
+ out.held_window(self.radius_raw,
154
+ None if self.full is None else self.full.scaled(x_sd, y_sd),
155
+ self.n_side, self.M_side)
156
+ return out
157
+
158
+ def columns(self, cols, dT=0):
159
+ """The side with only the response columns `cols` (dT: whether the
160
+ second of them is a take-up)."""
161
+ out = copy.copy(self)
162
+ out.dT = dT
163
+ out.dZ = len(cols) - 1 - dT
164
+ out.D = np.ascontiguousarray(self.D[:, cols])
165
+ if not self.rows:
166
+ out.M2 = np.ascontiguousarray(self.M2[:, cols][:, :, cols])
167
+ out.ncol = len(cols)
168
+ out.sy = np.ascontiguousarray(out.D[:, 0])
169
+ out.m2 = _DUMMY_F if self.rows else np.ascontiguousarray(out.M2[:, 0, 0])
170
+ if self.full is not None:
171
+ out.full = self.full.columns(cols)
172
+ return out
173
+
174
+ def combine(self, s):
175
+ """The side whose response is D s (the variance passes' variable)."""
176
+ s = np.asarray(s, dtype=np.float64)
177
+ if self.ncol == 1 and s.shape[0] == 1 and s[0] == 1.0:
178
+ return self
179
+ out = copy.copy(self)
180
+ out.sy = np.ascontiguousarray(self.D @ s)
181
+ if not self.rows:
182
+ out.m2 = np.ascontiguousarray(np.einsum("nij,i,j->n", self.M2, s, s))
183
+ return out
184
+
185
+ # ---- sums over windows
186
+
187
+ def nobs_in(self, k):
188
+ if self.rows:
189
+ return k
190
+ return int(self.cum[k - 1]) if k > 0 else 0
191
+
192
+ def distinct_in(self, k):
193
+ """Distinct values of x among the first k units."""
194
+ return int(np.searchsorted(self.run_start, k, side="left"))
195
+
196
+ def window(self, h, kern):
197
+ if h > self.radius * _RADIUS_MARGIN:
198
+ raise NeedWider(h * self.x_scale)
199
+ return K.window_len(self.t, h, kern)
200
+
201
+ def covers_side(self, h):
202
+ """Whether a window of half-width h holds every unit of the side,
203
+ held or not (then `full` has its sums)."""
204
+ return self.full is not None and h > self.full.d_max
205
+
206
+ def _f(self):
207
+ return (self.f, True) if self.f is not None else (_DUMMY_F, False)
208
+
209
+ def moments_w(self, k, h, kern, A):
210
+ """sum w t^a (w = f K/h; times the unit's count)."""
211
+ f, use_f = self._f()
212
+ return K.moments(self.t, self.cntf, not self.rows, f, use_f, k, h, kern, 1, A)
213
+
214
+ def moments_D(self, k, h, kern, A):
215
+ """sum w t^a D_j, (A + 1) x columns."""
216
+ f, use_f = self._f()
217
+ return np.column_stack([
218
+ K.moments(self.t, np.ascontiguousarray(self.D[:, j]), True, f, use_f, k, h, kern, 1, A)
219
+ for j in range(self.ncol)])
220
+
221
+ def zwd(self, k, h, kern):
222
+ """sum w z d' over the window: the covariates' weighted cross-products
223
+ with every response column (dZ x columns)."""
224
+ zc = slice(1 + self.dT, self.ncol)
225
+ f, use_f = self._f()
226
+ w = K.weights(self.t, f, use_f, k, h, kern)
227
+ if self.rows:
228
+ return (self.D[:k, zc] * w[:, None]).T @ self.D[:k]
229
+ DD = self.M2[:k] + self.D[:k, :, None] * self.D[:k, None, :] / self.cntf[:k, None, None]
230
+ return np.einsum("n,nij->ij", w, DD[:, zc, :])
231
+
232
+ def moments_ss(self, ss, k, h, kern, A):
233
+ f, use_f = self._f()
234
+ return K.moments(self.t, ss, True, f, use_f, k, h, kern, 2, A)
235
+
236
+ # ---- residuals and variance meat (of the combined response)
237
+
238
+ def residuals(self, k, vce, matches, h=None, kern=None, beta=None, Ginv=None, d=0,
239
+ n_window=None):
240
+ """(sum of squared residuals per unit, signed row residuals or None),
241
+ `beta` the combined response's coefficients. `n_window`: the window's
242
+ observations, when the units are part of it (a slab)."""
243
+ signed = self.cl is not None
244
+ if vce == "nn":
245
+ nrun = int(np.searchsorted(self.run_start, k, side="left"))
246
+ return K.nn_residuals(self.d, self.cnt, self.sy, self.m2, self.sy, self.rows,
247
+ self.run_start, nrun, matches, signed)
248
+ mode = {"hc0": 0, "hc1": 1, "hc2": 2, "hc3": 3, "cr2": 0, "cr3": 0}[vce]
249
+ n = self.nobs_in(k) if n_window is None else n_window
250
+ factor = 1.0
251
+ if mode == 1 and self.cl is None:
252
+ factor = math.sqrt(n / (n - d))
253
+ f, use_f = self._f()
254
+ return K.hc_residuals(self.t, self.cntf, self.sy, self.m2, self.rows, f, use_f, k, h,
255
+ kern, np.ascontiguousarray(beta, dtype=np.float64),
256
+ np.ascontiguousarray(Ginv), mode, factor, signed)
257
+
258
+ def meat(self, k, h, kern, P, ss, res, Ginv=None, vce="hc1"):
259
+ """sum (w r)(w r)' res^2 over the window, or its cluster-robust
260
+ version (CRV1, CRV2 or CRV3), as rdrobust_vce computes it."""
261
+ if self.cl is None:
262
+ return gram(self.moments_ss(ss, k, h, kern, 2 * (P - 1)), P - 1)
263
+ f, use_f = self._f()
264
+ if vce in ("cr2", "cr3"):
265
+ L, u, seen = self.cluster_sums(k, h, kern, P, res)
266
+ return _cluster.meat(L, u, seen, Ginv, 2 if vce == "cr2" else 3)
267
+ scores = K.poly_scores(self.t, f, use_f, k, h, kern, P, res)
268
+ return self.cluster_meat(scores, k, P)
269
+
270
+ def cluster_meat(self, scores, k, k_df):
271
+ M, G = K.cluster_meat_ordered(scores, k, *self._cluster_order())
272
+ n = k
273
+ return M * ((n - 1) / (n - k_df)) * (G / (G - 1))
274
+
275
+ # ---- per-cluster sums over the window [0, k), a cluster per thread
276
+
277
+ def _cluster_order(self):
278
+ if self._clo[0] is None:
279
+ self._clo[0] = K.cluster_order(self.cl, self.n_clusters)
280
+ return self._clo[0]
281
+
282
+ def cluster_sums(self, k, h, kern, P, res):
283
+ f, use_f = self._f()
284
+ return K.cluster_sums_ordered(self.t, f, use_f, k, h, kern, P, res,
285
+ *self._cluster_order())
286
+
287
+ def cluster_sums_qq(self, k, b, kern, Pq, Q, res):
288
+ f, use_f = self._f()
289
+ return K.cluster_sums_qq_ordered(self.t, f, use_f, k, b, kern, Pq, Q, res,
290
+ *self._cluster_order())
291
+
292
+ def cluster_score_sums(self, scores, k):
293
+ return K.cluster_score_sums_ordered(scores, k, *self._cluster_order())
294
+
295
+ # ---- the window sums the steps take (a slab-backed side has the same)
296
+
297
+ @property
298
+ def clustered(self):
299
+ return self.cl is not None
300
+
301
+ def run_distance(self, j):
302
+ """The distance from the cutoff of the j-th distinct value (1-based)."""
303
+ return self.d[self.run_start[j - 1]]
304
+
305
+ def residual_meat(self, svec, k, h, kern, P, vce, matches, beta, Ginv, d):
306
+ """The variance meat of a pilot fit over the window of k units for the
307
+ combined response D svec, its coefficients `beta`."""
308
+ cs = self.combine(svec)
309
+ ss, res = cs.residuals(k, vce, matches, h, kern, beta, Ginv, d)
310
+ return cs.meat(k, h, kern, P, ss, res, Ginv, vce)
311
+
312
+ def variance_sums(self, svec, fit, *, p, q, kern, vce, matches):
313
+ """The final step's squared-residual moments without clusters: at h
314
+ (from the residuals at h, and from those at b), mixed, and at b."""
315
+ k, kh, kb, h, b = fit.k, fit.kh, fit.kb, fit.h, fit.b
316
+ cs = self.combine(svec)
317
+ if vce == "nn":
318
+ ss_h, _ = cs.residuals(k, "nn", matches)
319
+ ss_b = ss_h
320
+ else:
321
+ ss_h, _ = cs.residuals(k, vce, 0, h, kern, fit.beta_p @ svec, fit.Gp_inv, p + 1)
322
+ ss_b, _ = cs.residuals(k, vce, 0, b, kern, fit.beta_q @ svec, fit.Gq_inv, q + 1)
323
+ f, use_f = self._f()
324
+ mh = self.moments_ss(ss_h, kh, h, kern, 2 * p)
325
+ mh_b = mh if ss_b is ss_h else self.moments_ss(ss_b, kh, h, kern, 2 * p)
326
+ mx = moments_mixed(self.t, ss_b, f, use_f, min(kh, kb), h, b, kern, p + q)
327
+ mb = self.moments_ss(ss_b, kb, b, kern, 2 * q)
328
+ return mh, mh_b, mx, mb
329
+
330
+ def cluster_meats(self, svec, fit, *, p, q, kern, vce, matches, hb_match):
331
+ """The final step's cluster-robust meats: (conventional, robust); the
332
+ robust one is in rdrobust's q-order basis when h = b."""
333
+ k, h, b = fit.k, fit.h, fit.b
334
+ P, Pq = p + 1, q + 1
335
+ cs = self.combine(svec)
336
+ if vce == "nn":
337
+ ss_h, res_h = cs.residuals(k, "nn", matches)
338
+ ss_b, res_b = ss_h, res_h
339
+ else:
340
+ ss_h, res_h = cs.residuals(k, vce, 0, h, kern, fit.beta_p @ svec, fit.Gp_inv, P)
341
+ ss_b, res_b = cs.residuals(k, vce, 0, b, kern, fit.beta_q @ svec, fit.Gq_inv, Pq)
342
+ f, use_f = self._f()
343
+ if vce in ("cr2", "cr3"):
344
+ mode = 2 if vce == "cr2" else 3
345
+ L, u, seen = self.cluster_sums(k, h, kern, P, res_h)
346
+ meat_cl = _cluster.meat(L, u, seen, fit.Gp_inv, mode)
347
+ if hb_match:
348
+ L, u, seen = self.cluster_sums(k, h, kern, Pq, res_b)
349
+ return meat_cl, _cluster.meat(L, u, seen, fit.Gq_inv, mode)
350
+ _, Q = K.final_rows(self.t, f, use_f, k, h, b, kern, p, q, fit.g, fit.L)
351
+ L, Pg, uQ, uq, seen = self.cluster_sums_qq(k, b, kern, Pq,
352
+ np.ascontiguousarray(Q), res_b)
353
+ return meat_cl, _cluster.meat_qq(L, Pg, uQ, uq, seen, fit.Gq_inv, mode)
354
+ RW, Q = K.final_rows(self.t, f, use_f, k, h, b, kern, p, q, fit.g, fit.L)
355
+ meat_cl = self.cluster_meat(RW * res_h[:, None], k, P)
356
+ if hb_match:
357
+ Rq_h = K.poly_scores(self.t, f, use_f, k, h, kern, Pq, res_b)
358
+ return meat_cl, self.cluster_meat(Rq_h, k, Pq)
359
+ return meat_cl, self.cluster_meat(Q * res_b[:, None], k, Pq)
360
+
361
+
362
+ def gram(mom, o):
363
+ idx = np.add.outer(np.arange(o + 1), np.arange(o + 1))
364
+ return mom[idx]
365
+
366
+
367
+ def inv_chol(G):
368
+ L = np.linalg.cholesky(G)
369
+ Li = np.linalg.inv(L)
370
+ return Li.T @ Li
371
+
372
+
373
+ def inv_chol_or_pinv(G):
374
+ try:
375
+ return inv_chol(G)
376
+ except np.linalg.LinAlgError:
377
+ return np.linalg.pinv(G)
378
+
379
+
380
+ def partial_z(U, Gi, ZWD, dT):
381
+ """ZWZ and ZWY of the covariate adjustment: the covariates' cross-products
382
+ after partialling out the local polynomial."""
383
+ colsZ = np.arange(1 + dT, U.shape[1])
384
+ UiGU = U[:, colsZ].T @ Gi @ U
385
+ return ZWD[:, colsZ] - UiGU[:, colsZ], ZWD[:, :1 + dT] - UiGU[:, :1 + dT]
386
+
387
+
388
+ def combination(beta_row, gamma, dT, scale_y=1.0, fac=1.0):
389
+ """rdrobust's s: the weights on the response columns [y, (take-up),
390
+ covariates] whose variance is the estimate's, with the jumps tau_Y,
391
+ tau_T they imply. `beta_row` is a row of coefficients (or of jumps) over
392
+ the columns; `gamma` the covariate coefficients (dZ x (1 + dT))."""
393
+ dZ = gamma.shape[0]
394
+ cz = slice(1 + dT, 1 + dT + dZ)
395
+ tau_Y = scale_y * fac * (beta_row[0] - gamma[:, 0] @ beta_row[cz])
396
+ if dT == 0:
397
+ return np.concatenate([[1.0], -gamma[:, 0]]), tau_Y, None
398
+ tau_T = fac * (beta_row[1] - gamma[:, 1] @ beta_row[cz])
399
+ s = np.concatenate([[1 / tau_T, -(tau_Y / tau_T ** 2)],
400
+ -(1 / tau_T) * gamma[:, 0] + (tau_Y / tau_T ** 2) * gamma[:, 1]])
401
+ return s, tau_Y, tau_T
402
+
403
+
404
+ # ---------------------------------------------------------------------------
405
+ # rdbwselect
406
+
407
+ class _BandwidthSide:
408
+ """rdrobust_bw on one (standardized) side, with the pilot fits at c_bw
409
+ computed once per (order, derivative). With a take-up column (fuzzy),
410
+ the variances are of the delta-method combination D s."""
411
+
412
+ def __init__(self, s, c_bw, kern, vce, matches):
413
+ self.s, self.c_bw, self.kern, self.vce, self.matches = s, c_bw, kern, vce, matches
414
+ self.kV = s.window(c_bw, kern)
415
+ self._vcache = {}
416
+
417
+ def _pilot(self, o, nu):
418
+ key = (o, nu)
419
+ if key in self._vcache:
420
+ return self._vcache[key]
421
+ s, h, k, kern = self.s, self.c_bw, self.kV, self.kern
422
+ if s.distinct_in(k) < o + 1:
423
+ out = (math.nan, math.nan, np.ones(1))
424
+ else:
425
+ mw = s.moments_w(k, h, kern, 2 * o + 1)
426
+ Gi = inv_chol_or_pinv(gram(mw, o))
427
+ U = s.moments_D(k, h, kern, o) # (o + 1) x columns
428
+ beta = Gi @ U
429
+ gamma = np.zeros((0, 1 + s.dT))
430
+ if s.dZ:
431
+ ZWZ, ZWY = partial_z(U, Gi, s.zwd(k, h, kern), s.dT)
432
+ gamma = np.linalg.pinv(ZWZ) @ ZWY
433
+ svec = combination(beta[nu], gamma, s.dT, fac=math.factorial(nu))[0]
434
+ if s.dT == 0 and s.dZ == 0:
435
+ svec = np.ones(1)
436
+ meat = s.residual_meat(svec, k, h, kern, o + 1, self.vce, self.matches,
437
+ beta @ svec, Gi, o + 1)
438
+ V_V = (Gi @ meat @ Gi)[nu, nu]
439
+ v = mw[o + 1:2 * o + 2] / h ** (o + 1)
440
+ Hp = h ** np.arange(o + 1)
441
+ out = (V_V, (Hp * (Gi @ v))[nu], svec)
442
+ self._vcache[key] = out
443
+ return out
444
+
445
+ def bw(self, o, nu, o_B, h_B, scale):
446
+ nan_out = (math.nan, math.nan, math.nan, 1 / (2 * o + 3))
447
+ V_V, BConst, svec = self._pilot(o, nu)
448
+ if not math.isfinite(V_V) or not (math.isfinite(h_B) and h_B > 0):
449
+ return nan_out
450
+ s, kern = self.s, self.kern
451
+ if scale == 0 and s.covers_side(h_B) and (s.prefer_full or
452
+ h_B > s.radius * _RADIUS_MARGIN):
453
+ # the whole side, beyond the rows held: from its power sums
454
+ if s.M_side < o_B + 1:
455
+ return nan_out
456
+ Gi = inv_chol_or_pinv(gram(s.full.moments_w(h_B, kern, 2 * o_B), o_B))
457
+ beta = Gi @ s.full.moments_D(h_B, kern, o_B)
458
+ else:
459
+ kB = s.window(h_B, kern)
460
+ if s.distinct_in(kB) < o_B + 1:
461
+ return nan_out
462
+ Gi = inv_chol_or_pinv(gram(s.moments_w(kB, h_B, kern, 2 * o_B), o_B))
463
+ beta = Gi @ s.moments_D(kB, h_B, kern, o_B)
464
+ BWreg = 0.0
465
+ if scale > 0:
466
+ meat = s.residual_meat(svec, kB, h_B, kern, o_B + 1, self.vce, self.matches,
467
+ beta @ svec, Gi, o_B + 1)
468
+ V_B = (Gi @ meat @ Gi)[o + 1, o + 1]
469
+ BWreg = 3 * BConst ** 2 * V_B
470
+ B = math.sqrt(2 * (o + 1 - nu)) * BConst * float(beta[o + 1] @ svec) # R: beta_B[o + 2, ]
471
+ V = (2 * nu + 1) * self.c_bw ** (2 * nu + 1) * V_V
472
+ R = scale * (2 * (o + 1 - nu)) * BWreg
473
+ return V, B, R, 1 / (2 * o + 3)
474
+
475
+
476
+ @dataclass
477
+ class Bandwidths:
478
+ """Main (h) and bias (b) bandwidths on each side, by selector."""
479
+ table: dict # selector -> (h_left, h_right, b_left, b_right)
480
+ selector: str
481
+
482
+ @property
483
+ def chosen(self):
484
+ return self.table[self.selector]
485
+
486
+
487
+ def quantile_type2_sorted(xs, prob):
488
+ n = xs.shape[0]
489
+ hq = n * prob
490
+ j = int(math.floor(hq))
491
+ if prob <= 0:
492
+ return xs[0]
493
+ if prob >= 1:
494
+ return xs[-1]
495
+ return 0.5 * (xs[j - 1] + xs[j]) if hq == j else xs[j]
496
+
497
+
498
+ def select_bandwidths(left, right, stats, *, p, q, deriv, kern, vce, matches, scaleregul,
499
+ masspoints, bwcheck, bwrestrict, stdvars, selector="mserd", all_=False):
500
+ """rdbwselect. `stats` has the full sample's x_sd, y_sd, x_iq, x_min,
501
+ x_max and N (and the cluster counts); returns `Bandwidths`."""
502
+ c = left.c
503
+ x_sd = stats["x_sd"] if stdvars else 1.0
504
+ y_sd = stats["y_sd"] if stdvars else 1.0
505
+ BWp = min(stats["x_sd"], stats["x_iq"] / 1.349)
506
+ if stdvars:
507
+ BWp = min(1.0, (stats["x_iq"] / x_sd) / 1.349)
508
+ sl = left.scaled(x_sd, y_sd) if stdvars else left
509
+ sr = right.scaled(x_sd, y_sd) if stdvars else right
510
+ cs = c / x_sd
511
+ x_min, x_max = stats["x_min"] / x_sd, stats["x_max"] / x_sd
512
+ range_l, range_r = abs(cs - x_min), abs(cs - x_max)
513
+ N = stats["N"]
514
+ M_l, M_r = left.M_side, right.M_side
515
+ if masspoints == "adjust" and bwcheck is None and stats["mass"]:
516
+ bwcheck = 10
517
+ M = M_l + M_r if masspoints in ("check", "adjust") else N
518
+ C_c = _C_C[kern]
519
+ c_bw = C_c * BWp * (M if masspoints == "adjust" else N) ** (-1 / 5)
520
+ bw_max_l, bw_max_r = abs(cs - x_min), abs(cs - x_max)
521
+ bw_max = max(bw_max_l, bw_max_r)
522
+ if bwrestrict:
523
+ c_bw = min(c_bw, bw_max)
524
+ bw_min_l = bw_min_r = None
525
+ if bwcheck is not None:
526
+ if min(bwcheck, M_l) > sl.M or min(bwcheck, M_r) > sr.M:
527
+ raise NeedWider() # fewer distinct values held than bwcheck
528
+ bw_min_l = sl.run_distance(min(bwcheck, M_l)) * (1 + SQRT_EPS)
529
+ bw_min_r = sr.run_distance(min(bwcheck, M_r)) * (1 + SQRT_EPS)
530
+ c_bw = max(c_bw, bw_min_l, bw_min_r)
531
+
532
+ bl = _BandwidthSide(sl, c_bw, kern, vce, matches)
533
+ br = _BandwidthSide(sr, c_bw, kern, vce, matches)
534
+ C_d_l = bl.bw(q + 1, q + 1, q + 2, range_l * (1 + SQRT_EPS), 0)
535
+ C_d_r = br.bw(q + 1, q + 1, q + 2, range_r * (1 + SQRT_EPS), 0)
536
+
537
+ def restrict(v, hi):
538
+ return min(v, hi) if bwrestrict else v
539
+
540
+ def floor(v, *lo):
541
+ return max(v, *lo) if bwcheck is not None else v
542
+
543
+ out = {}
544
+ need = set(SELECTORS) if all_ else {selector}
545
+ two = need & {"msetwo", "certwo", "msecomb2", "cercomb2"}
546
+ summ = need & {"msesum", "cersum", "msecomb1", "msecomb2", "cercomb1", "cercomb2"}
547
+ rd = need & {"mserd", "cerrd", "msecomb1", "msecomb2", "cercomb1", "cercomb2"}
548
+ if two:
549
+ d_l = floor(restrict((C_d_l[0] / C_d_l[1] ** 2) ** C_d_l[3], bw_max_l), bw_min_l or 0)
550
+ d_r = floor(restrict((C_d_r[0] / C_d_r[1] ** 2) ** C_d_r[3], bw_max_r), bw_min_r or 0)
551
+ C_b_l = bl.bw(q, p + 1, q + 1, d_l, scaleregul)
552
+ C_b_r = br.bw(q, p + 1, q + 1, d_r, scaleregul)
553
+ b_l = restrict((C_b_l[0] / (C_b_l[1] ** 2 + scaleregul * C_b_l[2])) ** C_b_l[3], bw_max_l)
554
+ b_r = restrict((C_b_r[0] / (C_b_r[1] ** 2 + scaleregul * C_b_r[2])) ** C_b_r[3], bw_max_r)
555
+ C_h_l = bl.bw(p, deriv, q, b_l, scaleregul)
556
+ C_h_r = br.bw(p, deriv, q, b_r, scaleregul)
557
+ h_l = restrict((C_h_l[0] / (C_h_l[1] ** 2 + scaleregul * C_h_l[2])) ** C_h_l[3], bw_max_l)
558
+ h_r = restrict((C_h_r[0] / (C_h_r[1] ** 2 + scaleregul * C_h_r[2])) ** C_h_r[3], bw_max_r)
559
+ out["msetwo"] = (x_sd * h_l, x_sd * h_r, x_sd * b_l, x_sd * b_r)
560
+ if summ:
561
+ d_s = ((C_d_l[0] + C_d_r[0]) / (C_d_r[1] + C_d_l[1]) ** 2) ** C_d_l[3]
562
+ d_s = restrict(d_s, bw_max)
563
+ if bwcheck is not None:
564
+ d_s = max(d_s, bw_min_l, bw_min_r)
565
+ C_b_l = bl.bw(q, p + 1, q + 1, d_s, scaleregul)
566
+ C_b_r = br.bw(q, p + 1, q + 1, d_s, scaleregul)
567
+ b_s = ((C_b_l[0] + C_b_r[0]) / ((C_b_r[1] + C_b_l[1]) ** 2
568
+ + scaleregul * (C_b_r[2] + C_b_l[2]))) ** C_b_l[3]
569
+ b_s = restrict(b_s, bw_max)
570
+ C_h_l = bl.bw(p, deriv, q, b_s, scaleregul)
571
+ C_h_r = br.bw(p, deriv, q, b_s, scaleregul)
572
+ h_s = ((C_h_l[0] + C_h_r[0]) / ((C_h_r[1] + C_h_l[1]) ** 2
573
+ + scaleregul * (C_h_r[2] + C_h_l[2]))) ** C_h_l[3]
574
+ h_s = restrict(h_s, bw_max)
575
+ out["msesum"] = (x_sd * h_s,) * 2 + (x_sd * b_s,) * 2
576
+ if rd:
577
+ d_d = ((C_d_l[0] + C_d_r[0]) / (C_d_r[1] - C_d_l[1]) ** 2) ** C_d_l[3]
578
+ d_d = restrict(d_d, bw_max)
579
+ if bwcheck is not None:
580
+ d_d = max(d_d, bw_min_l, bw_min_r)
581
+ C_b_l = bl.bw(q, p + 1, q + 1, d_d, scaleregul)
582
+ C_b_r = br.bw(q, p + 1, q + 1, d_d, scaleregul)
583
+ b_d = ((C_b_l[0] + C_b_r[0]) / ((C_b_r[1] - C_b_l[1]) ** 2
584
+ + scaleregul * (C_b_r[2] + C_b_l[2]))) ** C_b_l[3]
585
+ b_d = restrict(b_d, bw_max)
586
+ C_h_l = bl.bw(p, deriv, q, b_d, scaleregul)
587
+ C_h_r = br.bw(p, deriv, q, b_d, scaleregul)
588
+ h_d = ((C_h_l[0] + C_h_r[0]) / ((C_h_r[1] - C_h_l[1]) ** 2
589
+ + scaleregul * (C_h_r[2] + C_h_l[2]))) ** C_h_l[3]
590
+ h_d = restrict(h_d, bw_max)
591
+ out["mserd"] = (x_sd * h_d,) * 2 + (x_sd * b_d,) * 2
592
+ if need & {"msecomb1", "cercomb1"}:
593
+ h1 = min(out["mserd"][0], out["msesum"][0])
594
+ b1 = min(out["mserd"][2], out["msesum"][2])
595
+ out["msecomb1"] = (h1, h1, b1, b1)
596
+ if need & {"msecomb2", "cercomb2"}:
597
+ med = lambda *v: float(np.median(np.array(v)))
598
+ out["msecomb2"] = (med(out["mserd"][0], out["msesum"][0], out["msetwo"][0]),
599
+ med(out["mserd"][1], out["msesum"][1], out["msetwo"][1]),
600
+ med(out["mserd"][2], out["msesum"][2], out["msetwo"][2]),
601
+ med(out["mserd"][3], out["msesum"][3], out["msetwo"][3]))
602
+ cer_n = stats["G_l"] + stats["G_r"] if stats.get("clustered") else N
603
+ cer_h = cer_n ** (-(p / ((3 + p) * (3 + 2 * p))))
604
+ for cer, mse in (("cerrd", "mserd"), ("certwo", "msetwo"), ("cersum", "msesum"),
605
+ ("cercomb1", "msecomb1"), ("cercomb2", "msecomb2")):
606
+ if cer in need:
607
+ v = out[mse]
608
+ out[cer] = (v[0] * cer_h, v[1] * cer_h, v[2], v[3])
609
+ table = {k: out[k] for k in SELECTORS if k in out and k in need}
610
+ for v in table.values():
611
+ if not all(math.isfinite(b) and b > 0 for b in v):
612
+ raise ValueError("a pilot bandwidth fit is not identified (too few distinct values "
613
+ "of the running variable near the cutoff); give the bandwidth "
614
+ "with bandwidth=")
615
+ return Bandwidths(table, selector)
616
+
617
+
618
+ # ---------------------------------------------------------------------------
619
+ # rdrobust's estimate at given bandwidths
620
+
621
+ @dataclass
622
+ class SideFit:
623
+ """One side's fit at bandwidths h and b: coefficients for every response
624
+ column, and what the variances need."""
625
+ beta_p: np.ndarray # (p + 1) x columns
626
+ beta_q: np.ndarray # (q + 1) x columns
627
+ beta_bc: np.ndarray # (p + 1) x columns
628
+ n_h: int
629
+ n_b: int
630
+ k: int # units within max(h, b)
631
+ kh: int
632
+ kb: int
633
+ h: float
634
+ b: float
635
+ L: np.ndarray # sum w_h t^(p+1+j) / h^(p+1), j = 0..p
636
+ g: np.ndarray # row p + 1 of Gq_inv
637
+ Gp_inv: np.ndarray
638
+ Gq_inv: np.ndarray
639
+ U_p: np.ndarray # sum w_h r_p d' over the columns
640
+ n_h_units: int
641
+
642
+
643
+ def fit_side(s, h, b, *, p, q, kern, grid=None):
644
+ """One side's local-polynomial coefficients at bandwidths h, b, from the
645
+ window moments (rdrobust's Q_q enters through Q'D = U_p - h^(p+1) L g'M_b).
646
+ `grid`: a GridSide whose tables cover the window, or None for direct sums."""
647
+ kh, kb = s.window(h, kern), s.window(b, kern)
648
+ k = max(kh, kb)
649
+ src = grid if grid is not None and k <= grid.extent else s
650
+ Gq_inv = inv_chol(gram(src.moments_w(kb, b, kern, 2 * q), q))
651
+ mp = src.moments_w(kh, h, kern, 3 * p + 1)
652
+ Gp_inv = inv_chol(gram(mp, p))
653
+ L = mp[p + 1:2 * p + 2] / h ** (p + 1)
654
+ g = np.ascontiguousarray(Gq_inv[p + 1, :])
655
+ U_p = src.moments_D(kh, h, kern, p)
656
+ M_b = src.moments_D(kb, b, kern, q)
657
+ beta_p = Gp_inv @ U_p
658
+ beta_q = Gq_inv @ M_b
659
+ beta_bc = Gp_inv @ (U_p - h ** (p + 1) * np.outer(L, g @ M_b))
660
+ return SideFit(beta_p, beta_q, beta_bc, s.nobs_in(kh), s.nobs_in(kb), k, kh, kb, h, b,
661
+ L, g, Gp_inv, Gq_inv, U_p, kh)
662
+
663
+
664
+ def _sq(coef):
665
+ return np.convolve(coef, coef)
666
+
667
+
668
+ def side_variances(s, fit, svec, *, p, q, kern, vce, matches, hb_match, grid=None):
669
+ """Conventional and robust variance matrices of one side's coefficients
670
+ for the combined response D s.
671
+
672
+ Without clusters, both are sums over the window:
673
+ V_cl = Gp_inv (sum w_h^2 r r' e^2) Gp_inv and, with rdrobust's
674
+ Q_i = w_h r_i - h^(p+1) w_b (g' r_q,i) L,
675
+ Q' diag(e^2) Q = sum w_h^2 r r' e^2 - h^(p+1) (v L' + L v') + h^(2p+2) c L L',
676
+ v = sum w_h w_b (g' r_q) r e^2 and c = sum w_b^2 (g' r_q)^2 e^2."""
677
+ k, kh, kb, h, b = fit.k, fit.kh, fit.kb, fit.h, fit.b
678
+ P, Pq = p + 1, q + 1
679
+ Gp_inv, Gq_inv = fit.Gp_inv, fit.Gq_inv
680
+ if not s.clustered:
681
+ hp1 = h ** (p + 1)
682
+ edge = None
683
+ if grid is not None and vce == "nn" and k <= grid.extent:
684
+ edge = grid.residuals_at(k)
685
+ if edge is not None:
686
+ kp_h, kp_b = kernel_poly(kern, h, grid.D), kernel_poly(kern, b, grid.D)
687
+ mh = grid.ss_moments(edge, svec, kh, _sq(kp_h), 2 * p)
688
+ mx = grid.ss_moments(edge, svec, min(kh, kb), np.convolve(kp_h, kp_b), p + q)
689
+ mb = grid.ss_moments(edge, svec, kb, _sq(kp_b), 2 * q)
690
+ mh_b = mh
691
+ else:
692
+ mh, mh_b, mx, mb = s.variance_sums(svec, fit, p=p, q=q, kern=kern, vce=vce,
693
+ matches=matches)
694
+ V_cl = Gp_inv @ gram(mh, p) @ Gp_inv
695
+ g = fit.g
696
+ v = np.array([g @ mx[a:a + Pq] for a in range(P)])
697
+ c = g @ gram(mb, q) @ g
698
+ meat_rb = (gram(mh_b, p) - hp1 * (np.outer(v, fit.L) + np.outer(fit.L, v))
699
+ + hp1 * hp1 * c * np.outer(fit.L, fit.L))
700
+ V_rb = Gp_inv @ meat_rb @ Gp_inv
701
+ return V_cl, V_rb
702
+ meat_cl, meat_rb = s.cluster_meats(svec, fit, p=p, q=q, kern=kern, vce=vce,
703
+ matches=matches, hb_match=hb_match)
704
+ V_cl = Gp_inv @ meat_cl @ Gp_inv
705
+ if hb_match:
706
+ V_rb = (Gq_inv @ meat_rb @ Gq_inv)[:P, :P]
707
+ else:
708
+ V_rb = Gp_inv @ meat_rb @ Gp_inv
709
+ return V_cl, V_rb
710
+
711
+
712
+ def estimate(left, right, h_l, h_r, b_l, b_r, *, p, q, deriv, kern, vce, matches,
713
+ scalepar=1.0, grids=(None, None)):
714
+ """Conventional and bias-corrected estimates with their conventional and
715
+ robust standard errors. With a take-up column (fuzzy), the local Wald
716
+ ratio and the first stage; with covariates, the adjustment of Calonico,
717
+ Cattaneo, Farrell and Titiunik (2019), gamma from both sides at h."""
718
+ hb_match = h_l == b_l and h_r == b_r
719
+ gl, gr = grids
720
+ L = fit_side(left, h_l, b_l, p=p, q=q, kern=kern, grid=gl)
721
+ R = fit_side(right, h_r, b_r, p=p, q=q, kern=kern, grid=gr)
722
+ dT, dZ = left.dT, left.dZ
723
+ fac = math.factorial(deriv)
724
+ gamma = np.zeros((0, 1 + dT))
725
+ if dZ:
726
+ Z_l = partial_z(L.U_p, L.Gp_inv, left.zwd(L.n_h_units, h_l, kern), dT)
727
+ Z_r = partial_z(R.U_p, R.Gp_inv, right.zwd(R.n_h_units, h_r, kern), dT)
728
+ gamma = np.linalg.pinv(Z_l[0] + Z_r[0]) @ (Z_l[1] + Z_r[1])
729
+ jump_p = R.beta_p[deriv] - L.beta_p[deriv]
730
+ jump_bc = R.beta_bc[deriv] - L.beta_bc[deriv]
731
+ s_cl, tau_Y_cl, tau_T_cl = combination(jump_p, gamma, dT, scalepar, fac)
732
+ _, tau_Y_bc, tau_T_bc = combination(jump_bc, gamma, dT, scalepar, fac)
733
+ out = dict(side_l=L, side_r=R, fuzzy=dT == 1, gamma=gamma)
734
+ kw = dict(p=p, q=q, kern=kern, vce=vce, matches=matches, hb_match=hb_match)
735
+ if dT == 0:
736
+ svec = s_cl if dZ else np.ones(1)
737
+ tau_cl, tau_bc = tau_Y_cl, tau_Y_bc
738
+ else:
739
+ tau_cl = tau_Y_cl / tau_T_cl
740
+ s2 = np.array([1 / tau_T_cl, -(tau_Y_cl / tau_T_cl ** 2)])
741
+ tau_bc = tau_cl - float(s2 @ np.array([tau_Y_cl - tau_Y_bc, tau_T_cl - tau_T_bc]))
742
+ svec = s_cl
743
+ sV_T = np.concatenate([[0.0, 1.0], -gamma[:, 1]])
744
+ VT_l = side_variances(left, L, sV_T, grid=gl, **kw)
745
+ VT_r = side_variances(right, R, sV_T, grid=gr, **kw)
746
+ out["first_stage"] = dict(
747
+ tau_cl=tau_T_cl, tau_bc=tau_T_bc,
748
+ se_cl=fac * math.sqrt((VT_l[0] + VT_r[0])[deriv, deriv]),
749
+ se_rb=fac * math.sqrt((VT_l[1] + VT_r[1])[deriv, deriv]))
750
+ V_l = side_variances(left, L, svec, grid=gl, **kw)
751
+ V_r = side_variances(right, R, svec, grid=gr, **kw)
752
+ V_cl = scalepar ** 2 * fac ** 2 * (V_l[0] + V_r[0])[deriv, deriv]
753
+ V_rb = scalepar ** 2 * fac ** 2 * (V_l[1] + V_r[1])[deriv, deriv]
754
+ out.update(tau_cl=tau_cl, tau_bc=tau_bc, se_cl=math.sqrt(V_cl), se_rb=math.sqrt(V_rb))
755
+ return out