Skip to content
Navigation Menu
{{ message }}
forked from igerber/diff-diff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_had.py
More file actions
5611 lines (5069 loc) · 239 KB
/
Copy pathtest_had.py
File metadata and controls
5611 lines (5069 loc) · 239 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for :class:`diff_diff.had.HeterogeneousAdoptionDiD` (Phase 2a).
Covers the 12 plan commit criteria:
1. All three design paths produce a finite result on synthetic DGPs.
2. ``design="auto"`` resolves correctly on each DGP + two edge cases.
3. Beta-scale WAS estimator at atol=1e-14:
- Design 1' / continuous_at_zero:
``att = (mean(ΔY) - tau_bc) / mean(D)``
- Design 1 / continuous_near_d_lower:
``att = (mean(ΔY) - tau_bc) / mean(D - d_lower)``
- CI endpoints reverse under subtraction:
``CI_lower(att) = (mean(ΔY) - CI_upper_boundary) / den``
4. Mass-point Wald-IV point estimate matches manual formula at
``atol=1e-14``.
5. Mass-point 2SLS SE parity against hand-coded sandwich at
``atol=1e-12`` for HC1, classical, and CR1 (cluster-robust).
6. Mass-point + ``vcov_type in {hc2, hc2_bm}`` raises
``NotImplementedError``.
7. Panel-contract violations raise targeted ``ValueError``s.
8. NaN propagation: constant-y and mass-point degenerate inputs produce
all-NaN inference.
9. sklearn clone round-trip preserves raw ``design="auto"``; fit is
idempotent.
10. Scaffolding (``aggregate="event_study"``, ``survey``, ``weights``)
raises ``NotImplementedError`` with phase pointers.
11. ``get_params()`` keys match ``__init__`` signature.
12. REGISTRY ticks tested indirectly via parity with the paper rules.
"""
from __future__ import annotations
import inspect
import warnings
from typing import Any, cast
import numpy as np
import pandas as pd
import pytest
from diff_diff.had import (
HeterogeneousAdoptionDiD,
HeterogeneousAdoptionDiDEventStudyResults,
HeterogeneousAdoptionDiDResults,
_aggregate_first_difference,
_aggregate_multi_period_first_differences,
_detect_design,
_fit_mass_point_2sls,
_validate_had_panel,
_validate_had_panel_event_study,
)
from diff_diff.local_linear import bias_corrected_local_linear
from tests.conftest import assert_nan_inference
# =============================================================================
# DGP helpers
# =============================================================================
def _make_panel(d_post, delta_y, periods=(1, 2), extra_cols=None):
"""Build a balanced two-period panel with ``D_{g,1} = 0``.
Parameters
----------
d_post : np.ndarray, shape (G,)
Unit-level post-period dose ``D_{g,2}``.
delta_y : np.ndarray, shape (G,)
Unit-level first-difference outcome ``Y_{g,2} - Y_{g,1}``.
periods : tuple
(t_pre, t_post).
extra_cols : dict or None
Additional unit-constant columns (e.g., cluster variable).
"""
G = len(d_post)
t_pre, t_post = periods
units = np.arange(G)
df = pd.DataFrame(
{
"unit": np.repeat(units, 2),
"period": np.tile([t_pre, t_post], G),
"dose": np.column_stack([np.zeros(G), d_post]).ravel(),
# Set period-1 outcome to 0; period-2 outcome = delta_y so that
# Y_{g,2} - Y_{g,1} == delta_y exactly.
"outcome": np.column_stack([np.zeros(G), delta_y]).ravel(),
}
)
if extra_cols:
for col, vals in extra_cols.items():
df[col] = np.repeat(vals, 2)
return df
def _dgp_continuous_at_zero(G, seed):
"""Design 1' DGP: uniform dose on [0, 1] with exact zero in the sample."""
rng = np.random.default_rng(seed)
d = rng.uniform(0.0, 1.0, G)
d[0] = 0.0 # guarantee continuous_at_zero auto-detection
dy = 0.3 * d + 0.1 * rng.standard_normal(G)
return d, dy
def _dgp_continuous_near_d_lower(G, seed):
"""Design 1 continuous-near-d_lower DGP: Beta(2,2) shifted to [0.1, 1]."""
rng = np.random.default_rng(seed)
u = rng.beta(2, 2, G)
d = 0.1 + 0.9 * u
dy = 0.3 * d + 0.1 * rng.standard_normal(G)
return d, dy
def _dgp_mass_point(G, seed, d_lower=0.5, mass_frac=0.3, beta=0.3):
"""Mass-point DGP: ``mass_frac`` at d_lower, rest Uniform(d_lower, 1)."""
rng = np.random.default_rng(seed)
mass_n = int(mass_frac * G)
d = np.concatenate([np.full(mass_n, d_lower), rng.uniform(d_lower, 1.0, G - mass_n)])
dy = beta * d + 0.1 * rng.standard_normal(G)
return d, dy
# =============================================================================
# Criterion 1: Smoke tests - all 3 design paths produce finite output
# =============================================================================
class TestSmokeAllDesigns:
def test_continuous_at_zero_finite(self):
d, dy = _dgp_continuous_at_zero(500, seed=42)
r = HeterogeneousAdoptionDiD(design="continuous_at_zero").fit(
_make_panel(d, dy), "outcome", "dose", "period", "unit"
)
assert np.isfinite(r.att)
assert np.isfinite(r.se)
assert r.se > 0
def test_continuous_near_d_lower_finite(self):
d, dy = _dgp_continuous_near_d_lower(500, seed=42)
r = HeterogeneousAdoptionDiD(design="continuous_near_d_lower").fit(
_make_panel(d, dy), "outcome", "dose", "period", "unit"
)
assert np.isfinite(r.att)
assert np.isfinite(r.se)
assert r.se > 0
def test_mass_point_finite(self):
d, dy = _dgp_mass_point(500, seed=42)
r = HeterogeneousAdoptionDiD(design="mass_point").fit(
_make_panel(d, dy), "outcome", "dose", "period", "unit"
)
assert np.isfinite(r.att)
assert np.isfinite(r.se)
assert r.se > 0
def test_result_is_dataclass(self):
d, dy = _dgp_continuous_at_zero(400, seed=0)
r = HeterogeneousAdoptionDiD().fit(_make_panel(d, dy), "outcome", "dose", "period", "unit")
assert isinstance(r, HeterogeneousAdoptionDiDResults)
def test_continuous_populates_bandwidth_diagnostics(self):
d, dy = _dgp_continuous_at_zero(400, seed=0)
r = HeterogeneousAdoptionDiD().fit(_make_panel(d, dy), "outcome", "dose", "period", "unit")
assert r.bandwidth_diagnostics is not None
assert r.bias_corrected_fit is not None
def test_mass_point_nulls_bandwidth_diagnostics(self):
d, dy = _dgp_mass_point(400, seed=0)
r = HeterogeneousAdoptionDiD(design="mass_point").fit(
_make_panel(d, dy), "outcome", "dose", "period", "unit"
)
assert r.bandwidth_diagnostics is None
assert r.bias_corrected_fit is None
assert r.n_mass_point is not None
assert r.n_above_d_lower is not None
def test_continuous_nulls_mass_point_counts(self):
d, dy = _dgp_continuous_at_zero(400, seed=0)
r = HeterogeneousAdoptionDiD().fit(_make_panel(d, dy), "outcome", "dose", "period", "unit")
assert r.n_mass_point is None
assert r.n_above_d_lower is None
# =============================================================================
# Criterion 2: design="auto" detection rule
# =============================================================================
class TestDesignAutoDetect:
def test_detect_design_1_prime_exact_zero(self):
d, _ = _dgp_continuous_at_zero(500, seed=0)
assert _detect_design(d) == "continuous_at_zero"
def test_detect_design_continuous_near_d_lower(self):
d, _ = _dgp_continuous_near_d_lower(500, seed=0)
assert _detect_design(d) == "continuous_near_d_lower"
def test_detect_mass_point(self):
d, _ = _dgp_mass_point(500, seed=0)
assert _detect_design(d) == "mass_point"
def test_edge_small_mass_at_zero_resolves_continuous_at_zero(self):
"""Plan criterion 2 edge-case (a): 3% at D=0 + 97% Uniform(0.5, 1)."""
rng = np.random.default_rng(0)
G = 1000
mass_n = int(0.03 * G)
d = np.concatenate([np.zeros(mass_n), rng.uniform(0.5, 1.0, G - mass_n)])
assert _detect_design(d) == "continuous_at_zero"
def test_edge_shifted_beta_not_small_enough_for_design_1_prime(self):
"""Plan criterion 2 edge-case (b): d.min/median ~ 0.03 > 0.01 threshold."""
rng = np.random.default_rng(0)
u = rng.beta(2, 2, 1000)
d = 0.03 + u
assert _detect_design(d) == "continuous_near_d_lower"
def test_design_auto_dispatches_correctly_at_fit(self):
d, dy = _dgp_continuous_at_zero(500, seed=0)
r = HeterogeneousAdoptionDiD(design="auto").fit(
_make_panel(d, dy), "outcome", "dose", "period", "unit"
)
assert r.design == "continuous_at_zero"
def test_design_auto_mass_point_at_fit(self):
d, dy = _dgp_mass_point(500, seed=0)
r = HeterogeneousAdoptionDiD(design="auto").fit(
_make_panel(d, dy), "outcome", "dose", "period", "unit"
)
assert r.design == "mass_point"
def test_auto_does_not_mutate_self_design(self):
"""Plan decision #14: self.design preserves raw 'auto' after fit."""
d, dy = _dgp_continuous_at_zero(500, seed=0)
est = HeterogeneousAdoptionDiD(design="auto")
_ = est.fit(_make_panel(d, dy), "outcome", "dose", "period", "unit")
assert est.design == "auto"
assert est.get_params()["design"] == "auto"
# =============================================================================
# Criterion 3: Beta-scale rescaling parity
# =============================================================================
class TestBetaScaleRescaling:
"""Plan commit criterion #3 + review P0: the continuous estimator is
att = (mean(ΔY) - tau_bc) / den
with ``den = mean(D)`` for Design 1' and ``den = mean(D - d_lower)``
for Design 1 continuous-near-d_lower. SE is ``se_robust / |den|``.
CI endpoints are computed via ``att +/- z * se`` (endpoints reverse
relative to the boundary-limit CI because the numerator is
``ΔȲ - tau_bc``).
"""
def test_att_design_1_prime(self):
"""att = (mean(ΔY) - tau_bc) / D_bar for Design 1' at atol=1e-14."""
d, dy = _dgp_continuous_at_zero(500, seed=0)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="continuous_at_zero").fit(
panel, "outcome", "dose", "period", "unit"
)
bc = bias_corrected_local_linear(d=d, y=dy, boundary=0.0, alpha=0.05)
d_bar = float(d.mean())
dy_mean = float(dy.mean())
expected = (dy_mean - float(bc.estimate_bias_corrected)) / d_bar
assert abs(r.att - expected) < 1e-14
def test_se_design_1_prime(self):
"""se = se_robust / |D_bar| for Design 1' at atol=1e-14."""
d, dy = _dgp_continuous_at_zero(500, seed=0)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="continuous_at_zero").fit(
panel, "outcome", "dose", "period", "unit"
)
bc = bias_corrected_local_linear(d=d, y=dy, boundary=0.0, alpha=0.05)
expected = float(bc.se_robust) / abs(float(d.mean()))
assert abs(r.se - expected) < 1e-14
def test_ci_endpoints_reverse_under_subtraction(self):
"""Because att = (ΔȲ - tau_bc)/D_bar, CI endpoints reverse:
CI_lower(att) = (ΔȲ - CI_upper_boundary) / D_bar
CI_upper(att) = (ΔȲ - CI_lower_boundary) / D_bar
"""
d, dy = _dgp_continuous_at_zero(500, seed=0)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="continuous_at_zero").fit(
panel, "outcome", "dose", "period", "unit"
)
bc = bias_corrected_local_linear(d=d, y=dy, boundary=0.0, alpha=0.05)
d_bar = float(d.mean())
dy_mean = float(dy.mean())
# CI bounds on the att scale, computed by endpoint reversal from
# the boundary-limit CI.
expected_lower = (dy_mean - float(bc.ci_high)) / d_bar
expected_upper = (dy_mean - float(bc.ci_low)) / d_bar
assert abs(r.conf_int[0] - expected_lower) < 1e-14
assert abs(r.conf_int[1] - expected_upper) < 1e-14
def test_att_design_1_continuous_near_d_lower(self):
"""att = (mean(ΔY) - tau_bc) / mean(D - d_lower) for Design 1 at atol=1e-14."""
d, dy = _dgp_continuous_near_d_lower(500, seed=0)
panel = _make_panel(d, dy)
d_lower_val = float(d.min())
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
r = HeterogeneousAdoptionDiD(design="continuous_near_d_lower").fit(
panel, "outcome", "dose", "period", "unit"
)
d_reg = d - d_lower_val
bc = bias_corrected_local_linear(d=d_reg, y=dy, boundary=0.0, alpha=0.05)
den = float((d - d_lower_val).mean())
dy_mean = float(dy.mean())
expected = (dy_mean - float(bc.estimate_bias_corrected)) / den
assert abs(r.att - expected) < 1e-14
def test_att_recovers_true_beta_design_1_prime(self):
"""Sanity: on a known DGP with beta=0.3, att should be close to 0.3."""
rng = np.random.default_rng(0)
G = 2000
d = rng.uniform(0, 1, G)
d[0] = 0.0
dy = 0.3 * d + 0.05 * rng.standard_normal(G)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="continuous_at_zero").fit(
panel, "outcome", "dose", "period", "unit"
)
# Asymptotic: expect att close to 0.3 at G=2000, n=4000 observations.
assert abs(r.att - 0.3) < 0.1
def test_att_recovers_true_beta_continuous_near_d_lower(self):
"""Sanity: Design 1 DGP with beta_d_lower=0.3 recovers beta at scale."""
rng = np.random.default_rng(0)
G = 2000
u = rng.beta(2, 2, G)
d = 0.1 + 0.9 * u # d_lower ~ 0.1
# True WAS_{d_lower} = 0.3 since dy = 0.3 * (d - d_lower) + noise
dy = 0.3 * (d - 0.1) + 0.05 * rng.standard_normal(G)
panel = _make_panel(d, dy)
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
r = HeterogeneousAdoptionDiD(design="continuous_near_d_lower").fit(
panel, "outcome", "dose", "period", "unit"
)
assert abs(r.att - 0.3) < 0.1
def test_dose_mean_stored_on_result(self):
d, dy = _dgp_continuous_at_zero(500, seed=0)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD().fit(panel, "outcome", "dose", "period", "unit")
assert abs(r.dose_mean - float(d.mean())) < 1e-14
# =============================================================================
# Criterion 4: Mass-point Wald-IV point estimate parity
# =============================================================================
class TestMassPointWaldIV:
def test_wald_iv_point_estimate(self):
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="mass_point").fit(
panel, "outcome", "dose", "period", "unit"
)
Z = (d > 0.5).astype(float)
expected = (dy[Z == 1].mean() - dy[Z == 0].mean()) / (d[Z == 1].mean() - d[Z == 0].mean())
assert abs(r.att - expected) < 1e-14
def test_wald_iv_equals_2sls(self):
"""Sanity: Wald-IV is exactly 2SLS for binary instrument."""
d, dy = _dgp_mass_point(500, seed=7)
Z = (d > 0.5).astype(float).reshape(-1, 1)
# 2SLS via Z'X invert: beta = [(Z'X)^-1 Z'y][1]
X = np.column_stack([np.ones_like(d), d])
Zd = np.column_stack([np.ones_like(d), Z.ravel()])
beta_2sls = np.linalg.inv(Zd.T @ X) @ (Zd.T @ dy)
beta_wald = (dy[Z.ravel() == 1].mean() - dy[Z.ravel() == 0].mean()) / (
d[Z.ravel() == 1].mean() - d[Z.ravel() == 0].mean()
)
assert abs(float(beta_2sls[1]) - beta_wald) < 1e-12
def test_mass_point_n_counts_populated(self):
d, dy = _dgp_mass_point(500, seed=0, d_lower=0.5, mass_frac=0.3)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="mass_point").fit(
panel, "outcome", "dose", "period", "unit"
)
assert r.n_mass_point == int(0.3 * 500)
assert r.n_above_d_lower == 500 - int(0.3 * 500)
assert r.n_treated == r.n_above_d_lower
assert r.n_control == r.n_mass_point
# =============================================================================
# Criterion 5: Mass-point 2SLS SE sandwich parity
# =============================================================================
def _manual_2sls_sandwich_se(d, dy, d_lower, vcov_type, cluster=None):
"""Hand-coded textbook 2SLS sandwich using structural residuals.
Returns se_beta for the coefficient on d. Mirrors the helper in had.py
but computed from scratch to serve as the parity reference.
"""
n = len(d)
Z = (d > d_lower).astype(np.float64)
dose_gap = d[Z == 1].mean() - d[Z == 0].mean()
dy_gap = dy[Z == 1].mean() - dy[Z == 0].mean()
beta = dy_gap / dose_gap
alpha_hat = dy.mean() - beta * d.mean()
u = dy - alpha_hat - beta * d # STRUCTURAL residuals
X = np.column_stack([np.ones(n), d])
Zd = np.column_stack([np.ones(n), Z])
ZtX_inv = np.linalg.inv(Zd.T @ X)
if cluster is not None:
Omega = np.zeros((2, 2))
clusters = pd.unique(cluster)
G = len(clusters)
for c in clusters:
idx = cluster == c
s = Zd[idx].T @ u[idx]
Omega += np.outer(s, s)
Omega *= (G / (G - 1)) * ((n - 1) / (n - 2))
elif vcov_type == "classical":
sigma2 = (u * u).sum() / (n - 2)
Omega = sigma2 * (Zd.T @ Zd)
elif vcov_type == "hc1":
Omega = (n / (n - 2)) * (Zd.T @ ((u * u)[:, None] * Zd))
else:
raise ValueError(f"unknown vcov_type={vcov_type}")
V = ZtX_inv @ Omega @ ZtX_inv.T
return float(np.sqrt(V[1, 1]))
class TestMassPointSEParity:
def test_classical_parity(self):
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="mass_point", vcov_type="classical").fit(
panel, "outcome", "dose", "period", "unit"
)
expected = _manual_2sls_sandwich_se(d, dy, 0.5, "classical")
assert abs(r.se - expected) < 1e-12
def test_hc1_parity(self):
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="mass_point", vcov_type="hc1").fit(
panel, "outcome", "dose", "period", "unit"
)
expected = _manual_2sls_sandwich_se(d, dy, 0.5, "hc1")
assert abs(r.se - expected) < 1e-12
def test_cr1_cluster_robust_parity(self):
d, dy = _dgp_mass_point(500, seed=0)
cluster_ids = np.tile(np.arange(50), 10) # 50 clusters of 10 units
panel = _make_panel(d, dy, extra_cols={"state": cluster_ids})
r = HeterogeneousAdoptionDiD(design="mass_point", cluster="state").fit(
panel, "outcome", "dose", "period", "unit"
)
expected = _manual_2sls_sandwich_se(d, dy, 0.5, "hc1", cluster=cluster_ids)
assert abs(r.se - expected) < 1e-12
def test_robust_alias_maps_to_hc1(self):
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
r_robust = HeterogeneousAdoptionDiD(design="mass_point", robust=True).fit(
panel, "outcome", "dose", "period", "unit"
)
r_hc1 = HeterogeneousAdoptionDiD(design="mass_point", vcov_type="hc1").fit(
panel, "outcome", "dose", "period", "unit"
)
assert r_robust.se == r_hc1.se
def test_robust_false_maps_to_classical(self):
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
r_robust = HeterogeneousAdoptionDiD(design="mass_point", robust=False).fit(
panel, "outcome", "dose", "period", "unit"
)
r_classical = HeterogeneousAdoptionDiD(design="mass_point", vcov_type="classical").fit(
panel, "outcome", "dose", "period", "unit"
)
assert r_robust.se == r_classical.se
def test_vcov_type_explicit_overrides_robust(self):
"""When vcov_type is explicit, robust is ignored."""
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
r = HeterogeneousAdoptionDiD(design="mass_point", vcov_type="classical", robust=True).fit(
panel, "outcome", "dose", "period", "unit"
)
assert r.vcov_type == "classical"
# =============================================================================
# Criterion 6: hc2 / hc2_bm raise NotImplementedError
# =============================================================================
class TestMassPointUnsupportedVcov:
def test_hc2_raises(self):
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD(design="mass_point", vcov_type="hc2")
with pytest.raises(NotImplementedError, match="HC2"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_hc2_bm_raises(self):
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD(design="mass_point", vcov_type="hc2_bm")
with pytest.raises(NotImplementedError, match="HC2"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_hc2_pointer_references_followup_pr(self):
d, dy = _dgp_mass_point(500, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD(design="mass_point", vcov_type="hc2")
with pytest.raises(NotImplementedError, match="follow-up"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_vcov_type_ignored_on_continuous(self):
"""hc2 passed with continuous design emits warning, does not raise."""
d, dy = _dgp_continuous_at_zero(300, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD(design="continuous_at_zero", vcov_type="hc2")
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
r = est.fit(panel, "outcome", "dose", "period", "unit")
assert any("ignored" in str(warn.message).lower() for warn in w)
assert np.isfinite(r.att)
def test_robust_true_ignored_on_continuous_warns(self):
"""Review P2 round 9: robust=True on continuous path must warn.
The continuous designs use the CCT-2014 robust SE unconditionally;
robust= is a mass-point-only backward-compat alias for vcov_type.
Passing robust=True on a continuous path has no effect on the
computed SE, so the user must get a warning that the flag was
ignored.
"""
d, dy = _dgp_continuous_at_zero(300, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD(design="continuous_at_zero", robust=True)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
r = est.fit(panel, "outcome", "dose", "period", "unit")
robust_warnings = [warn for warn in w if "robust" in str(warn.message).lower()]
assert len(robust_warnings) >= 1
assert np.isfinite(r.att)
def test_robust_false_silent_on_continuous(self):
"""robust=False (the default) on continuous path emits no robust-warn."""
d, dy = _dgp_continuous_at_zero(300, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD(design="continuous_at_zero", robust=False)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
r = est.fit(panel, "outcome", "dose", "period", "unit")
robust_warnings = [warn for warn in w if "robust=True is ignored" in str(warn.message)]
assert len(robust_warnings) == 0
assert np.isfinite(r.att)
# =============================================================================
# Criterion 7: Panel-contract violations
# =============================================================================
class TestPanelContract:
def test_missing_outcome_col_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="column"):
est.fit(panel, "missing", "dose", "period", "unit")
def test_missing_dose_col_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="column"):
est.fit(panel, "outcome", "missing", "period", "unit")
def test_missing_time_col_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="column"):
est.fit(panel, "outcome", "dose", "missing", "unit")
def test_missing_unit_col_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="column"):
est.fit(panel, "outcome", "dose", "period", "missing")
def test_nonzero_pre_period_dose_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
panel.loc[panel["period"] == 1, "dose"] = 0.5
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match=r"D_\{g,1\}|pre-period"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_unbalanced_panel_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy).iloc[:-1] # drop one row
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match=r"[Uu]nbalanced|[Bb]alanced"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_three_periods_without_first_treat_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel2 = _make_panel(d, dy)
panel3 = pd.concat([panel2, panel2.assign(period=3)])
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match=r"two time periods|Phase 2b"):
est.fit(panel3, "outcome", "dose", "period", "unit")
def test_three_periods_with_first_treat_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel2 = _make_panel(d, dy)
panel3 = pd.concat([panel2, panel2.assign(period=3)])
panel3["ft"] = 2 # arbitrary first_treat
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match=r"two time periods|Phase 2b"):
est.fit(
panel3,
"outcome",
"dose",
"period",
"unit",
first_treat_col="ft",
)
def test_single_period_raises(self):
d, _ = _dgp_continuous_at_zero(200, seed=0)
panel = pd.DataFrame(
{
"unit": np.arange(200),
"period": 2,
"dose": d,
"outcome": np.zeros(200),
}
)
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="two-period"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_nan_outcome_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
panel.loc[0, "outcome"] = np.nan
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="NaN"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_nan_dose_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
panel.loc[3, "dose"] = np.nan
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="NaN"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_duplicate_unit_period_raises(self):
"""Two observations of the same unit-period cell."""
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
panel = pd.concat([panel, panel.iloc[[0]]]) # duplicate first row
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match=r"[Uu]nbalanced|observation"):
est.fit(panel, "outcome", "dose", "period", "unit")
def test_first_treat_col_invalid_cohort_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
# Set first_treat values to {0, 5, 2} where 5 is not t_post.
ft_unit = np.where(np.arange(200) % 2 == 0, 0, 5)
panel["ft"] = np.repeat(ft_unit, 2)
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match=r"first_treat_col"):
est.fit(
panel,
"outcome",
"dose",
"period",
"unit",
first_treat_col="ft",
)
def test_first_treat_col_mixed_row_nan_raises(self):
"""Review P2 round 8: per-unit rows like [valid, NaN] must be rejected.
`groupby().first()` silently skips NaNs; a unit with [0, NaN]
collapses to first_treat=0 and a unit-level NaN check would
pass. Row-level validation must catch the NaN on the bad row.
"""
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
# Unit-level first_treat all zero (never-treated); inject a NaN on
# exactly the second row of unit 0 (t_post row).
panel["ft"] = 0.0
unit0_post_idx = panel[(panel["unit"] == 0) & (panel["period"] == 2)].index[0]
panel.loc[unit0_post_idx, "ft"] = np.nan
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="NaN"):
est.fit(panel, "outcome", "dose", "period", "unit", first_treat_col="ft")
def test_first_treat_col_mixed_row_invalid_value_raises(self):
"""Per-unit rows like [valid, invalid_value] must be rejected."""
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
panel["ft"] = 0.0
# Inject an out-of-domain value on unit 0's post-period row.
unit0_post_idx = panel[(panel["unit"] == 0) & (panel["period"] == 2)].index[0]
panel.loc[unit0_post_idx, "ft"] = 999.0
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match=r"first_treat_col.*999"):
est.fit(panel, "outcome", "dose", "period", "unit", first_treat_col="ft")
# =============================================================================
# Criterion 8: NaN propagation
# =============================================================================
class TestNaNPropagation:
def test_constant_y_produces_nan_inference(self):
"""Constant outcome -> zero residuals -> NaN via safe_inference."""
d, _ = _dgp_continuous_at_zero(500, seed=0)
dy_zero = np.zeros_like(d)
panel = _make_panel(d, dy_zero)
r = HeterogeneousAdoptionDiD(design="continuous_at_zero").fit(
panel, "outcome", "dose", "period", "unit"
)
# All inference fields NaN when SE is non-finite.
assert_nan_inference(
{
"se": r.se,
"t_stat": r.t_stat,
"p_value": r.p_value,
"conf_int": r.conf_int,
}
)
def test_mass_point_all_at_d_lower_nan(self):
"""Degenerate mass-point: all units at d_lower -> NaN."""
rng = np.random.default_rng(0)
G = 500
d = np.full(G, 0.5) # all at 0.5
dy = 0.1 * rng.standard_normal(G)
panel = _make_panel(d, dy)
# Avoid triggering pre-period D=0 check by starting at 0.5 at t2.
r = HeterogeneousAdoptionDiD(design="mass_point", d_lower=0.5).fit(
panel, "outcome", "dose", "period", "unit"
)
assert np.isnan(r.att)
assert_nan_inference(
{
"se": r.se,
"t_stat": r.t_stat,
"p_value": r.p_value,
"conf_int": r.conf_int,
}
)
def test_helper_returns_nan_on_empty_z_one(self):
"""_fit_mass_point_2sls returns NaN when no units above d_lower."""
d = np.full(50, 0.5)
dy = np.random.default_rng(0).standard_normal(50)
beta, se, _ = _fit_mass_point_2sls(d, dy, 0.5, None, "hc1")
assert np.isnan(beta)
assert np.isnan(se)
def test_helper_returns_nan_on_empty_z_zero(self):
"""_fit_mass_point_2sls returns NaN when no units at d_lower."""
d = np.full(50, 0.6) # all strictly above d_lower=0.5
dy = np.random.default_rng(0).standard_normal(50)
beta, se, _ = _fit_mass_point_2sls(d, dy, 0.5, None, "hc1")
assert np.isnan(beta)
assert np.isnan(se)
def test_single_cluster_cr1_returns_nan(self):
"""CR1 with only 1 cluster is undefined -> NaN."""
rng = np.random.default_rng(0)
G = 100
d = np.concatenate([np.full(30, 0.5), rng.uniform(0.5, 1.0, G - 30)])
dy = 0.3 * d + 0.1 * rng.standard_normal(G)
panel = _make_panel(d, dy, extra_cols={"state": np.zeros(G, dtype=int)}) # single cluster
r = HeterogeneousAdoptionDiD(design="mass_point", cluster="state").fit(
panel, "outcome", "dose", "period", "unit"
)
assert np.isnan(r.se)
# =============================================================================
# Criterion 9: sklearn clone round-trip + fit idempotence
# =============================================================================
class TestSklearnCompat:
def test_get_params_returns_all_constructor_args(self):
est = HeterogeneousAdoptionDiD(
design="continuous_near_d_lower",
d_lower=0.3,
kernel="triangular",
alpha=0.1,
vcov_type="hc1",
robust=True,
cluster="state",
n_bootstrap=500,
seed=42,
)
params = est.get_params()
assert params == {
"design": "continuous_near_d_lower",
"d_lower": 0.3,
"kernel": "triangular",
"alpha": 0.1,
"vcov_type": "hc1",
"robust": True,
"cluster": "state",
"n_bootstrap": 500,
"seed": 42,
}
def test_clone_round_trip(self):
est = HeterogeneousAdoptionDiD(design="auto", alpha=0.1, kernel="triangular")
est2 = HeterogeneousAdoptionDiD(**est.get_params())
assert est.get_params() == est2.get_params()
def test_fit_idempotent_same_att(self):
d, dy = _dgp_continuous_at_zero(500, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD()
r1 = est.fit(panel, "outcome", "dose", "period", "unit")
r2 = est.fit(panel, "outcome", "dose", "period", "unit")
assert r1.att == r2.att
assert r1.se == r2.se
assert r1.conf_int == r2.conf_int
def test_set_params_updates_and_returns_self(self):
est = HeterogeneousAdoptionDiD()
ret = est.set_params(alpha=0.1, design="continuous_at_zero")
assert ret is est
assert est.alpha == 0.1
assert est.design == "continuous_at_zero"
def test_set_params_invalid_key_raises(self):
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="Invalid parameter"):
est.set_params(not_a_param=True)
def test_set_params_rejects_method_names(self):
"""Review P1 round 10: set_params must restrict to constructor keys,
not any hasattr-able name. Method names like 'fit' must raise,
else they would silently overwrite the method.
"""
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="Invalid parameter"):
est.set_params(fit="not_a_method")
# sanity: fit is still callable on the class
assert callable(est.fit)
def test_set_params_rejects_private_attrs(self):
"""Internal-looking attribute names must also raise."""
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="Invalid parameter"):
est.set_params(_internal=42)
def test_get_params_accepts_deep_keyword(self):
"""Review P1 round 10: get_params must match sklearn's signature.
sklearn.base.BaseEstimator.get_params(deep=True). This estimator
has no nested sub-estimators, so deep=True and deep=False return
the same dict, but the keyword must be accepted.
"""
est = HeterogeneousAdoptionDiD(design="continuous_at_zero", alpha=0.1)
params_default = est.get_params()
params_deep_true = est.get_params(deep=True)
params_deep_false = est.get_params(deep=False)
assert params_default == params_deep_true == params_deep_false
def test_sklearn_clone_round_trip_if_available(self):
"""If sklearn is installed, sklearn.base.clone round-trips the estimator."""
sklearn_base = pytest.importorskip("sklearn.base")
est = HeterogeneousAdoptionDiD(design="auto", alpha=0.1, kernel="triangular")
cloned = sklearn_base.clone(est)
assert cloned.get_params() == est.get_params()
assert cloned is not est
# clone produces a fresh instance of the same class.
assert type(cloned) is type(est)
def test_set_params_invalid_design_raises(self):
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="design"):
est.set_params(design="made_up")
def test_set_params_rollback_on_failure(self):
"""Review P2 round 11: set_params must be ATOMIC.
A failing call (valid key but value violates constructor
constraints) must leave the estimator unchanged so the caller
can catch the ValueError and reuse the object.
"""
est = HeterogeneousAdoptionDiD(alpha=0.05, design="continuous_at_zero")
baseline = est.get_params()
# Multi-key call where alpha is valid but design is invalid.
# The old (non-atomic) code would have set alpha before raising
# on design, leaving the estimator half-mutated.
with pytest.raises(ValueError):
est.set_params(alpha=0.1, design="garbage_design")
assert est.get_params() == baseline
def test_set_params_rollback_on_invalid_key(self):
"""Rejecting an unknown key must leave self unchanged."""
est = HeterogeneousAdoptionDiD(alpha=0.05)
baseline = est.get_params()
with pytest.raises(ValueError):
est.set_params(alpha=0.1, not_a_param=True)
assert est.get_params() == baseline
def test_set_params_rollback_on_invalid_alpha(self):
"""alpha outside (0, 1) must leave self unchanged."""
est = HeterogeneousAdoptionDiD(alpha=0.05, design="continuous_at_zero")
baseline = est.get_params()
with pytest.raises(ValueError):
est.set_params(alpha=1.5, kernel="triangular")
assert est.get_params() == baseline
# =============================================================================
# Criterion 10: Scaffolding raises
# =============================================================================
class TestScaffoldingRejections:
def test_aggregate_event_study_on_two_period_panel_raises(self):
"""Event-study mode requires T > 2 (Phase 2b). A T=2 panel should
raise a helpful ValueError pointing to ``aggregate='overall'``."""
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="more than two"):
est.fit(
panel,
"outcome",
"dose",
"period",
"unit",
aggregate="event_study",
)
def test_aggregate_invalid_raises(self):
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD()
with pytest.raises(ValueError, match="Invalid aggregate"):
est.fit(
panel,
"outcome",
"dose",
"period",
"unit",
aggregate="garbage",
)
def test_survey_bad_type_raises(self):
"""survey= must be a SurveyDesign-like object with a `.resolve()`
method; a bare string (or any object lacking `.resolve()`) raises
TypeError front-door. Updated PR #376 R8 P1: the data-in type
guard now runs at the canonical entry and rejects on the
`hasattr(survey, "resolve")` check (which catches both bare
strings and ResolvedSurveyDesign / make_pweight_design output)."""
d, dy = _dgp_continuous_at_zero(200, seed=0)
panel = _make_panel(d, dy)
est = HeterogeneousAdoptionDiD()
with pytest.raises(TypeError, match="SurveyDesign"):
est.fit(
panel,
"outcome",
"dose",
"period",
"unit",
survey="anything",
)
# =============================================================================
# Criterion 11: get_params signature enumeration
# =============================================================================
class TestGetParamsContract:
You can’t perform that action at this time.
