-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathtriple_diff.py
More file actions
1921 lines (1726 loc) · 72.4 KB
/
triple_diff.py
File metadata and controls
1921 lines (1726 loc) · 72.4 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
"""
Triple Difference (DDD) estimators.
Implements the methodology from Ortiz-Villavicencio & Sant'Anna (2025)
"Better Understanding Triple Differences Estimators" for causal inference
when treatment requires satisfying two criteria:
1. Belonging to a treated group (e.g., a state with a policy)
2. Being in an eligible partition (e.g., women, low-income, etc.)
This module provides regression adjustment, inverse probability weighting,
and doubly robust estimators that correctly handle covariate adjustment,
unlike naive implementations. Standard errors use the efficient influence
function: SE = std(IF) / sqrt(n), which is inherently heteroskedasticity-
robust. Cluster-robust SEs are available via the ``cluster`` parameter.
The DDD is computed via three pairwise DiD comparisons matching R's
``triplediff::ddd()`` package (panel=FALSE mode).
Reference:
Ortiz-Villavicencio, M., & Sant'Anna, P. H. C. (2025).
Better Understanding Triple Differences Estimators.
arXiv:2505.09942.
"""
import warnings
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from diff_diff.linalg import solve_logit, solve_ols
from diff_diff.results import _format_survey_block, _get_significance_stars
from diff_diff.utils import safe_inference
_MIN_CELL_SIZE = 10
# =============================================================================
# Results Classes
# =============================================================================
@dataclass
class TripleDifferenceResults:
"""
Results from Triple Difference (DDD) estimation.
Provides access to the estimated average treatment effect on the treated
(ATT), standard errors, confidence intervals, and diagnostic information.
Attributes
----------
att : float
Average Treatment effect on the Treated (ATT).
This is the effect on units in the treated group (G=1) and eligible
partition (P=1) after treatment (T=1).
se : float
Standard error of the ATT estimate.
t_stat : float
T-statistic for the ATT estimate.
p_value : float
P-value for the null hypothesis that ATT = 0.
conf_int : tuple[float, float]
Confidence interval for the ATT.
n_obs : int
Total number of observations used in estimation.
n_treated_eligible : int
Number of observations in treated group and eligible partition.
n_treated_ineligible : int
Number of observations in treated group and ineligible partition.
n_control_eligible : int
Number of observations in control group and eligible partition.
n_control_ineligible : int
Number of observations in control group and ineligible partition.
estimation_method : str
Estimation method used: "dr" (doubly robust), "reg" (regression
adjustment), or "ipw" (inverse probability weighting).
alpha : float
Significance level used for confidence intervals.
"""
att: float
se: float
t_stat: float
p_value: float
conf_int: Tuple[float, float]
n_obs: int
n_treated_eligible: int
n_treated_ineligible: int
n_control_eligible: int
n_control_ineligible: int
estimation_method: str
alpha: float = 0.05
# Group means for diagnostics
group_means: Optional[Dict[str, float]] = field(default=None)
# Propensity score diagnostics (for IPW/DR)
pscore_stats: Optional[Dict[str, float]] = field(default=None)
# Regression diagnostics
r_squared: Optional[float] = field(default=None)
# Covariate balance statistics
covariate_balance: Optional[pd.DataFrame] = field(default=None, repr=False)
# Inference details
inference_method: str = field(default="analytical")
n_bootstrap: Optional[int] = field(default=None)
n_clusters: Optional[int] = field(default=None)
# Survey design metadata (SurveyMetadata instance from diff_diff.survey)
survey_metadata: Optional[Any] = field(default=None)
def __repr__(self) -> str:
"""Concise string representation."""
return (
f"TripleDifferenceResults(ATT={self.att:.4f}{self.significance_stars}, "
f"SE={self.se:.4f}, p={self.p_value:.4f}, method={self.estimation_method})"
)
def summary(self, alpha: Optional[float] = None) -> str:
"""
Generate a formatted summary of the estimation results.
Parameters
----------
alpha : float, optional
Significance level for confidence intervals. Defaults to the
alpha used during estimation.
Returns
-------
str
Formatted summary table.
"""
alpha = alpha or self.alpha
conf_level = int((1 - alpha) * 100)
lines = [
"=" * 75,
"Triple Difference (DDD) Estimation Results".center(75),
"=" * 75,
"",
f"{'Estimation method:':<30} {self.estimation_method:>15}",
f"{'Total observations:':<30} {self.n_obs:>15}",
"",
"Sample Composition by Cell:",
f" {'Treated group, Eligible:':<28} {self.n_treated_eligible:>15}",
f" {'Treated group, Ineligible:':<28} {self.n_treated_ineligible:>15}",
f" {'Control group, Eligible:':<28} {self.n_control_eligible:>15}",
f" {'Control group, Ineligible:':<28} {self.n_control_ineligible:>15}",
]
if self.r_squared is not None:
lines.append(f"{'R-squared:':<30} {self.r_squared:>15.4f}")
# Add survey design info
if self.survey_metadata is not None:
sm = self.survey_metadata
lines.extend(_format_survey_block(sm, 75))
if self.inference_method != "analytical":
lines.append(f"{'Inference method:':<30} {self.inference_method:>15}")
if self.n_bootstrap is not None:
lines.append(f"{'Bootstrap replications:':<30} {self.n_bootstrap:>15}")
if self.n_clusters is not None:
lines.append(f"{'Number of clusters:':<30} {self.n_clusters:>15}")
lines.extend(
[
"",
"-" * 75,
f"{'Parameter':<15} {'Estimate':>12} {'Std. Err.':>12} {'t-stat':>10} {'P>|t|':>10} {'':>5}",
"-" * 75,
f"{'ATT':<15} {self.att:>12.4f} {self.se:>12.4f} {self.t_stat:>10.3f} {self.p_value:>10.4f} {self.significance_stars:>5}",
"-" * 75,
"",
f"{conf_level}% Confidence Interval: [{self.conf_int[0]:.4f}, {self.conf_int[1]:.4f}]",
]
)
# Show group means if available
if self.group_means:
lines.extend(
[
"",
"-" * 75,
"Cell Means (Y):",
"-" * 75,
]
)
for cell, mean in self.group_means.items():
lines.append(f" {cell:<35} {mean:>12.4f}")
# Show propensity score diagnostics if available
if self.pscore_stats:
lines.extend(
[
"",
"-" * 75,
"Propensity Score Diagnostics:",
"-" * 75,
]
)
for stat, value in self.pscore_stats.items():
lines.append(f" {stat:<35} {value:>12.4f}")
lines.extend(
[
"",
"Signif. codes: '***' 0.001, '**' 0.01, '*' 0.05, '.' 0.1",
"=" * 75,
]
)
return "\n".join(lines)
def print_summary(self, alpha: Optional[float] = None) -> None:
"""Print the summary to stdout."""
print(self.summary(alpha))
def to_dict(self) -> Dict[str, Any]:
"""
Convert results to a dictionary.
Returns
-------
Dict[str, Any]
Dictionary containing all estimation results.
"""
result = {
"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],
"n_obs": self.n_obs,
"n_treated_eligible": self.n_treated_eligible,
"n_treated_ineligible": self.n_treated_ineligible,
"n_control_eligible": self.n_control_eligible,
"n_control_ineligible": self.n_control_ineligible,
"estimation_method": self.estimation_method,
"inference_method": self.inference_method,
}
if self.r_squared is not None:
result["r_squared"] = self.r_squared
if self.n_bootstrap is not None:
result["n_bootstrap"] = self.n_bootstrap
if self.n_clusters is not None:
result["n_clusters"] = self.n_clusters
if self.survey_metadata is not None:
sm = self.survey_metadata
result["weight_type"] = sm.weight_type
result["effective_n"] = sm.effective_n
result["design_effect"] = sm.design_effect
result["sum_weights"] = sm.sum_weights
result["n_strata"] = sm.n_strata
result["n_psu"] = sm.n_psu
result["df_survey"] = sm.df_survey
return result
def to_dataframe(self) -> pd.DataFrame:
"""
Convert results to a pandas DataFrame.
Returns
-------
pd.DataFrame
DataFrame with estimation results.
"""
return pd.DataFrame([self.to_dict()])
@property
def is_significant(self) -> bool:
"""Check if the ATT is statistically significant at the alpha level."""
return bool(self.p_value < self.alpha)
@property
def significance_stars(self) -> str:
"""Return significance stars based on p-value."""
return _get_significance_stars(self.p_value)
# =============================================================================
# Helper Functions
# =============================================================================
# =============================================================================
# Main Estimator Class
# =============================================================================
class TripleDifference:
"""
Triple Difference (DDD) estimator.
Estimates the Average Treatment effect on the Treated (ATT) when treatment
requires satisfying two criteria: belonging to a treated group AND being
in an eligible partition of the population.
This implementation follows Ortiz-Villavicencio & Sant'Anna (2025), which
shows that naive DDD implementations (difference of two DiDs, three-way
fixed effects) are invalid when covariates are needed for identification.
Parameters
----------
estimation_method : str, default="dr"
Estimation method to use:
- "dr": Doubly robust (recommended). Consistent if either the outcome
model or propensity score model is correctly specified.
- "reg": Regression adjustment (outcome regression).
- "ipw": Inverse probability weighting.
robust : bool, default=True
Whether to use heteroskedasticity-robust standard errors.
Note: influence function-based SEs are inherently robust to
heteroskedasticity, so this parameter has no effect. Retained
for API compatibility.
cluster : str, optional
Column name for cluster-robust standard errors. When provided,
SEs are computed using the Liang-Zeger cluster-robust variance
estimator on the influence function.
alpha : float, default=0.05
Significance level for confidence intervals.
pscore_trim : float, default=0.01
Trimming threshold for propensity scores. Scores below this value
or above (1 - pscore_trim) are clipped to avoid extreme weights.
rank_deficient_action : str, default="warn"
Action when design matrix is rank-deficient (linearly dependent columns):
- "warn": Issue warning and drop linearly dependent columns (default)
- "error": Raise ValueError
- "silent": Drop columns silently without warning
Attributes
----------
results_ : TripleDifferenceResults
Estimation results after calling fit().
is_fitted_ : bool
Whether the model has been fitted.
Examples
--------
Basic usage with a DataFrame:
>>> import pandas as pd
>>> from diff_diff import TripleDifference
>>>
>>> # Data where treatment affects women (partition=1) in states
>>> # that enacted a policy (group=1)
>>> data = pd.DataFrame({
... 'outcome': [...],
... 'group': [1, 1, 0, 0, ...], # 1=policy state, 0=control state
... 'partition': [1, 0, 1, 0, ...], # 1=women, 0=men
... 'post': [0, 0, 1, 1, ...], # 1=post-treatment period
... })
>>>
>>> # Fit using doubly robust estimation
>>> ddd = TripleDifference(estimation_method="dr")
>>> results = ddd.fit(
... data,
... outcome='outcome',
... group='group',
... partition='partition',
... time='post'
... )
>>> print(results.att) # ATT estimate
With covariates (properly handled unlike naive DDD):
>>> results = ddd.fit(
... data,
... outcome='outcome',
... group='group',
... partition='partition',
... time='post',
... covariates=['age', 'income']
... )
Notes
-----
The DDD estimator is appropriate when:
1. Treatment affects only units satisfying BOTH criteria:
- Belonging to a treated group (G=1), e.g., states with a policy
- Being in an eligible partition (P=1), e.g., women, low-income
2. The DDD parallel trends assumption holds: the differential trend
between eligible and ineligible partitions would have been the same
across treated and control groups, absent treatment.
This is weaker than requiring separate parallel trends for two DiDs,
as biases can cancel out in the differencing.
References
----------
.. [1] Ortiz-Villavicencio, M., & Sant'Anna, P. H. C. (2025).
Better Understanding Triple Differences Estimators.
arXiv:2505.09942.
.. [2] Gruber, J. (1994). The incidence of mandated maternity benefits.
American Economic Review, 84(3), 622-641.
"""
def __init__(
self,
estimation_method: str = "dr",
robust: bool = True,
cluster: Optional[str] = None,
alpha: float = 0.05,
pscore_trim: float = 0.01,
rank_deficient_action: str = "warn",
):
if estimation_method not in ("dr", "reg", "ipw"):
raise ValueError(
f"estimation_method must be 'dr', 'reg', or 'ipw', " f"got '{estimation_method}'"
)
if rank_deficient_action not in ["warn", "error", "silent"]:
raise ValueError(
f"rank_deficient_action must be 'warn', 'error', or 'silent', "
f"got '{rank_deficient_action}'"
)
self.estimation_method = estimation_method
self.robust = robust
self.cluster = cluster
self.alpha = alpha
self.pscore_trim = pscore_trim
self.rank_deficient_action = rank_deficient_action
self.is_fitted_ = False
self.results_: Optional[TripleDifferenceResults] = None
def fit(
self,
data: pd.DataFrame,
outcome: str,
group: str,
partition: str,
time: str,
covariates: Optional[List[str]] = None,
survey_design=None,
) -> TripleDifferenceResults:
"""
Fit the Triple Difference model.
Parameters
----------
data : pd.DataFrame
DataFrame containing all variables.
outcome : str
Name of the outcome variable column.
group : str
Name of the group indicator column (0/1).
1 = treated group (e.g., states that enacted policy).
0 = control group.
partition : str
Name of the partition/eligibility indicator column (0/1).
1 = eligible partition (e.g., women, targeted demographic).
0 = ineligible partition.
time : str
Name of the time period indicator column (0/1).
1 = post-treatment period.
0 = pre-treatment period.
covariates : list of str, optional
List of covariate column names to adjust for.
These are properly incorporated using the selected estimation
method (unlike naive DDD implementations).
survey_design : SurveyDesign, optional
Survey design specification for complex survey data. When
provided, uses survey weights for estimation and Taylor Series
Linearization (TSL) for variance estimation. Supported with
all estimation methods ("reg", "ipw", "dr").
Returns
-------
TripleDifferenceResults
Object containing estimation results.
Raises
------
ValueError
If required columns are missing or data validation fails.
NotImplementedError
If survey_design is used with wild_bootstrap inference.
"""
# Reset replicate state from any previous fit
self._replicate_n_valid = None
# Resolve survey design if provided
from diff_diff.survey import (
_inject_cluster_as_psu,
_resolve_effective_cluster,
_resolve_survey_for_fit,
compute_survey_metadata,
)
resolved_survey, survey_weights, survey_weight_type, survey_metadata = (
_resolve_survey_for_fit(survey_design, data, "analytical")
)
if resolved_survey is not None and resolved_survey.weight_type != "pweight":
raise ValueError(
f"TripleDifference survey support requires weight_type='pweight', "
f"got '{resolved_survey.weight_type}'. The survey variance math "
f"assumes probability weights (pweight)."
)
# Validate inputs
self._validate_data(data, outcome, group, partition, time, covariates)
# Extract data
y = data[outcome].values.astype(float)
G = data[group].values.astype(float)
P = data[partition].values.astype(float)
T = data[time].values.astype(float)
# Store cluster IDs for SE computation
self._cluster_ids = data[self.cluster].values if self.cluster is not None else None
if self._cluster_ids is not None and np.any(pd.isna(data[self.cluster])):
raise ValueError(f"Cluster column '{self.cluster}' contains missing values")
# Resolve effective cluster and inject cluster-as-PSU for survey variance
if resolved_survey is not None:
effective_cluster_ids = _resolve_effective_cluster(
resolved_survey, self._cluster_ids, self.cluster
)
if effective_cluster_ids is not None:
resolved_survey = _inject_cluster_as_psu(resolved_survey, effective_cluster_ids)
if resolved_survey.psu is not None and survey_metadata is not None:
raw_w = (
data[survey_design.weights].values.astype(np.float64)
if survey_design.weights
else np.ones(len(data), dtype=np.float64)
)
survey_metadata = compute_survey_metadata(resolved_survey, raw_w)
# Get covariates if specified
X = None
if covariates:
X = data[covariates].values.astype(float)
if np.any(np.isnan(X)):
raise ValueError("Covariates contain missing values")
# Count observations in each cell
n_obs = len(y)
n_treated_eligible = int(np.sum((G == 1) & (P == 1)))
n_treated_ineligible = int(np.sum((G == 1) & (P == 0)))
n_control_eligible = int(np.sum((G == 0) & (P == 1)))
n_control_ineligible = int(np.sum((G == 0) & (P == 0)))
# Compute cell means for diagnostics
group_means = self._compute_cell_means(y, G, P, T, weights=survey_weights)
# Estimate ATT based on method
if self.estimation_method == "reg":
att, se, r_squared, pscore_stats = self._regression_adjustment(
y,
G,
P,
T,
X,
survey_weights=survey_weights,
resolved_survey=resolved_survey,
)
elif self.estimation_method == "ipw":
att, se, r_squared, pscore_stats = self._ipw_estimation(
y,
G,
P,
T,
X,
survey_weights=survey_weights,
resolved_survey=resolved_survey,
)
else: # doubly robust
att, se, r_squared, pscore_stats = self._doubly_robust(
y,
G,
P,
T,
X,
survey_weights=survey_weights,
resolved_survey=resolved_survey,
)
# Compute inference
# When survey design is active, use survey df (n_PSU - n_strata)
if survey_metadata is not None and survey_metadata.df_survey is not None:
df = survey_metadata.df_survey
# Override with effective replicate df only when replicates were dropped
if (hasattr(self, '_replicate_n_valid') and self._replicate_n_valid is not None
and resolved_survey is not None
and self._replicate_n_valid < resolved_survey.n_replicates):
df = self._replicate_n_valid - 1
survey_metadata.df_survey = self._replicate_n_valid - 1
# df <= 0 means insufficient rank for t-based inference
if df is not None and df <= 0:
df = 0 # Forces NaN from t-distribution
elif (resolved_survey is not None
and hasattr(resolved_survey, 'uses_replicate_variance')
and resolved_survey.uses_replicate_variance):
# Replicate design with undefined df (rank <= 1) — NaN inference
df = 0 # Forces NaN from t-distribution
else:
df = n_obs - 8 # Approximate df (8 cell means)
if covariates:
df -= len(covariates)
df = max(df, 1)
t_stat, p_value, conf_int = safe_inference(att, se, alpha=self.alpha, df=df)
# Get number of clusters if clustering
n_clusters = None
if self.cluster is not None:
n_clusters = data[self.cluster].nunique()
# Create results object
self.results_ = TripleDifferenceResults(
att=att,
se=se,
t_stat=t_stat,
p_value=p_value,
conf_int=conf_int,
n_obs=n_obs,
n_treated_eligible=n_treated_eligible,
n_treated_ineligible=n_treated_ineligible,
n_control_eligible=n_control_eligible,
n_control_ineligible=n_control_ineligible,
estimation_method=self.estimation_method,
alpha=self.alpha,
group_means=group_means,
pscore_stats=pscore_stats,
r_squared=r_squared,
inference_method="analytical",
n_clusters=n_clusters,
survey_metadata=survey_metadata,
)
self.is_fitted_ = True
return self.results_
def _validate_data(
self,
data: pd.DataFrame,
outcome: str,
group: str,
partition: str,
time: str,
covariates: Optional[List[str]] = None,
) -> None:
"""Validate input data."""
if not isinstance(data, pd.DataFrame):
raise TypeError("data must be a pandas DataFrame")
# Check required columns exist
required_cols = [outcome, group, partition, time]
if covariates:
required_cols.extend(covariates)
if self.cluster is not None:
required_cols.append(self.cluster)
missing_cols = [col for col in required_cols if col not in data.columns]
if missing_cols:
raise ValueError(f"Missing columns in data: {missing_cols}")
# Check for missing values in required columns
for col in [outcome, group, partition, time]:
if data[col].isna().any():
raise ValueError(f"Column '{col}' contains missing values")
# Validate binary variables
for col, name in [(group, "group"), (partition, "partition"), (time, "time")]:
unique_vals = set(data[col].unique())
if not unique_vals.issubset({0, 1, 0.0, 1.0}):
raise ValueError(
f"'{name}' column must be binary (0/1), " f"got values: {sorted(unique_vals)}"
)
if len(unique_vals) < 2:
raise ValueError(f"'{name}' column must have both 0 and 1 values")
# Check we have observations in all cells
G = data[group].values
P = data[partition].values
T = data[time].values
cells = [
((G == 1) & (P == 1) & (T == 0), "treated, eligible, pre"),
((G == 1) & (P == 1) & (T == 1), "treated, eligible, post"),
((G == 1) & (P == 0) & (T == 0), "treated, ineligible, pre"),
((G == 1) & (P == 0) & (T == 1), "treated, ineligible, post"),
((G == 0) & (P == 1) & (T == 0), "control, eligible, pre"),
((G == 0) & (P == 1) & (T == 1), "control, eligible, post"),
((G == 0) & (P == 0) & (T == 0), "control, ineligible, pre"),
((G == 0) & (P == 0) & (T == 1), "control, ineligible, post"),
]
for mask, cell_name in cells:
n_cell = int(np.sum(mask))
if n_cell == 0:
raise ValueError(
f"No observations in cell: {cell_name}. "
"DDD requires observations in all 8 cells."
)
elif n_cell < _MIN_CELL_SIZE:
warnings.warn(
f"Low observation count ({n_cell}) in cell: {cell_name}. "
f"Estimates may be unreliable with fewer than "
f"{_MIN_CELL_SIZE} observations per cell.",
UserWarning,
stacklevel=2,
)
def _compute_cell_means(
self,
y: np.ndarray,
G: np.ndarray,
P: np.ndarray,
T: np.ndarray,
weights: Optional[np.ndarray] = None,
) -> Dict[str, float]:
"""Compute mean outcomes for each of the 8 DDD cells."""
means = {}
for g_val, g_name in [(1, "Treated"), (0, "Control")]:
for p_val, p_name in [(1, "Eligible"), (0, "Ineligible")]:
for t_val, t_name in [(0, "Pre"), (1, "Post")]:
mask = (G == g_val) & (P == p_val) & (T == t_val)
cell_name = f"{g_name}, {p_name}, {t_name}"
if weights is not None:
w_cell = weights[mask]
if np.sum(w_cell) <= 0:
raise ValueError(
f"Cell '{cell_name}' has zero effective survey "
f"weight. Cannot compute weighted cell mean. "
f"Check subpopulation/domain definition."
)
means[cell_name] = float(np.average(y[mask], weights=w_cell))
else:
means[cell_name] = float(np.mean(y[mask]))
return means
# =========================================================================
# Three-DiD Decomposition (matches R's triplediff::ddd())
# =========================================================================
#
# The DDD is decomposed into three pairwise DiD comparisons:
# DiD_3: subgroup 3 (G=1,P=0) vs subgroup 4 (G=1,P=1)
# DiD_2: subgroup 2 (G=0,P=1) vs subgroup 4 (G=1,P=1)
# DiD_1: subgroup 1 (G=0,P=0) vs subgroup 4 (G=1,P=1)
#
# DDD = DiD_3 + DiD_2 - DiD_1
#
# Each DiD uses the selected estimation method (DR, IPW, or RA).
# SE is computed from the combined influence function:
# inf = w3*inf_3 + w2*inf_2 - w1*inf_1
# SE = std(inf, ddof=1) / sqrt(n)
#
# Reference: Ortiz-Villavicencio & Sant'Anna (2025), implemented in
# R's triplediff::ddd() with panel=FALSE (repeated cross-section).
# =========================================================================
def _regression_adjustment(
self,
y: np.ndarray,
G: np.ndarray,
P: np.ndarray,
T: np.ndarray,
X: Optional[np.ndarray],
survey_weights: Optional[np.ndarray] = None,
resolved_survey=None,
) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]]]:
"""
Estimate ATT using regression adjustment via three-DiD decomposition.
For each pairwise comparison (subgroup j vs subgroup 4), fits
separate outcome models per subgroup-time cell and computes
imputed counterfactual means. Matches R's triplediff::ddd()
with est_method="reg".
"""
return self._estimate_ddd_decomposition(
y,
G,
P,
T,
X,
survey_weights=survey_weights,
resolved_survey=resolved_survey,
)
def _ipw_estimation(
self,
y: np.ndarray,
G: np.ndarray,
P: np.ndarray,
T: np.ndarray,
X: Optional[np.ndarray],
survey_weights: Optional[np.ndarray] = None,
resolved_survey=None,
) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]]]:
"""
Estimate ATT using inverse probability weighting via three-DiD
decomposition.
For each pairwise comparison, estimates propensity scores for
subgroup membership P(subgroup=4|X) within {j, 4} subset.
Matches R's triplediff::ddd() with est_method="ipw".
"""
return self._estimate_ddd_decomposition(
y,
G,
P,
T,
X,
survey_weights=survey_weights,
resolved_survey=resolved_survey,
)
def _doubly_robust(
self,
y: np.ndarray,
G: np.ndarray,
P: np.ndarray,
T: np.ndarray,
X: Optional[np.ndarray],
survey_weights: Optional[np.ndarray] = None,
resolved_survey=None,
) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]]]:
"""
Estimate ATT using doubly robust estimation via three-DiD
decomposition.
Combines outcome regression and IPW for robustness: consistent
if either the outcome model or propensity score model is
correctly specified. Matches R's triplediff::ddd() with
est_method="dr".
"""
return self._estimate_ddd_decomposition(
y,
G,
P,
T,
X,
survey_weights=survey_weights,
resolved_survey=resolved_survey,
)
def _estimate_ddd_decomposition(
self,
y: np.ndarray,
G: np.ndarray,
P: np.ndarray,
T: np.ndarray,
X: Optional[np.ndarray],
survey_weights: Optional[np.ndarray] = None,
resolved_survey=None,
) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]]]:
"""
Core DDD estimation via three-DiD decomposition.
Implements the methodology from Ortiz-Villavicencio & Sant'Anna
(2025), matching R's triplediff::ddd() for repeated cross-section
data (panel=FALSE).
The DDD is decomposed into three pairwise DiD comparisons,
each using the selected estimation method (DR, IPW, or RA):
DDD = DiD_3 + DiD_2 - DiD_1
Standard errors use the efficient influence function:
SE = std(w3*IF_3 + w2*IF_2 - w1*IF_1) / sqrt(n)
When resolved_survey is provided, survey-weighted SE is computed
using TSL on the combined influence function.
"""
n = len(y)
est_method = self.estimation_method
# Assign subgroups following R convention:
# 4: G=1, P=1 (treated, eligible - reference/"treated")
# 3: G=1, P=0 (treated, ineligible)
# 2: G=0, P=1 (control, eligible)
# 1: G=0, P=0 (control, ineligible)
subgroup = np.zeros(n, dtype=int)
subgroup[(G == 1) & (P == 1)] = 4
subgroup[(G == 1) & (P == 0)] = 3
subgroup[(G == 0) & (P == 1)] = 2
subgroup[(G == 0) & (P == 0)] = 1
post = T.astype(float)
# Covariate matrix (always includes intercept)
if X is not None and X.shape[1] > 0:
covX = np.column_stack([np.ones(n), X])
has_covariates = True
else:
covX = np.ones((n, 1))
has_covariates = False
# Three DiD comparisons: j vs 4 for j in {3, 2, 1}
did_results = {}
pscore_stats = None
all_pscores = {} # Collect pscores for diagnostics
overlap_issues = [] # Collect overlap diagnostics across comparisons
any_nonfinite_if = False
with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
for j in [3, 2, 1]:
mask = (subgroup == j) | (subgroup == 4)
y_sub = y[mask]
post_sub = post[mask]
sg_sub = subgroup[mask]
covX_sub = covX[mask]
n_sub = len(y_sub)
PA4 = (sg_sub == 4).astype(float)
PAa = (sg_sub == j).astype(float)
# Subset survey weights for this comparison (needed for logit)
w_sub = survey_weights[mask] if survey_weights is not None else None
# --- Propensity scores ---
if est_method == "reg":
# RA: no propensity scores needed
pscore_sub = np.ones(n_sub)
hessian = None
elif has_covariates:
# Logistic regression: P(subgroup=4 | X) within {j, 4}
ps_estimated = True
try:
_, pscore_sub = solve_logit(
covX_sub[:, 1:],
PA4,
rank_deficient_action=self.rank_deficient_action,
weights=w_sub,
)
except Exception:
if self.rank_deficient_action == "error":
raise
pscore_sub = np.full(n_sub, np.mean(PA4))
ps_estimated = False
warnings.warn(
f"Propensity score estimation failed for subgroup "
f"{j} vs 4; using unconditional probability. "
f"SEs may be less efficient.",
UserWarning,
stacklevel=3,
)
pscore_sub = np.clip(pscore_sub, self.pscore_trim, 1 - self.pscore_trim)
all_pscores[j] = pscore_sub
# Check overlap: count obs at trim bounds
# (1e-10 tolerance for floating-point after np.clip)
n_trimmed = int(
np.sum(
(pscore_sub <= self.pscore_trim + 1e-10)
| (pscore_sub >= 1 - self.pscore_trim - 1e-10)
)
)
frac_trimmed = n_trimmed / len(pscore_sub)
if frac_trimmed > 0.05:
overlap_issues.append((j, frac_trimmed))
# Hessian only when PS was actually estimated
if ps_estimated:
W_ps = pscore_sub * (1 - pscore_sub)
if w_sub is not None:
W_ps = W_ps * w_sub
try:
XWX = covX_sub.T @ (W_ps[:, None] * covX_sub)
hessian = np.linalg.inv(XWX) * n_sub
except np.linalg.LinAlgError:
hessian = np.linalg.pinv(XWX) * n_sub
else:
hessian = None
else:
# No covariates: unconditional probability
pscore_sub = np.full(n_sub, np.mean(PA4))
pscore_sub = np.clip(pscore_sub, self.pscore_trim, 1 - self.pscore_trim)
# Check overlap (same logic as covariate branch)
n_trimmed = int(
np.sum(
(pscore_sub <= self.pscore_trim + 1e-10)
| (pscore_sub >= 1 - self.pscore_trim - 1e-10)
)
)
frac_trimmed = n_trimmed / len(pscore_sub)
if frac_trimmed > 0.05:
overlap_issues.append((j, frac_trimmed))
hessian = None
# --- Outcome regression ---
if est_method == "ipw":
# IPW: no outcome regression
or_ctrl_pre = np.zeros(n_sub)
or_ctrl_post = np.zeros(n_sub)
or_trt_pre = np.zeros(n_sub)
or_trt_post = np.zeros(n_sub)
else:
# Fit separate OLS per subgroup-time cell, predict for all
or_ctrl_pre = self._fit_predict_mu(
y_sub,
covX_sub,
sg_sub == j,
post_sub == 0,
n_sub,
weights=w_sub,