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/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """Regression discontinuity on large data.
2
+
3
+ rdrobust's local-polynomial estimates, bandwidth selectors and robust
4
+ bias-corrected inference, and rdplot's binned means, from one sort of the
5
+ running variable (or one grouping by its values) and compiled, threaded
6
+ passes over each bandwidth's observations.
7
+ """
8
+
9
+ # first, before polars is imported: a scheduler's or container's thread and
10
+ # memory limits, which set Polars' out-of-core budget (read when it is imported)
11
+ import stream_limits as _limits
12
+
13
+ _limits.apply_scheduler_defaults()
14
+ # No OpenMP wait policy is set: the bandwidth steps' parallel passes follow one
15
+ # another closely, and run 2-5 times slower when idle threads sleep (passive).
16
+
17
+ from .api import BandwidthResult, rd_bandwidth, rd_estimate # noqa: E402
18
+ from .placebo import PlaceboResult, rd_placebo # noqa: E402
19
+ from .plot import RDPlot, RDPlotMulti, rd_plot # noqa: E402
20
+ from .results import RDMulti, RDResult, etable # noqa: E402
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ __all__ = ["BandwidthResult", "PlaceboResult", "RDMulti", "RDPlot", "RDPlotMulti", "RDResult",
25
+ "etable", "rd_bandwidth", "rd_estimate", "rd_placebo", "rd_plot"]
rd_stream/_cluster.py ADDED
@@ -0,0 +1,333 @@
1
+ """rdrobust's CRV2 and CRV3 cluster-robust variances (rdrobust_vce and
2
+ .rdrobust_vce_qq_cluster in R's rdrobust 4.1.1), from per-cluster sums.
3
+
4
+ Both adjust each cluster's score before the outer products are summed, with
5
+ no small-sample factor:
6
+
7
+ - CRV3 (the jackknife-like correction): score_g = u_g + L_g (G - L_g)^-1 u_g,
8
+ G the window's Gram matrix.
9
+ - CRV2 (Bell and McCaffrey's bias-reduced linearization): the same idea with
10
+ (I - H_gg)^(-1/2), from the eigendecomposition of C L_g C', C the upper
11
+ Cholesky factor of G^-1.
12
+
13
+ L_g and u_g (and, for the robust variance with h != b, P_g, uQ_g and uq_g)
14
+ come from one compiled pass over the window (_kernels.cluster_sums*). The
15
+ small matrix work runs here, compiled and in parallel over clusters: each
16
+ cluster's symmetric eigendecomposition (2 x 2 to about 6 x 6) by cyclic
17
+ Jacobi rotations, which are exact to rounding at these sizes, and each chunk
18
+ of clusters adds its scores' outer products into a P x P total of its own.
19
+ Every score is linear in the residuals, so a fuzzy or covariate-adjusted fit
20
+ uses the residuals of the combined response, as rdrobust's sum over its
21
+ columns does.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import numpy as np
27
+ from numba import njit, prange
28
+
29
+ EPS = np.finfo(float).eps
30
+ _SQRT_EPS = np.sqrt(EPS)
31
+
32
+
33
+ @njit(cache=True)
34
+ def _eigh(A):
35
+ """Eigenvalues and eigenvectors (columns) of a small symmetric matrix:
36
+ cyclic Jacobi rotations until the off-diagonal part is negligible."""
37
+ n = A.shape[0]
38
+ a = A.copy()
39
+ V = np.eye(n)
40
+ for _ in range(100):
41
+ off = 0.0
42
+ tot = 0.0
43
+ for p in range(n):
44
+ tot += a[p, p] * a[p, p]
45
+ for q in range(p + 1, n):
46
+ off += a[p, q] * a[p, q]
47
+ tot += 2.0 * off
48
+ if off == 0.0 or off <= 1e-36 * tot:
49
+ break
50
+ for p in range(n - 1):
51
+ for q in range(p + 1, n):
52
+ apq = a[p, q]
53
+ if apq == 0.0:
54
+ continue
55
+ theta = (a[q, q] - a[p, p]) / (2.0 * apq)
56
+ t = 1.0 / (abs(theta) + np.sqrt(theta * theta + 1.0))
57
+ if theta < 0.0:
58
+ t = -t
59
+ c = 1.0 / np.sqrt(t * t + 1.0)
60
+ s = t * c
61
+ for k in range(n):
62
+ akp = a[k, p]
63
+ akq = a[k, q]
64
+ a[k, p] = c * akp - s * akq
65
+ a[k, q] = s * akp + c * akq
66
+ for k in range(n):
67
+ apk = a[p, k]
68
+ aqk = a[q, k]
69
+ a[p, k] = c * apk - s * aqk
70
+ a[q, k] = s * apk + c * aqk
71
+ a[p, q] = 0.0
72
+ a[q, p] = 0.0
73
+ for k in range(n):
74
+ vkp = V[k, p]
75
+ vkq = V[k, q]
76
+ V[k, p] = c * vkp - s * vkq
77
+ V[k, q] = s * vkp + c * vkq
78
+ lam = np.empty(n)
79
+ for i in range(n):
80
+ lam[i] = a[i, i]
81
+ return lam, V
82
+
83
+
84
+ @njit(cache=True)
85
+ def _inverse_or(A, ginv):
86
+ """The inverse of a symmetric matrix, as R's solve(); when numerically
87
+ singular, its generalized inverse (MASS::ginv's tolerance, `ginv`) or
88
+ zeros."""
89
+ n = A.shape[0]
90
+ lam, V = _eigh(A)
91
+ amax = 0.0
92
+ amin = np.inf
93
+ for i in range(n):
94
+ a = abs(lam[i])
95
+ amax = max(amax, a)
96
+ amin = min(amin, a)
97
+ singular = amin <= EPS * amax
98
+ inv = np.zeros(n)
99
+ for i in range(n):
100
+ a = abs(lam[i])
101
+ if a > 0.0:
102
+ inv[i] = 1.0 / lam[i]
103
+ if singular and (not ginv or a <= _SQRT_EPS * amax):
104
+ inv[i] = 0.0
105
+ out = np.zeros((n, n))
106
+ for i in range(n):
107
+ for j in range(n):
108
+ s = 0.0
109
+ for m in range(n):
110
+ s += V[i, m] * inv[m] * V[j, m]
111
+ out[i, j] = s
112
+ return out
113
+
114
+
115
+ @njit(cache=True, inline="always")
116
+ def _mv(A, x, out):
117
+ """out = A x, in loops (BLAS calls cost more than the work at these sizes)."""
118
+ for i in range(A.shape[0]):
119
+ acc = 0.0
120
+ for j in range(A.shape[1]):
121
+ acc += A[i, j] * x[j]
122
+ out[i] = acc
123
+
124
+
125
+ @njit(cache=True, inline="always")
126
+ def _mtv(A, x, out):
127
+ """out = A' x."""
128
+ for i in range(A.shape[1]):
129
+ acc = 0.0
130
+ for j in range(A.shape[0]):
131
+ acc += A[j, i] * x[j]
132
+ out[i] = acc
133
+
134
+
135
+ @njit(cache=True, inline="always")
136
+ def _sandwich(A, B, out):
137
+ """out = A B A' (B symmetric), symmetrized."""
138
+ n, m = A.shape
139
+ for i in range(n):
140
+ for j in range(i, n):
141
+ acc = 0.0
142
+ for a in range(m):
143
+ ra = 0.0
144
+ for b in range(m):
145
+ ra += B[a, b] * A[j, b]
146
+ acc += A[i, a] * ra
147
+ out[i, j] = acc
148
+ out[j, i] = acc
149
+
150
+
151
+ @njit(cache=True)
152
+ def _chunks(n):
153
+ nchunk = max(1, min(256, n // 256))
154
+ return nchunk, (n + nchunk - 1) // nchunk if n else 0
155
+
156
+
157
+ @njit(cache=True)
158
+ def _add_outer(M, s):
159
+ P = s.shape[0]
160
+ for i in range(P):
161
+ for j in range(P):
162
+ M[i, j] += s[i] * s[j]
163
+
164
+
165
+ @njit(parallel=True, cache=True)
166
+ def _meat3(L, u, idx, G):
167
+ """CRV3: sum_g score_g score_g', score_g = u_g + L_g (G - L_g)^+ u_g."""
168
+ P = u.shape[1]
169
+ nchunk, step = _chunks(idx.shape[0])
170
+ part = np.zeros((nchunk, P, P))
171
+ for c in prange(nchunk):
172
+ s = np.empty(P)
173
+ mu = np.empty(P)
174
+ for ii in range(c * step, min(idx.shape[0], (c + 1) * step)):
175
+ g = idx[ii]
176
+ _mv(_inverse_or(G - L[g], True), u[g], mu)
177
+ for i in range(P):
178
+ acc = u[g, i]
179
+ for j in range(P):
180
+ acc += L[g, i, j] * mu[j]
181
+ s[i] = acc
182
+ _add_outer(part[c], s)
183
+ return part.sum(axis=0)
184
+
185
+
186
+ @njit(parallel=True, cache=True)
187
+ def _meat2(L, u, idx, C):
188
+ """CRV2: score_g = u_g + L_g C' V (coef * V' C u_g), V and coef from the
189
+ eigendecomposition of C L_g C'."""
190
+ P = u.shape[1]
191
+ nchunk, step = _chunks(idx.shape[0])
192
+ part = np.zeros((nchunk, P, P))
193
+ for c in prange(nchunk):
194
+ s = np.empty(P)
195
+ F = np.empty((P, P))
196
+ coef = np.empty(P)
197
+ a1 = np.empty(P)
198
+ a2 = np.empty(P)
199
+ w = np.empty(P)
200
+ for ii in range(c * step, min(idx.shape[0], (c + 1) * step)):
201
+ g = idx[ii]
202
+ _sandwich(C, L[g], F)
203
+ lam, V = _eigh(F)
204
+ for i in range(P):
205
+ s2 = max(lam[i], 0.0)
206
+ coef[i] = 0.0 if s2 < 1e-14 else (1.0 / np.sqrt(max(1.0 - s2, 1e-8)) - 1.0) / s2
207
+ _mv(C, u[g], a1) # C u
208
+ _mtv(V, a1, a2) # V' C u
209
+ for i in range(P):
210
+ a2[i] *= coef[i]
211
+ _mv(V, a2, a1) # adj
212
+ _mtv(C, a1, w) # C' adj
213
+ for i in range(P):
214
+ acc = u[g, i]
215
+ for j in range(P):
216
+ acc += L[g, i, j] * w[j]
217
+ s[i] = acc
218
+ _add_outer(part[c], s)
219
+ return part.sum(axis=0)
220
+
221
+
222
+ @njit(parallel=True, cache=True)
223
+ def _meat_qq3(L, Pg, uQ, uq, idx, G):
224
+ """CRV3 with h != b: score_g = uQ_g + P_g (G - L_g)^-1 uq_g (zero where
225
+ G - L_g is singular)."""
226
+ P = uQ.shape[1]
227
+ nchunk, step = _chunks(idx.shape[0])
228
+ part = np.zeros((nchunk, P, P))
229
+ for c in prange(nchunk):
230
+ s = np.empty(P)
231
+ adj = np.empty(uq.shape[1])
232
+ for ii in range(c * step, min(idx.shape[0], (c + 1) * step)):
233
+ g = idx[ii]
234
+ _mv(_inverse_or(G - L[g], False), uq[g], adj)
235
+ _mv(Pg[g], adj, s)
236
+ for i in range(P):
237
+ s[i] += uQ[g, i]
238
+ _add_outer(part[c], s)
239
+ return part.sum(axis=0)
240
+
241
+
242
+ @njit(parallel=True, cache=True)
243
+ def _meat_qq2(L, Pg, uQ, uq, idx, Ginv_q):
244
+ """CRV2 with h != b (.rdrobust_vce_qq_cluster)."""
245
+ P = uQ.shape[1]
246
+ Pq = uq.shape[1]
247
+ nchunk, step = _chunks(idx.shape[0])
248
+ part = np.zeros((nchunk, P, P))
249
+ for c in prange(nchunk):
250
+ s = np.empty(P)
251
+ T = np.empty((Pq, Pq))
252
+ a1 = np.empty(Pq)
253
+ adj = np.empty(Pq)
254
+ for ii in range(c * step, min(idx.shape[0], (c + 1) * step)):
255
+ g = idx[ii]
256
+ vals, V = _eigh(L[g])
257
+ sig = np.empty(Pq)
258
+ smax = 0.0
259
+ for i in range(Pq):
260
+ sig[i] = np.sqrt(max(vals[i], 0.0))
261
+ smax = max(smax, sig[i])
262
+ any_keep = False
263
+ sig0 = np.zeros(Pq)
264
+ dinv = np.zeros(Pq)
265
+ for i in range(Pq):
266
+ if sig[i] > smax * 1e-10:
267
+ any_keep = True
268
+ sig0[i] = sig[i]
269
+ dinv[i] = 1.0 / sig[i]
270
+ if not any_keep:
271
+ for i in range(P):
272
+ s[i] = uQ[g, i]
273
+ _add_outer(part[c], s)
274
+ continue
275
+ Vt = np.ascontiguousarray(V.T)
276
+ _sandwich(Vt, Ginv_q, T)
277
+ for i in range(Pq):
278
+ for j in range(Pq):
279
+ T[i, j] *= sig0[i] * sig0[j]
280
+ tau, W = _eigh(T)
281
+ gamma = np.empty(Pq)
282
+ for i in range(Pq):
283
+ tt = min(max(tau[i], 0.0), 1.0 - 1e-10)
284
+ gamma[i] = 1.0 / np.sqrt(1.0 - tt) - 1.0
285
+ A = np.empty((Pq, Pq))
286
+ for i in range(Pq):
287
+ for j in range(Pq):
288
+ acc = 0.0
289
+ for m in range(Pq):
290
+ acc += V[i, m] * dinv[m] * W[m, j]
291
+ A[i, j] = acc
292
+ _mtv(A, uq[g], a1)
293
+ for i in range(Pq):
294
+ a1[i] *= gamma[i]
295
+ _mv(A, a1, adj)
296
+ _mv(Pg[g], adj, s)
297
+ for i in range(P):
298
+ s[i] += uQ[g, i]
299
+ _add_outer(part[c], s)
300
+ return part.sum(axis=0)
301
+
302
+
303
+ def meat(L, u, seen, Ginv, mode):
304
+ """sum_g score_g score_g' for the conventional variance (and the robust
305
+ one with h = b, and the bandwidth steps): mode 2 (CRV2) or 3 (CRV3)."""
306
+ idx = np.flatnonzero(seen)
307
+ L, u = np.ascontiguousarray(L), np.ascontiguousarray(u)
308
+ if mode == 3:
309
+ try:
310
+ G = np.linalg.inv(Ginv)
311
+ except np.linalg.LinAlgError:
312
+ G = np.linalg.pinv(Ginv)
313
+ return _meat3(L, u, idx, np.ascontiguousarray(G))
314
+ try:
315
+ C = np.linalg.cholesky(Ginv).T # R's chol(): upper, C'C = Ginv
316
+ except np.linalg.LinAlgError:
317
+ uu = u[idx]
318
+ return uu.T @ uu
319
+ return _meat2(L, u, idx, np.ascontiguousarray(C))
320
+
321
+
322
+ def meat_qq(L, Pg, uQ, uq, seen, Ginv_q, mode):
323
+ """sum_g score_g score_g' for the robust variance with h != b
324
+ (.rdrobust_vce_qq_cluster): mode 2 (CRV2) or 3 (CRV3)."""
325
+ idx = np.flatnonzero(seen)
326
+ args = [np.ascontiguousarray(a) for a in (L, Pg, uQ, uq)]
327
+ if mode == 3:
328
+ try:
329
+ G = np.linalg.inv(Ginv_q)
330
+ except np.linalg.LinAlgError:
331
+ G = np.linalg.pinv(Ginv_q)
332
+ return _meat_qq3(*args, idx, np.ascontiguousarray(G))
333
+ return _meat_qq2(*args, idx, np.ascontiguousarray(Ginv_q))