Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathhad.py
More file actions
4649 lines (4318 loc) · 224 KB
/
Copy pathhad.py
File metadata and controls
4649 lines (4318 loc) · 224 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
"""
Heterogeneous Adoption Difference-in-Differences (HAD) estimator (Phase 2a).
Implements the de Chaisemartin, Ciccia, D'Haultfoeuille, and Knau (2026)
Weighted-Average-Slope (WAS) estimator with three design-dispatch paths.
All three paths produce a beta-scale point estimate of the form
``(mean(Delta Y) - [boundary limit]) / [expected dose gap]`` (Design 1
family) or the Wald-IV ratio (mass-point), then route inference through
:func:`diff_diff.utils.safe_inference`.
1. Design 1' (``continuous_at_zero``): ``d_lower = 0``, boundary density
continuous at zero, Assumption 3. Theorem 1 / Equation 3
(identification); Equation 7 (sample estimator):
beta = (E[Delta Y] - lim_{d v 0} E[Delta Y | D_2 <= d]) / E[D_2]
The bias-corrected local-linear fit at ``boundary = 0`` estimates
the boundary limit; ``E[D_2]`` and ``E[Delta Y]`` are plugin sample
means.
2. Design 1 continuous-near-d_lower (``continuous_near_d_lower``):
``d_lower > 0``, continuous boundary density, Assumption 5 or 6.
Theorem 3 / Equation 11 (``WAS_{d_lower}`` under Assumption 6;
Theorem 4 is the QUG null test, not this estimand):
beta = (E[Delta Y] - lim_{d v d_lower} E[Delta Y | D_2 <= d])
/ E[D_2 - d_lower]
The local-linear fit is anchored at ``d_lower`` via the regressor
shift ``D' = D - d_lower``, evaluated at ``boundary = 0`` on the
shifted scale.
3. Design 1 mass-point (``mass_point``): ``d_lower > 0``, modal fraction
at ``d.min()`` exceeds 2%. Sample-average 2SLS with instrument
``Z_g = 1{D_{g,2} > d_lower}`` (paper Section 3.2.4). Point estimate
equals the Wald-IV ratio
``(Ybar_{Z=1} - Ybar_{Z=0}) / (Dbar_{Z=1} - Dbar_{Z=0})``. Standard
error via the structural-residual 2SLS sandwich
(see ``_fit_mass_point_2sls``).
Phase 2a ships the single-period WAS estimator (``aggregate="overall"``).
Phase 2b adds the multi-period event-study extension (paper Appendix B.2)
via ``aggregate="event_study"``: per-horizon WAS estimates with pointwise
CIs, including pre-period placebos, reusing the three Phase 2a design
paths on per-horizon first differences anchored at ``Y_{g, F-1}``.
Staggered-timing panels are auto-filtered to the last-treatment cohort
per paper Appendix B.2 prescription.
Infrastructure reused from Phase 1:
- ``diff_diff.local_linear.bias_corrected_local_linear`` (Phase 1c)
- ``diff_diff.local_linear.BiasCorrectedFit``, ``BandwidthResult``
- ``diff_diff.utils.safe_inference`` (NaN-safe CI gating)
- ``diff_diff.prep.balance_panel`` (panel validation)
References
----------
- de Chaisemartin, C., Ciccia, D., D'Haultfoeuille, X., & Knau, F. (2026).
Difference-in-Differences Estimators When No Unit Remains Untreated.
arXiv:2405.04465v6.
- Calonico, S., Cattaneo, M. D., & Titiunik, R. (2014). Robust
nonparametric confidence intervals for regression-discontinuity designs.
Econometrica, 82(6), 2295-2326.
"""
from __future__ import annotations
import warnings
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
from diff_diff.local_linear import (
BandwidthResult,
BiasCorrectedFit,
bias_corrected_local_linear,
)
from diff_diff.survey import (
HAD_DEPRECATION_MSG_SURVEY_KWARG,
HAD_DEPRECATION_MSG_WEIGHTS_KWARG_HAD_FIT,
HAD_DUAL_KNOB_MUTEX_MSG_DATA_IN,
SurveyMetadata,
compute_survey_metadata,
)
from diff_diff.utils import safe_inference
__all__ = [
"HeterogeneousAdoptionDiD",
"HeterogeneousAdoptionDiDResults",
"HeterogeneousAdoptionDiDEventStudyResults",
]
# =============================================================================
# Module-level constants
# =============================================================================
# REGISTRY line 2320 auto-detect boundary: d.min() < 0.01 * median(|d|) resolves
# to Design 1' (continuous_at_zero). Distinct from Phase 1c's stricter
# _DESIGN_1_PRIME_RATIO = 0.05 in ``local_linear.py`` which is a plausibility
# guard on the nonparametric fit, not the auto-detect rule.
_CONTINUOUS_AT_ZERO_THRESHOLD = 0.01
# REGISTRY line 2320 mass-point rule: modal fraction at d.min() > 0.02 resolves
# to Design 1 mass-point. Mirrored (not imported) from
# ``diff_diff.local_linear._validate_had_inputs`` where the same constant
# enforces the upstream mass-point rejection on the nonparametric path.
_MASS_POINT_THRESHOLD = 0.02
_VALID_DESIGNS = (
"auto",
"continuous_at_zero",
"continuous_near_d_lower",
"mass_point",
)
_VALID_AGGREGATES = ("overall", "event_study")
# Mass-point 2SLS supports: classical, hc1 (HC0 is an unscaled variant not
# publicly exposed; hc2 and hc2_bm raise NotImplementedError pending a
# 2SLS-specific leverage derivation and R parity anchor).
_MASS_POINT_VCOV_SUPPORTED = ("classical", "hc1")
_MASS_POINT_VCOV_UNSUPPORTED = ("hc2", "hc2_bm")
# Target-parameter label per design. Design 1' targets the WAS (Assumption 3);
# Design 1 targets WAS_{d_lower} (Assumption 5 or 6), which also applies to
# the mass-point path (paper Section 3.2.4).
_TARGET_PARAMETER = {
"continuous_at_zero": "WAS",
"continuous_near_d_lower": "WAS_d_lower",
"mass_point": "WAS_d_lower",
}
# =============================================================================
# JSON-serialization helpers
# =============================================================================
def _json_safe_scalar(x: Any) -> Any:
"""Coerce a scalar to a JSON-serializable type.
- NumPy scalars (``np.int64``, ``np.float64``, ``np.bool_``) ->
native Python via ``.item()``
- ``pd.Timestamp`` / ``pd.Timedelta`` -> ISO 8601 string via
``.isoformat()``
- Everything else returned as-is.
The ``to_dict`` methods use this to keep the returned dict
serializable via ``json.dumps`` regardless of the underlying
pandas/numpy dtype of the time / first_treat columns.
"""
if isinstance(x, (pd.Timestamp, pd.Timedelta)):
return x.isoformat()
if hasattr(x, "item") and callable(getattr(x, "item")):
try:
return x.item()
except (AttributeError, ValueError, TypeError):
return x
return x
def _json_safe_filter_info(
filter_info: Optional[Dict[str, Any]],
) -> Optional[Dict[str, Any]]:
"""Normalize a ``filter_info`` dict to JSON-safe scalars.
Returns ``None`` unchanged; otherwise coerces ``F_last`` and each
entry in ``dropped_cohorts`` via :func:`_json_safe_scalar`. Int
counts are cast to ``int`` for stability.
"""
if filter_info is None:
return None
return {
"F_last": _json_safe_scalar(filter_info.get("F_last")),
"n_kept": int(filter_info.get("n_kept", 0)),
"n_dropped": int(filter_info.get("n_dropped", 0)),
"dropped_cohorts": [_json_safe_scalar(c) for c in filter_info.get("dropped_cohorts", [])],
}
# =============================================================================
# Results dataclass
# =============================================================================
@dataclass
class HeterogeneousAdoptionDiDResults:
"""Estimator output for :class:`HeterogeneousAdoptionDiD`.
NaN-safe inference: the three downstream fields ``t_stat``,
``p_value``, and ``conf_int`` are routed through
:func:`diff_diff.utils.safe_inference`, which returns NaN on all
three whenever ``se`` is non-finite, zero, or negative. ``att`` and
``se`` themselves are RAW estimator outputs from the chosen fit
path and are NOT gated by ``safe_inference``:
- On the degenerate fit configurations (constant outcome on the
continuous paths, all-units-at-d_lower / no-dose-variation on the
mass-point path), the fit path explicitly returns
``(att=nan, se=nan)``, which combined with the safe-inference
gate yields all five fields NaN together.
- On the degenerate CR1 cluster configuration (mass-point path
with a single cluster), ``_fit_mass_point_2sls`` returns
``(att=beta_hat, se=nan)`` - ``att`` stays finite because the
Wald-IV ratio is well defined, but the cluster-robust SE is
not, so ``se`` is NaN and the downstream triple becomes NaN
via the safe-inference gate.
So the guaranteed NaN coupling is on the downstream triple
(``t_stat``, ``p_value``, ``conf_int``), not on ``att``. The
``assert_nan_inference`` fixture in ``tests/conftest.py`` checks
the downstream triple against the gate contract and does not
assume ``att`` is NaN.
Attributes
----------
att : float
Point estimate of the WAS parameter on the beta-scale.
- Design 1' (paper Theorem 1 / Equation 3 identification;
Equation 7 sample estimator):
``att = (mean(ΔY) - tau_bc) / D_bar``
where ``tau_bc`` is the bias-corrected local-linear estimate
of ``lim_{d v 0} E[ΔY | D_2 <= d]`` and
``D_bar = (1/G) * sum(D_{g,2})``.
- Design 1 continuous-near-d_lower (paper Theorem 3 /
Equation 11, ``WAS_{d_lower}`` under Assumption 6):
``att = (mean(ΔY) - tau_bc) / mean(D_2 - d_lower)``
where ``tau_bc`` is the bias-corrected local-linear estimate
of ``lim_{d v d_lower} E[ΔY | D_2 <= d]``.
- Mass-point (paper Section 3.2.4): the Wald-IV / 2SLS
coefficient directly -
``(Ybar_{Z=1} - Ybar_{Z=0}) / (Dbar_{Z=1} - Dbar_{Z=0})``.
se : float
Standard error on the beta-scale. For continuous designs:
- Unweighted or ``weights=<array>``: CCT-2014 weighted-robust SE
from Phase 1c divided by ``|den|`` (``den`` = raw or weighted
denominator depending on fit path).
- ``survey=SurveyDesign(...)``: Binder (1983) Taylor-series
linearization of the per-unit IF (bias-corrected scale,
aligned with ``tau_bc``) routed through
:func:`compute_survey_if_variance` for PSU-aggregated,
FPC/strata-adjusted variance, divided by ``|den|``.
In both cases the higher-order variance from ``mean(ΔY)`` is
dominated by the nonparametric boundary estimate in large
samples and is not included in the leading-order formula. For
mass-point, the 2SLS structural-residual sandwich SE.
t_stat, p_value, conf_int : inference fields
Routed through ``safe_inference``; NaN when SE is non-finite.
alpha : float
CI level used at fit time (0.05 for a 95% CI).
design : str
Resolved design mode: ``"continuous_at_zero"``,
``"continuous_near_d_lower"``, or ``"mass_point"``. ``"auto"`` is
resolved to one of the three concrete modes before storing.
target_parameter : str
Estimand label: ``"WAS"`` for Design 1', ``"WAS_d_lower"`` for the
other two. Pins the estimand semantically even when two designs
share the same divisor.
d_lower : float
Support infimum ``d_lower``. ``0.0`` for Design 1';
``float(d.min())`` for the other two.
dose_mean : float
``D_bar = (1/G) * sum(D_{g,2})``.
n_obs : int
Number of units contributing to the estimator (post panel
aggregation to unit-level first differences).
n_treated : int
Number of units with ``D_{g,2} > d_lower``.
n_control : int
Number of units at or below ``d_lower`` (the "not-treated" subset).
n_mass_point : int or None
Mass-point path only: number of units with ``D_{g,2} == d_lower``.
``None`` on continuous paths.
n_above_d_lower : int or None
Mass-point path only: number of units with ``D_{g,2} > d_lower``.
``None`` on continuous paths.
inference_method : str
``"analytical_nonparametric"`` (continuous designs) or
``"analytical_2sls"`` (mass-point).
vcov_type : str or None
Effective variance-covariance family used. ``None`` on continuous
paths (they use the CCT-2014 robust SE from Phase 1c, not the
library's ``vcov_type`` enum). Mass-point: ``"classical"`` or
``"hc1"`` when ``cluster`` is not supplied, and ``"cr1"``
whenever ``cluster`` is supplied (cluster-robust CR1 is computed
regardless of the requested ``vcov_type`` because
classical/hc1 + cluster collapses to the same CR1 sandwich).
Downstream consumers reading ``result.to_dict()`` can inspect
this field directly to determine the effective SE family.
cluster_name : str or None
Column name of the cluster variable on the mass-point path when
cluster-robust SE is requested. ``None`` otherwise.
survey_metadata : SurveyMetadata or None
Repo-standard survey metadata dataclass from
:class:`diff_diff.survey.SurveyMetadata`. ``None`` when ``fit()``
was called without ``survey=`` or ``weights=``; populated on the
continuous-dose weighted paths via
:func:`diff_diff.survey.compute_survey_metadata`. Exposes
``weight_type``, ``effective_n``, ``design_effect``,
``sum_weights``, ``n_strata``, ``n_psu``, ``weight_range``, and
``df_survey`` for downstream reporting consumers (BusinessReport,
DiagnosticReport) that read these fields via attribute access.
HAD-specific inference-method info (pweight vs Binder-TSL) is
carried on ``inference_method`` and ``variance_formula``.
bandwidth_diagnostics : BandwidthResult or None
Full Phase 1b MSE-DPI selector output on the continuous paths
(when bandwidths were auto-selected). ``None`` on the mass-point
path (parametric, no bandwidth).
bias_corrected_fit : BiasCorrectedFit or None
Full Phase 1c bias-corrected local-linear fit on the continuous
paths. ``None`` on the mass-point path.
"""
# Point estimate + inference (safe_inference-gated)
att: float
se: float
t_stat: float
p_value: float
conf_int: Tuple[float, float]
alpha: float
# Design metadata
design: str
target_parameter: str
d_lower: float
dose_mean: float
# Sample counts
n_obs: int
n_treated: int
n_control: int
n_mass_point: Optional[int]
n_above_d_lower: Optional[int]
# Inference metadata
inference_method: str
vcov_type: Optional[str]
cluster_name: Optional[str]
survey_metadata: Optional[SurveyMetadata]
# Nonparametric-only diagnostics
bandwidth_diagnostics: Optional[BandwidthResult]
bias_corrected_fit: Optional[BiasCorrectedFit]
# Phase 4.5 weighted-path extras (optional so unweighted fits stay unchanged)
variance_formula: Optional[str] = None
"""HAD-specific label for the SE formula on weighted fits, populated
on BOTH continuous and mass-point designs (Phase 4.5 A / B):
``"pweight"`` (continuous, weighted-robust CCT 2014 under the
``weights=`` shortcut), ``"survey_binder_tsl"`` (continuous, Binder
1983 TSL with PSU/strata/FPC under ``survey_design=SurveyDesign(...)``),
``"pweight_2sls"`` (mass-point + ``weights=``; label applied
uniformly across vcov families — classical / HC1 / CR1 — on the
weighted 2SLS path, with the actual sandwich resolved via
``vcov_type``), or ``"survey_binder_tsl_2sls"`` (mass-point, Binder
1983 TSL under ``survey_design=``). ``None`` on unweighted fits. Orthogonal to ``survey_metadata`` which is the
repo-standard :class:`diff_diff.survey.SurveyMetadata` shared with
downstream report/diagnostic consumers (no HAD-specific leakage)."""
effective_dose_mean: Optional[float] = None
"""Weighted denominator used by the beta-scale rescaling, populated
on weighted fits across all designs: ``sum(w_g · D_g) / sum(w_g)``
on ``continuous_at_zero``, ``sum(w_g · (D_g - d_lower)) / sum(w_g)``
on ``continuous_near_d_lower``, and the weighted Wald-IV dose gap
``mean(D | Z=1, w) - mean(D | Z=0, w)`` on ``mass_point`` (where
``Z = 1{D > d_lower}``). On the continuous designs reduces
bit-exactly to ``dose_mean`` / ``mean(D - d_lower)`` when weights
are uniform or absent. ``None`` when ``fit()`` was called without
``survey_design=`` / ``survey=`` / ``weights=`` (use ``dose_mean``
there). Exists because ``dose_mean`` is the raw sample mean of the
dose column; under weighted fits the estimator's actual denominator
is the weighted form above, and users reconstructing the β-scale
value by hand need the weighted one."""
def __repr__(self) -> str:
base = (
f"HeterogeneousAdoptionDiDResults("
f"att={self.att:.4f}, se={self.se:.4f}, "
f"design={self.design!r}, n_obs={self.n_obs}"
)
# Surface weighted-path identity when the fit was weighted, so the
# one-line repr makes it unambiguous which inference family was
# used (pweight-shortcut vs full Binder-TSL survey) and the
# effective denominator flows into ad-hoc log output.
if self.variance_formula is not None:
base += f", variance_formula={self.variance_formula!r}"
if self.effective_dose_mean is not None:
base += f", effective_dose_mean={self.effective_dose_mean:.4g}"
return base + ")"
def summary(self) -> str:
"""Formatted summary table."""
width = 72
conf_level = int((1 - self.alpha) * 100)
lines = [
"=" * width,
"HeterogeneousAdoptionDiD Estimation Results".center(width),
"=" * width,
"",
f"{'Design:':<30} {self.design:>20}",
f"{'Target parameter:':<30} {self.target_parameter:>20}",
f"{'d_lower:':<30} {self.d_lower:>20.6g}",
f"{'D_bar (dose mean):':<30} {self.dose_mean:>20.6g}",
f"{'Observations (units):':<30} {self.n_obs:>20}",
f"{'Above d_lower:':<30} {self.n_treated:>20}",
f"{'At/below d_lower:':<30} {self.n_control:>20}",
]
if self.n_mass_point is not None:
lines.append(f"{'At d_lower (mass point):':<30} {self.n_mass_point:>20}")
if self.n_above_d_lower is not None:
lines.append(f"{'Strictly above d_lower:':<30} {self.n_above_d_lower:>20}")
lines.append(f"{'Inference method:':<30} {self.inference_method:>20}")
if self.vcov_type is not None:
if self.cluster_name is not None:
# Cluster-robust (CR1): the stored vcov_type is already "cr1",
# but render with the cluster column for clarity.
label = f"CR1 at {self.cluster_name}"
else:
label = self.vcov_type
lines.append(f"{'Variance:':<30} {label:>20}")
if self.bandwidth_diagnostics is not None:
bw = self.bandwidth_diagnostics
lines.append(f"{'Bandwidth h (MSE-DPI):':<30} {bw.h_mse:>20.6g}")
lines.append(f"{'Bandwidth b (bias):':<30} {bw.b_mse:>20.6g}")
if self.bias_corrected_fit is not None:
bc = self.bias_corrected_fit
lines.append(f"{'Bandwidth h used:':<30} {bc.h:>20.6g}")
lines.append(f"{'Obs in window (n_used):':<30} {bc.n_used:>20}")
if self.survey_metadata is not None:
sm = self.survey_metadata
vf_label = self.variance_formula or "unknown"
lines.append(f"{'Variance formula:':<30} {vf_label:>20}")
lines.append(f"{'Effective sample size:':<30} {sm.effective_n:>20.6g}")
if self.effective_dose_mean is not None:
lines.append(
f"{'Weighted D̄ (denominator):':<30} " f"{self.effective_dose_mean:>20.6g}"
)
if sm.df_survey is not None:
lines.append(f"{'Survey df:':<30} {sm.df_survey:>20}")
param_label = self.target_parameter
lines.extend(
[
"",
"-" * width,
(
f"{'Parameter':<15} {'Estimate':>12} {'Std. Err.':>12} "
f"{'t-stat':>10} {'P>|t|':>10}"
),
"-" * width,
(
f"{param_label:<15} {self.att:>12.4f} {self.se:>12.4f} "
f"{self.t_stat:>10.3f} {self.p_value:>10.4f}"
),
"-" * width,
"",
(
f"{conf_level}% Confidence Interval: "
f"[{self.conf_int[0]:.4f}, {self.conf_int[1]:.4f}]"
),
"=" * width,
]
)
return "\n".join(lines)
def print_summary(self) -> None:
"""Print the summary to stdout."""
print(self.summary())
def to_dict(self) -> Dict[str, Any]:
"""Return results as a dict of scalars + weighted-path surfaces.
Always-present keys mirror the dataclass fields: ``att``, ``se``,
``t_stat``, ``p_value``, ``conf_int_lower`` / ``conf_int_upper``,
``alpha``, ``design``, ``target_parameter``, ``d_lower``,
``dose_mean``, ``n_obs`` / ``n_treated`` / ``n_control`` /
``n_mass_point`` / ``n_above_d_lower``, ``inference_method``,
``vcov_type``, ``cluster_name``.
Weighted-path keys (``None`` on unweighted fits):
- ``survey_metadata``: repo-standard
:class:`diff_diff.survey.SurveyMetadata` dataclass (object, not
dict) carrying ``weight_type`` / ``effective_n`` /
``design_effect`` / ``sum_weights`` / ``weight_range`` +
``n_strata`` / ``n_psu`` / ``df_survey`` (latter three
``None`` on the ``weights=`` shortcut).
- ``variance_formula``: HAD-specific SE label, populated on BOTH
continuous and mass-point designs (Phase 4.5 A / B):
``"pweight"`` (continuous, weighted-robust CCT 2014 under
``weights=``), ``"survey_binder_tsl"`` (continuous, Binder
1983 TSL under ``survey_design=``), ``"pweight_2sls"``
(mass-point + ``weights=``; label applied uniformly across
vcov families — classical / HC1 / CR1 — with the sandwich
resolved via ``vcov_type``), or ``"survey_binder_tsl_2sls"``
(mass-point, Binder 1983 TSL under ``survey_design=``). See
the field docstring above for the full contract.
- ``effective_dose_mean``: weighted denominator used by the
beta-scale rescaling - weighted ``mean(D)`` on
``continuous_at_zero``, weighted ``mean(D - d_lower)`` on
``continuous_near_d_lower``, or the weighted Wald-IV dose gap
``mean(D | Z=1, w) - mean(D | Z=0, w)`` on ``mass_point``."""
return {
"att": self.att,
"se": self.se,
"t_stat": self.t_stat,
"p_value": self.p_value,
"conf_int_lower": self.conf_int[0],
"conf_int_upper": self.conf_int[1],
"alpha": self.alpha,
"design": self.design,
"target_parameter": self.target_parameter,
"d_lower": self.d_lower,
"dose_mean": self.dose_mean,
"n_obs": self.n_obs,
"n_treated": self.n_treated,
"n_control": self.n_control,
"n_mass_point": self.n_mass_point,
"n_above_d_lower": self.n_above_d_lower,
"inference_method": self.inference_method,
"vcov_type": self.vcov_type,
"cluster_name": self.cluster_name,
"survey_metadata": self.survey_metadata,
"variance_formula": self.variance_formula,
"effective_dose_mean": self.effective_dose_mean,
}
def to_dataframe(self) -> pd.DataFrame:
"""Return a one-row DataFrame of the result dict."""
return pd.DataFrame([self.to_dict()])
@dataclass
class HeterogeneousAdoptionDiDEventStudyResults:
"""Event-study results for :class:`HeterogeneousAdoptionDiD` (Phase 2b).
Per-horizon arrays align with ``event_times`` by index; all per-horizon
arrays have shape ``(n_horizons,)``. The anchor horizon ``e = -1``
(i.e., ``t = F - 1``) is NOT included because
``Y_{g, F-1} - Y_{g, F-1} = 0`` trivially and the WAS is not identified
there.
Per-horizon inference fields (``t_stat``, ``p_value``, ``conf_int_low``,
``conf_int_high``) are NaN-coupled to the per-horizon ``se`` via
:func:`diff_diff.utils.safe_inference`; ``att`` and ``se`` themselves
are raw estimator outputs from the chosen design path on each
horizon's first differences.
Design resolution is SHARED across horizons: the design, ``d_lower``,
``target_parameter``, and ``inference_method`` are single scalars
determined once from the post-period dose distribution ``D_{g, F}``
(paper Appendix B.2 convention — the dose regressor is invariant
across event-time horizons).
Attributes
----------
event_times : np.ndarray, shape (n_horizons,)
Integer event-time labels ``e = t - F``, sorted ascending.
Excludes ``e = -1`` (the anchor). Post-period horizons have
``e >= 0``; pre-period placebos have ``e <= -2``.
att : np.ndarray, shape (n_horizons,)
Per-horizon WAS point estimate on the beta-scale (see
:class:`HeterogeneousAdoptionDiDResults.att` for the per-design
formula, applied to ``ΔY_t = Y_{g,t} - Y_{g,F-1}``).
se : np.ndarray, shape (n_horizons,)
Per-horizon standard error on the beta-scale. Three regimes:
- **Unweighted**: per-horizon INDEPENDENT analytical sandwich
(continuous: CCT-2014 weighted-robust divided by ``|den|``;
mass-point: structural-residual 2SLS sandwich via
``_fit_mass_point_2sls``). No cross-horizon covariance.
- **``weights=`` shortcut**: continuous paths still use the
CCT-2014 weighted-robust SE from lprobust (``bc_fit.se_robust
/ |den|``); mass-point uses the analytical weighted 2SLS
pweight sandwich (HC1 / classical / CR1 depending on
``vcov_type`` + ``cluster=``). No Binder-TSL composition
on this path — inference is Normal (``df=None``).
- **``survey=``**: each horizon composes Binder (1983)
Taylor-series linearization via
:func:`compute_survey_if_variance` on the per-unit β̂-scale
IF (continuous + mass-point both route through the same
helper). ``df_survey`` threads into ``safe_inference`` for
t-inference.
Pointwise CIs are always populated; a simultaneous confidence
band is available only on the weighted path via ``cband_*``
below. Joint cross-horizon analytical covariance is not
computed in this release (tracked in TODO.md).
t_stat, p_value : np.ndarray, shape (n_horizons,)
Per-horizon inference triple element.
conf_int_low, conf_int_high : np.ndarray, shape (n_horizons,)
Per-horizon CI endpoints at level ``alpha``.
n_obs_per_horizon : np.ndarray, shape (n_horizons,)
Per-horizon sample size (units contributing at that event time).
In Phase 2b this equals ``n_units`` for every horizon because the
validator rejects NaN in outcome / dose / unit columns upstream;
tracked as a field for future flexibility (e.g., per-period
missingness).
alpha : float
CI level used at fit time (0.05 for a 95% CI).
design : str
Resolved design mode, shared across horizons:
``"continuous_at_zero"``, ``"continuous_near_d_lower"``, or
``"mass_point"``.
target_parameter : str
Estimand label: ``"WAS"`` for Design 1' (continuous_at_zero),
``"WAS_d_lower"`` for the other two.
d_lower : float
Support infimum used for all horizons. ``0.0`` for Design 1';
``float(d.min())`` otherwise.
dose_mean : float
``D_bar = (1/G) * sum(D_{g,F})`` computed on the fit sample (after
the staggered last-cohort filter, if applied).
F : object
First-treatment period label (arbitrary dtype — int, str,
datetime). Identified by the multi-period dose invariant from the
fitted data.
n_units : int
Number of unique units contributing to the fit. After staggered
auto-filter: last-cohort units PLUS never-treated (``first_treat = 0``)
units retained as the untreated-group comparison per paper
Appendix B.2. Only earlier-treated cohorts are dropped.
inference_method : str
``"analytical_nonparametric"`` (continuous designs) or
``"analytical_2sls"`` (mass-point). Shared across horizons.
vcov_type : str or None
Effective variance-covariance family used on the mass-point path
(``"classical"``, ``"hc1"``, or ``"cr1"`` when cluster supplied).
``None`` on the continuous paths (they use CCT-2014 robust SE).
cluster_name : str or None
Column name of the cluster variable when cluster-robust SE is
requested. ``None`` otherwise.
survey_metadata : SurveyMetadata or None
Repo-standard survey metadata dataclass from
:class:`diff_diff.survey.SurveyMetadata`. ``None`` when
``fit()`` was called without ``survey=`` or ``weights=``;
populated on the weighted event-study path (Phase 4.5 B). See
:class:`HeterogeneousAdoptionDiDResults.survey_metadata` for
the attribute contract.
variance_formula : str or None
Per-horizon variance family (applied uniformly across horizons).
``"pweight"`` / ``"pweight_2sls"`` on the ``weights=`` shortcut,
``"survey_binder_tsl"`` / ``"survey_binder_tsl_2sls"`` on the
``survey=`` path. ``None`` on unweighted fits.
effective_dose_mean : float or None
Weighted denominator used by the β̂-scale rescaling (continuous
paths: weighted sample mean of ``d`` or ``d - d_lower``;
mass-point: weighted Wald-IV dose gap). ``None`` on unweighted
fits.
cband_low, cband_high : np.ndarray or None, shape (n_horizons,)
Simultaneous confidence-band endpoints constructed by the
multiplier-bootstrap sup-t procedure. ``None`` on unweighted
fits and when ``fit(..., cband=False)`` is passed. Horizons
with ``se <= 0`` or non-finite ``se`` are NaN (matches the
pointwise inference gate from ``safe_inference``).
cband_crit_value : float or None
Sup-t multiplier-bootstrap critical value at level
``1 - alpha``. Under a trivial resolved design (no strata /
PSU / FPC) at ``H=1`` reduces to ``Φ⁻¹(1 − alpha/2) ≈ 1.96``
up to Monte Carlo error; under stratified designs the helper
applies PSU-aggregation + stratum-demeaning + ``sqrt(n_h /
(n_h - 1))`` small-sample correction so the bootstrap
variance matches the analytical Binder-TSL target term-for-
term.
cband_method : str or None
``"multiplier_bootstrap"`` on the weighted event-study path
with ``cband=True``, else ``None``.
cband_n_bootstrap : int or None
Number of multiplier-bootstrap replicates used to compute the
sup-t critical value.
bandwidth_diagnostics : list[BandwidthResult] or None
Per-horizon bandwidth diagnostics on the continuous paths;
``None`` on the mass-point path. When non-None, aligned with
``event_times`` by index.
bias_corrected_fit : list[BiasCorrectedFit] or None
Per-horizon bias-corrected fit on the continuous paths; ``None``
on the mass-point path. When non-None, aligned with
``event_times`` by index.
filter_info : dict or None
Populated when the staggered-timing last-cohort auto-filter fires.
Keys: ``"F_last"`` (kept cohort label), ``"n_kept"`` (units
retained), ``"n_dropped"`` (units dropped), ``"dropped_cohorts"``
(list of dropped cohort labels). ``None`` when no filter was
applied.
"""
# Per-horizon arrays
event_times: np.ndarray
att: np.ndarray
se: np.ndarray
t_stat: np.ndarray
p_value: np.ndarray
conf_int_low: np.ndarray
conf_int_high: np.ndarray
n_obs_per_horizon: np.ndarray
# Shared metadata
alpha: float
design: str
target_parameter: str
d_lower: float
dose_mean: float
F: Any
n_units: int
inference_method: str
vcov_type: Optional[str]
cluster_name: Optional[str]
survey_metadata: Optional[SurveyMetadata]
# Per-horizon diagnostics (lists, None on mass-point).
# List entries may be None for horizons where the continuous-path fit
# caught a degenerate bandwidth-selector failure (constant / perfectly-
# linear outcome); att / se for those horizons are NaN as well.
bandwidth_diagnostics: Optional[List[Optional[BandwidthResult]]]
bias_corrected_fit: Optional[List[Optional[BiasCorrectedFit]]]
# Staggered auto-filter metadata
filter_info: Optional[Dict[str, Any]]
# Phase 4.5 B weighted / survey-path extras (optional so unweighted
# fits stay unchanged; all None on unweighted fits).
variance_formula: Optional[str] = None
"""Per-horizon variance family label (applied uniformly across all
horizons in the fit). One of ``"pweight"`` / ``"pweight_2sls"`` (when
a per-row weight array was supplied, including via the deprecated
``weights=`` alias; continuous / mass-point), ``"survey_binder_tsl"``
/ ``"survey_binder_tsl_2sls"`` (when a SurveyDesign was supplied via
``survey_design=`` or the deprecated ``survey=`` alias), or ``None``
on unweighted fits. Mirrors the static-path ``variance_formula``
field."""
effective_dose_mean: Optional[float] = None
"""Weighted denominator used by the β̂-scale rescaling. For continuous
designs: weighted ``sum(w · d)/sum(w)`` (continuous_at_zero) or
``sum(w · (d − d_lower))/sum(w)`` (continuous_near_d_lower). For
mass-point: weighted Wald-IV dose gap. ``None`` on unweighted fits."""
cband_low: Optional[np.ndarray] = None
"""Simultaneous confidence-band lower endpoints, shape ``(n_horizons,)``.
``None`` on unweighted fits and when ``cband=False`` on the weighted
event-study path. Derived from multiplier-bootstrap sup-t critical
value: ``cband_low[e] = att[e] − cband_crit_value * se[e]``."""
cband_high: Optional[np.ndarray] = None
"""Simultaneous confidence-band upper endpoints, shape
``(n_horizons,)``. See ``cband_low``."""
cband_crit_value: Optional[float] = None
"""Sup-t multiplier-bootstrap critical value at level ``1 - alpha``.
Reduces to ``Φ⁻¹(1 − alpha/2) ≈ 1.96`` at ``H=1`` up to Monte Carlo
error. ``None`` on unweighted fits and when ``cband=False``."""
cband_method: Optional[str] = None
"""``"multiplier_bootstrap"`` on the weighted event-study path with
``cband=True``, else ``None``."""
cband_n_bootstrap: Optional[int] = None
"""Number of multiplier-bootstrap replicates used to compute the sup-t
critical value. ``None`` on unweighted fits and when ``cband=False``."""
def __repr__(self) -> str:
base = (
f"HeterogeneousAdoptionDiDEventStudyResults("
f"n_horizons={len(self.event_times)}, "
f"design={self.design!r}, n_units={self.n_units}"
)
if self.variance_formula is not None:
base += f", variance_formula={self.variance_formula!r}"
if self.cband_crit_value is not None:
base += f", cband_crit={self.cband_crit_value:.3f}"
return base + ")"
def summary(self) -> str:
"""Formatted per-horizon summary table."""
width = 80
conf_level = int((1 - self.alpha) * 100)
lines = [
"=" * width,
"HeterogeneousAdoptionDiD Event-Study Results".center(width),
"=" * width,
"",
f"{'Design:':<30} {self.design:>20}",
f"{'Target parameter:':<30} {self.target_parameter:>20}",
f"{'d_lower:':<30} {self.d_lower:>20.6g}",
f"{'D_bar (dose mean):':<30} {self.dose_mean:>20.6g}",
f"{'First-treatment period (F):':<30} {str(self.F):>20}",
f"{'Observations (units):':<30} {self.n_units:>20}",
f"{'Horizons:':<30} {len(self.event_times):>20}",
f"{'Inference method:':<30} {self.inference_method:>20}",
]
if self.vcov_type is not None:
if self.cluster_name is not None:
label = f"CR1 at {self.cluster_name}"
else:
label = self.vcov_type
lines.append(f"{'Variance:':<30} {label:>20}")
if self.filter_info is not None:
lines.append(
f"{'Last-cohort filter (F_last):':<30} "
f"{str(self.filter_info.get('F_last')):>20}"
)
lines.append(
f"{' Units kept / dropped:':<30} "
f"{self.filter_info.get('n_kept', 0)} / "
f"{self.filter_info.get('n_dropped', 0):<8}".rjust(51)
)
if self.survey_metadata is not None:
sm = self.survey_metadata
vf_label = self.variance_formula or "unknown"
lines.append(f"{'Variance formula:':<30} {vf_label:>20}")
lines.append(f"{'Effective sample size:':<30} {sm.effective_n:>20.6g}")
if self.effective_dose_mean is not None:
lines.append(
f"{'Weighted D̄ (denominator):':<30} " f"{self.effective_dose_mean:>20.6g}"
)
if sm.df_survey is not None:
lines.append(f"{'Survey df:':<30} {sm.df_survey:>20}")
if self.cband_crit_value is not None:
lines.append(f"{'Sup-t crit (bootstrap):':<30} " f"{self.cband_crit_value:>20.4f}")
lines.append(f"{'Bootstrap replicates:':<30} " f"{self.cband_n_bootstrap or 0:>20}")
lines.extend(
[
"",
"-" * width,
(
f"{'Event-time':>10} {'Estimate':>12} {'Std. Err.':>12} "
f"{'t-stat':>10} {'P>|t|':>10} "
f"{str(conf_level) + '% CI':>22}"
),
"-" * width,
]
)
for i, e in enumerate(self.event_times):
ci_str = f"[{self.conf_int_low[i]:.4f}, {self.conf_int_high[i]:.4f}]"
# Default float formatting renders non-finite values as "nan";
# we do not override this here since the column width is fixed
# and lowercase "nan" is unambiguous.
se_i = self.se[i]
t_i = self.t_stat[i]
p_i = self.p_value[i]
lines.append(
f"{int(e):>10} {self.att[i]:>12.4f} "
f"{se_i:>12.4f} {t_i:>10.3f} {p_i:>10.4f} {ci_str:>22}"
)
lines.extend(
[
"-" * width,
"",
"=" * width,
]
)
return "\n".join(lines)
def print_summary(self) -> None:
"""Print the summary to stdout."""
print(self.summary())
def to_dict(self) -> Dict[str, Any]:
"""Return results as a dict with per-horizon arrays and scalars.
Per-horizon arrays are converted to Python lists via
``ndarray.tolist()`` (which unwraps NumPy scalar elements to
native ``int`` / ``float``); scalar fields are coerced to
native Python types via ``_json_safe_scalar`` where relevant
(NumPy scalars -> ``.item()``, pandas ``Timestamp`` -> ISO
string, ``Timedelta`` -> ISO string). The returned dict is
JSON-serializable directly via ``json.dumps``.
"""
return {
"event_times": self.event_times.tolist(),
"att": self.att.tolist(),
"se": self.se.tolist(),
"t_stat": self.t_stat.tolist(),
"p_value": self.p_value.tolist(),
"conf_int_low": self.conf_int_low.tolist(),
"conf_int_high": self.conf_int_high.tolist(),
"n_obs_per_horizon": self.n_obs_per_horizon.tolist(),
"alpha": float(self.alpha),
"design": self.design,
"target_parameter": self.target_parameter,
"d_lower": float(self.d_lower),
"dose_mean": float(self.dose_mean),
"F": _json_safe_scalar(self.F),
"n_units": int(self.n_units),
"inference_method": self.inference_method,
"vcov_type": self.vcov_type,
"cluster_name": self.cluster_name,
"filter_info": _json_safe_filter_info(self.filter_info),
# Phase 4.5 B weighted/survey-path surfaces (None on
# unweighted fits). The full SurveyMetadata dataclass is
# carried as an object, matching the static-path ``to_dict``
# contract — consumers read attributes uniformly.
"survey_metadata": self.survey_metadata,
"variance_formula": self.variance_formula,
"effective_dose_mean": self.effective_dose_mean,
"cband_low": (self.cband_low.tolist() if self.cband_low is not None else None),
"cband_high": (self.cband_high.tolist() if self.cband_high is not None else None),
"cband_crit_value": self.cband_crit_value,
"cband_method": self.cband_method,
"cband_n_bootstrap": self.cband_n_bootstrap,
}
def to_dataframe(self) -> pd.DataFrame:
"""Return a tidy per-horizon DataFrame.
Columns: ``event_time, att, se, t_stat, p_value, conf_int_low,
conf_int_high, n_obs``. One row per event-time horizon. On the
weighted event-study path with ``cband=True``, also includes
``cband_low`` and ``cband_high`` columns.
"""
data: Dict[str, Any] = {
"event_time": self.event_times,
"att": self.att,
"se": self.se,
"t_stat": self.t_stat,
"p_value": self.p_value,
"conf_int_low": self.conf_int_low,
"conf_int_high": self.conf_int_high,
"n_obs": self.n_obs_per_horizon,
}
if self.cband_low is not None:
data["cband_low"] = self.cband_low
if self.cband_high is not None:
data["cband_high"] = self.cband_high
return pd.DataFrame(data)
# =============================================================================
# Panel validation and aggregation
# =============================================================================
def _validate_had_panel(
data: pd.DataFrame,
outcome_col: str,
dose_col: str,
time_col: str,
unit_col: str,
first_treat_col: Optional[str],
) -> Tuple[int, int]:
"""Validate a HAD panel and return ``(t_pre, t_post)``.
Enforces the Phase 2a panel contract:
- All required columns present.
- Exactly two distinct time periods. Staggered timing (``>2`` periods)
with ``first_treat_col=None`` raises; with ``first_treat_col`` it
also raises (multi-period reduction is Phase 2b).
- Balanced panel (all units observed at both periods).
- ``D_{g, t_pre} == 0`` for all units (HAD no-unit-untreated pre-period).
- No NaN in outcome, dose, or unit columns.
Parameters
----------
data : pd.DataFrame
outcome_col, dose_col, time_col, unit_col : str
first_treat_col : str or None
Optional column for cross-validation. Supplied column must contain
``0`` for never-treated and the post-period value for treated units.
Returns
-------
tuple[Any, Any]
``(t_pre, t_post)`` - the two period identifiers identified by
the HAD dose invariant (``t_pre`` is the period with dose == 0
for all units; ``t_post`` is the other period). Supports
arbitrary-dtype period labels (int, str, datetime, etc.) rather
than relying on ordinal / lexicographic sort.
Raises
------
ValueError
"""
required = [outcome_col, dose_col, time_col, unit_col]
if first_treat_col is not None:
required.append(first_treat_col)
missing = [c for c in required if c not in data.columns]
if missing:
raise ValueError(f"Missing column(s) in data: {missing}. Required: {required}.")
periods_list = list(data[time_col].unique())
if len(periods_list) < 2:
raise ValueError(
f"HAD requires a two-period panel; got {len(periods_list)} distinct "
f"period(s) in column {time_col!r}."
)
if len(periods_list) > 2:
raise ValueError(
f"HAD with aggregate='overall' requires exactly two time "
f"periods (got {len(periods_list)} in {time_col!r}). For "
f"multi-period panels, pass aggregate='event_study' (paper "
f"Appendix B.2 multi-period event-study extension) which "
f"produces per-event-time WAS estimates."
)
# Balanced-panel check: every unit appears exactly once per period.
counts = data.groupby([unit_col, time_col]).size()
if (counts != 1).any():
n_bad = int((counts != 1).sum())
raise ValueError(
f"Unbalanced panel: {n_bad} unit-period cells have != 1 "
f"observation. HAD requires a balanced two-period panel "
f"(each unit observed exactly once at each period)."
)
unit_counts = data.groupby(unit_col)[time_col].nunique()
You can’t perform that action at this time.
