diff-diff 3.0.1__cp314-cp314-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. diff_diff/__init__.py +382 -0
  2. diff_diff/_backend.py +134 -0
  3. diff_diff/_rust_backend.cp314-win_amd64.pyd +0 -0
  4. diff_diff/bacon.py +1140 -0
  5. diff_diff/bootstrap_utils.py +730 -0
  6. diff_diff/continuous_did.py +1626 -0
  7. diff_diff/continuous_did_bspline.py +190 -0
  8. diff_diff/continuous_did_results.py +374 -0
  9. diff_diff/datasets.py +815 -0
  10. diff_diff/diagnostics.py +882 -0
  11. diff_diff/efficient_did.py +1770 -0
  12. diff_diff/efficient_did_bootstrap.py +359 -0
  13. diff_diff/efficient_did_covariates.py +899 -0
  14. diff_diff/efficient_did_results.py +368 -0
  15. diff_diff/efficient_did_weights.py +617 -0
  16. diff_diff/estimators.py +1501 -0
  17. diff_diff/honest_did.py +2585 -0
  18. diff_diff/imputation.py +2458 -0
  19. diff_diff/imputation_bootstrap.py +418 -0
  20. diff_diff/imputation_results.py +448 -0
  21. diff_diff/linalg.py +2538 -0
  22. diff_diff/power.py +2588 -0
  23. diff_diff/practitioner.py +869 -0
  24. diff_diff/prep.py +1738 -0
  25. diff_diff/prep_dgp.py +1718 -0
  26. diff_diff/pretrends.py +1105 -0
  27. diff_diff/results.py +918 -0
  28. diff_diff/stacked_did.py +1049 -0
  29. diff_diff/stacked_did_results.py +339 -0
  30. diff_diff/staggered.py +3895 -0
  31. diff_diff/staggered_aggregation.py +864 -0
  32. diff_diff/staggered_bootstrap.py +752 -0
  33. diff_diff/staggered_results.py +416 -0
  34. diff_diff/staggered_triple_diff.py +1545 -0
  35. diff_diff/staggered_triple_diff_results.py +416 -0
  36. diff_diff/sun_abraham.py +1685 -0
  37. diff_diff/survey.py +1981 -0
  38. diff_diff/synthetic_did.py +1136 -0
  39. diff_diff/triple_diff.py +2047 -0
  40. diff_diff/trop.py +952 -0
  41. diff_diff/trop_global.py +1270 -0
  42. diff_diff/trop_local.py +1307 -0
  43. diff_diff/trop_results.py +356 -0
  44. diff_diff/twfe.py +542 -0
  45. diff_diff/two_stage.py +1952 -0
  46. diff_diff/two_stage_bootstrap.py +520 -0
  47. diff_diff/two_stage_results.py +400 -0
  48. diff_diff/utils.py +1902 -0
  49. diff_diff/visualization/__init__.py +61 -0
  50. diff_diff/visualization/_common.py +328 -0
  51. diff_diff/visualization/_continuous.py +274 -0
  52. diff_diff/visualization/_diagnostic.py +817 -0
  53. diff_diff/visualization/_event_study.py +1086 -0
  54. diff_diff/visualization/_power.py +661 -0
  55. diff_diff/visualization/_staggered.py +833 -0
  56. diff_diff/visualization/_synthetic.py +197 -0
  57. diff_diff/wooldridge.py +1285 -0
  58. diff_diff/wooldridge_results.py +349 -0
  59. diff_diff-3.0.1.dist-info/METADATA +2997 -0
  60. diff_diff-3.0.1.dist-info/RECORD +62 -0
  61. diff_diff-3.0.1.dist-info/WHEEL +4 -0
  62. diff_diff-3.0.1.dist-info/sboms/diff_diff_rust.cyclonedx.json +5843 -0
@@ -0,0 +1,2047 @@
1
+ """
2
+ Triple Difference (DDD) estimators.
3
+
4
+ Implements the methodology from Ortiz-Villavicencio & Sant'Anna (2025)
5
+ "Better Understanding Triple Differences Estimators" for causal inference
6
+ when treatment requires satisfying two criteria:
7
+ 1. Belonging to a treated group (e.g., a state with a policy)
8
+ 2. Being in an eligible partition (e.g., women, low-income, etc.)
9
+
10
+ This module provides regression adjustment, inverse probability weighting,
11
+ and doubly robust estimators that correctly handle covariate adjustment,
12
+ unlike naive implementations. Standard errors use the efficient influence
13
+ function: SE = std(IF) / sqrt(n), which is inherently heteroskedasticity-
14
+ robust. Cluster-robust SEs are available via the ``cluster`` parameter.
15
+
16
+ The DDD is computed via three pairwise DiD comparisons matching R's
17
+ ``triplediff::ddd()`` package (panel=FALSE mode).
18
+
19
+ Reference:
20
+ Ortiz-Villavicencio, M., & Sant'Anna, P. H. C. (2025).
21
+ Better Understanding Triple Differences Estimators.
22
+ arXiv:2505.09942.
23
+ """
24
+
25
+ import warnings
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, List, Optional, Tuple
28
+
29
+ import numpy as np
30
+ import pandas as pd
31
+
32
+ from diff_diff.linalg import solve_logit, solve_ols
33
+ from diff_diff.results import _format_survey_block, _get_significance_stars
34
+ from diff_diff.utils import safe_inference
35
+
36
+ _MIN_CELL_SIZE = 10
37
+
38
+ # =============================================================================
39
+ # Results Classes
40
+ # =============================================================================
41
+
42
+
43
+ @dataclass
44
+ class TripleDifferenceResults:
45
+ """
46
+ Results from Triple Difference (DDD) estimation.
47
+
48
+ Provides access to the estimated average treatment effect on the treated
49
+ (ATT), standard errors, confidence intervals, and diagnostic information.
50
+
51
+ Attributes
52
+ ----------
53
+ att : float
54
+ Average Treatment effect on the Treated (ATT).
55
+ This is the effect on units in the treated group (G=1) and eligible
56
+ partition (P=1) after treatment (T=1).
57
+ se : float
58
+ Standard error of the ATT estimate.
59
+ t_stat : float
60
+ T-statistic for the ATT estimate.
61
+ p_value : float
62
+ P-value for the null hypothesis that ATT = 0.
63
+ conf_int : tuple[float, float]
64
+ Confidence interval for the ATT.
65
+ n_obs : int
66
+ Total number of observations used in estimation.
67
+ n_treated_eligible : int
68
+ Number of observations in treated group and eligible partition.
69
+ n_treated_ineligible : int
70
+ Number of observations in treated group and ineligible partition.
71
+ n_control_eligible : int
72
+ Number of observations in control group and eligible partition.
73
+ n_control_ineligible : int
74
+ Number of observations in control group and ineligible partition.
75
+ estimation_method : str
76
+ Estimation method used: "dr" (doubly robust), "reg" (regression
77
+ adjustment), or "ipw" (inverse probability weighting).
78
+ alpha : float
79
+ Significance level used for confidence intervals.
80
+ """
81
+
82
+ att: float
83
+ se: float
84
+ t_stat: float
85
+ p_value: float
86
+ conf_int: Tuple[float, float]
87
+ n_obs: int
88
+ n_treated_eligible: int
89
+ n_treated_ineligible: int
90
+ n_control_eligible: int
91
+ n_control_ineligible: int
92
+ estimation_method: str
93
+ alpha: float = 0.05
94
+ # Group means for diagnostics
95
+ group_means: Optional[Dict[str, float]] = field(default=None)
96
+ # Propensity score diagnostics (for IPW/DR)
97
+ pscore_stats: Optional[Dict[str, float]] = field(default=None)
98
+ # Regression diagnostics
99
+ r_squared: Optional[float] = field(default=None)
100
+ # Covariate balance statistics
101
+ covariate_balance: Optional[pd.DataFrame] = field(default=None, repr=False)
102
+ # Inference details
103
+ inference_method: str = field(default="analytical")
104
+ n_bootstrap: Optional[int] = field(default=None)
105
+ n_clusters: Optional[int] = field(default=None)
106
+ # Survey design metadata (SurveyMetadata instance from diff_diff.survey)
107
+ survey_metadata: Optional[Any] = field(default=None)
108
+ # EPV diagnostics per subgroup comparison
109
+ epv_diagnostics: Optional[Dict[int, Dict[str, Any]]] = field(
110
+ default=None, repr=False
111
+ )
112
+ epv_threshold: float = 10
113
+ pscore_fallback: str = "error"
114
+
115
+ def __repr__(self) -> str:
116
+ """Concise string representation."""
117
+ return (
118
+ f"TripleDifferenceResults(ATT={self.att:.4f}{self.significance_stars}, "
119
+ f"SE={self.se:.4f}, p={self.p_value:.4f}, method={self.estimation_method})"
120
+ )
121
+
122
+ def summary(self, alpha: Optional[float] = None) -> str:
123
+ """
124
+ Generate a formatted summary of the estimation results.
125
+
126
+ Parameters
127
+ ----------
128
+ alpha : float, optional
129
+ Significance level for confidence intervals. Defaults to the
130
+ alpha used during estimation.
131
+
132
+ Returns
133
+ -------
134
+ str
135
+ Formatted summary table.
136
+ """
137
+ alpha = alpha or self.alpha
138
+ conf_level = int((1 - alpha) * 100)
139
+
140
+ lines = [
141
+ "=" * 75,
142
+ "Triple Difference (DDD) Estimation Results".center(75),
143
+ "=" * 75,
144
+ "",
145
+ f"{'Estimation method:':<30} {self.estimation_method:>15}",
146
+ f"{'Total observations:':<30} {self.n_obs:>15}",
147
+ "",
148
+ "Sample Composition by Cell:",
149
+ f" {'Treated group, Eligible:':<28} {self.n_treated_eligible:>15}",
150
+ f" {'Treated group, Ineligible:':<28} {self.n_treated_ineligible:>15}",
151
+ f" {'Control group, Eligible:':<28} {self.n_control_eligible:>15}",
152
+ f" {'Control group, Ineligible:':<28} {self.n_control_ineligible:>15}",
153
+ ]
154
+
155
+ if self.r_squared is not None:
156
+ lines.append(f"{'R-squared:':<30} {self.r_squared:>15.4f}")
157
+
158
+ # Add survey design info
159
+ if self.survey_metadata is not None:
160
+ sm = self.survey_metadata
161
+ lines.extend(_format_survey_block(sm, 75))
162
+
163
+ if self.inference_method != "analytical":
164
+ lines.append(f"{'Inference method:':<30} {self.inference_method:>15}")
165
+ if self.n_bootstrap is not None:
166
+ lines.append(f"{'Bootstrap replications:':<30} {self.n_bootstrap:>15}")
167
+ if self.n_clusters is not None:
168
+ lines.append(f"{'Number of clusters:':<30} {self.n_clusters:>15}")
169
+
170
+ lines.extend(
171
+ [
172
+ "",
173
+ "-" * 75,
174
+ f"{'Parameter':<15} {'Estimate':>12} {'Std. Err.':>12} {'t-stat':>10} {'P>|t|':>10} {'':>5}",
175
+ "-" * 75,
176
+ 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}",
177
+ "-" * 75,
178
+ "",
179
+ f"{conf_level}% Confidence Interval: [{self.conf_int[0]:.4f}, {self.conf_int[1]:.4f}]",
180
+ ]
181
+ )
182
+
183
+ # EPV diagnostics block (if any subgroup has low EPV)
184
+ if self.epv_diagnostics:
185
+ low_epv = {k: v for k, v in self.epv_diagnostics.items() if v.get("is_low")}
186
+ if low_epv:
187
+ n_affected = len(low_epv)
188
+ n_total = len(self.epv_diagnostics)
189
+ min_entry = min(low_epv.values(), key=lambda v: v["epv"])
190
+ lines.extend(
191
+ [
192
+ "",
193
+ "-" * 75,
194
+ "EPV Diagnostics".center(75),
195
+ "-" * 75,
196
+ f"WARNING: Low Events Per Variable (EPV) in "
197
+ f"{n_affected} of {n_total} subgroup comparison(s).",
198
+ f"Minimum EPV: {min_entry['epv']:.1f}. "
199
+ f"Threshold: {self.epv_threshold:.0f}.",
200
+ "Consider: estimation_method='reg' or fewer covariates.",
201
+ "Call results.epv_summary() for details.",
202
+ "-" * 75,
203
+ ]
204
+ )
205
+
206
+ # Show group means if available
207
+ if self.group_means:
208
+ lines.extend(
209
+ [
210
+ "",
211
+ "-" * 75,
212
+ "Cell Means (Y):",
213
+ "-" * 75,
214
+ ]
215
+ )
216
+ for cell, mean in self.group_means.items():
217
+ lines.append(f" {cell:<35} {mean:>12.4f}")
218
+
219
+ # Show propensity score diagnostics if available
220
+ if self.pscore_stats:
221
+ lines.extend(
222
+ [
223
+ "",
224
+ "-" * 75,
225
+ "Propensity Score Diagnostics:",
226
+ "-" * 75,
227
+ ]
228
+ )
229
+ for stat, value in self.pscore_stats.items():
230
+ lines.append(f" {stat:<35} {value:>12.4f}")
231
+
232
+ lines.extend(
233
+ [
234
+ "",
235
+ "Signif. codes: '***' 0.001, '**' 0.01, '*' 0.05, '.' 0.1",
236
+ "=" * 75,
237
+ ]
238
+ )
239
+
240
+ return "\n".join(lines)
241
+
242
+ def print_summary(self, alpha: Optional[float] = None) -> None:
243
+ """Print the summary to stdout."""
244
+ print(self.summary(alpha))
245
+
246
+ def to_dict(self) -> Dict[str, Any]:
247
+ """
248
+ Convert results to a dictionary.
249
+
250
+ Returns
251
+ -------
252
+ Dict[str, Any]
253
+ Dictionary containing all estimation results.
254
+ """
255
+ result = {
256
+ "att": self.att,
257
+ "se": self.se,
258
+ "t_stat": self.t_stat,
259
+ "p_value": self.p_value,
260
+ "conf_int_lower": self.conf_int[0],
261
+ "conf_int_upper": self.conf_int[1],
262
+ "n_obs": self.n_obs,
263
+ "n_treated_eligible": self.n_treated_eligible,
264
+ "n_treated_ineligible": self.n_treated_ineligible,
265
+ "n_control_eligible": self.n_control_eligible,
266
+ "n_control_ineligible": self.n_control_ineligible,
267
+ "estimation_method": self.estimation_method,
268
+ "inference_method": self.inference_method,
269
+ }
270
+ if self.r_squared is not None:
271
+ result["r_squared"] = self.r_squared
272
+ if self.n_bootstrap is not None:
273
+ result["n_bootstrap"] = self.n_bootstrap
274
+ if self.n_clusters is not None:
275
+ result["n_clusters"] = self.n_clusters
276
+ if self.survey_metadata is not None:
277
+ sm = self.survey_metadata
278
+ result["weight_type"] = sm.weight_type
279
+ result["effective_n"] = sm.effective_n
280
+ result["design_effect"] = sm.design_effect
281
+ result["sum_weights"] = sm.sum_weights
282
+ result["n_strata"] = sm.n_strata
283
+ result["n_psu"] = sm.n_psu
284
+ result["df_survey"] = sm.df_survey
285
+ return result
286
+
287
+ def to_dataframe(self) -> pd.DataFrame:
288
+ """
289
+ Convert results to a pandas DataFrame.
290
+
291
+ Returns
292
+ -------
293
+ pd.DataFrame
294
+ DataFrame with estimation results.
295
+ """
296
+ return pd.DataFrame([self.to_dict()])
297
+
298
+ @property
299
+ def is_significant(self) -> bool:
300
+ """Check if the ATT is statistically significant at the alpha level."""
301
+ return bool(self.p_value < self.alpha)
302
+
303
+ @property
304
+ def significance_stars(self) -> str:
305
+ """Return significance stars based on p-value."""
306
+ return _get_significance_stars(self.p_value)
307
+
308
+ def epv_summary(self, show_all: bool = False) -> pd.DataFrame:
309
+ """
310
+ Return per-subgroup EPV diagnostics as a DataFrame.
311
+
312
+ Parameters
313
+ ----------
314
+ show_all : bool, default False
315
+ If False, only show subgroups with low EPV. If True, show all.
316
+
317
+ Returns
318
+ -------
319
+ pd.DataFrame
320
+ Columns: subgroup, epv, n_events, n_params, is_low.
321
+ """
322
+ if not self.epv_diagnostics:
323
+ return pd.DataFrame(
324
+ columns=["subgroup", "epv", "n_events", "n_params", "is_low"]
325
+ )
326
+ rows = []
327
+ for sg, diag in sorted(self.epv_diagnostics.items()):
328
+ if show_all or diag.get("is_low", False):
329
+ rows.append(
330
+ {
331
+ "subgroup": sg,
332
+ "epv": diag.get("epv"),
333
+ "n_events": diag.get("n_events"),
334
+ "n_params": diag.get("k"),
335
+ "is_low": diag.get("is_low", False),
336
+ }
337
+ )
338
+ cols = ["subgroup", "epv", "n_events", "n_params", "is_low"]
339
+ return pd.DataFrame(rows, columns=cols) if rows else pd.DataFrame(columns=cols)
340
+
341
+
342
+ # =============================================================================
343
+ # Helper Functions
344
+ # =============================================================================
345
+
346
+
347
+ # =============================================================================
348
+ # Main Estimator Class
349
+ # =============================================================================
350
+
351
+
352
+ class TripleDifference:
353
+ """
354
+ Triple Difference (DDD) estimator.
355
+
356
+ Estimates the Average Treatment effect on the Treated (ATT) when treatment
357
+ requires satisfying two criteria: belonging to a treated group AND being
358
+ in an eligible partition of the population.
359
+
360
+ This implementation follows Ortiz-Villavicencio & Sant'Anna (2025), which
361
+ shows that naive DDD implementations (difference of two DiDs, three-way
362
+ fixed effects) are invalid when covariates are needed for identification.
363
+
364
+ Parameters
365
+ ----------
366
+ estimation_method : str, default="dr"
367
+ Estimation method to use:
368
+ - "dr": Doubly robust (recommended). Consistent if either the outcome
369
+ model or propensity score model is correctly specified.
370
+ - "reg": Regression adjustment (outcome regression).
371
+ - "ipw": Inverse probability weighting.
372
+ robust : bool, default=True
373
+ Whether to use heteroskedasticity-robust standard errors.
374
+ Note: influence function-based SEs are inherently robust to
375
+ heteroskedasticity, so this parameter has no effect. Retained
376
+ for API compatibility.
377
+ cluster : str, optional
378
+ Column name for cluster-robust standard errors. When provided,
379
+ SEs are computed using the Liang-Zeger cluster-robust variance
380
+ estimator on the influence function.
381
+ alpha : float, default=0.05
382
+ Significance level for confidence intervals.
383
+ pscore_trim : float, default=0.01
384
+ Trimming threshold for propensity scores. Scores below this value
385
+ or above (1 - pscore_trim) are clipped to avoid extreme weights.
386
+ rank_deficient_action : str, default="warn"
387
+ Action when design matrix is rank-deficient (linearly dependent columns):
388
+ - "warn": Issue warning and drop linearly dependent columns (default)
389
+ - "error": Raise ValueError
390
+ - "silent": Drop columns silently without warning
391
+ epv_threshold : float, default=10
392
+ Events Per Variable threshold for propensity score logit.
393
+ When the ratio of minority-class observations to predictor
394
+ variables (excluding intercept) falls below this value, a
395
+ warning is emitted (or ``ValueError`` raised if
396
+ ``rank_deficient_action="error"``). Based on Peduzzi et al.
397
+ (1996). Only applies to IPW and DR estimation methods.
398
+ pscore_fallback : str, default="error"
399
+ Action when propensity score estimation fails:
400
+ - "error": Raise the exception (default)
401
+ - "unconditional": Fall back to unconditional propensity with
402
+ a warning. For IPW, drops all covariates. For DR, the
403
+ propensity model becomes unconditional but outcome regression
404
+ still uses covariates.
405
+ When ``rank_deficient_action="error"``, errors are always
406
+ re-raised regardless of this setting.
407
+
408
+ Attributes
409
+ ----------
410
+ results_ : TripleDifferenceResults
411
+ Estimation results after calling fit().
412
+ is_fitted_ : bool
413
+ Whether the model has been fitted.
414
+
415
+ Examples
416
+ --------
417
+ Basic usage with a DataFrame:
418
+
419
+ >>> import pandas as pd
420
+ >>> from diff_diff import TripleDifference
421
+ >>>
422
+ >>> # Data where treatment affects women (partition=1) in states
423
+ >>> # that enacted a policy (group=1)
424
+ >>> data = pd.DataFrame({
425
+ ... 'outcome': [...],
426
+ ... 'group': [1, 1, 0, 0, ...], # 1=policy state, 0=control state
427
+ ... 'partition': [1, 0, 1, 0, ...], # 1=women, 0=men
428
+ ... 'post': [0, 0, 1, 1, ...], # 1=post-treatment period
429
+ ... })
430
+ >>>
431
+ >>> # Fit using doubly robust estimation
432
+ >>> ddd = TripleDifference(estimation_method="dr")
433
+ >>> results = ddd.fit(
434
+ ... data,
435
+ ... outcome='outcome',
436
+ ... group='group',
437
+ ... partition='partition',
438
+ ... time='post'
439
+ ... )
440
+ >>> print(results.att) # ATT estimate
441
+
442
+ With covariates (properly handled unlike naive DDD):
443
+
444
+ >>> results = ddd.fit(
445
+ ... data,
446
+ ... outcome='outcome',
447
+ ... group='group',
448
+ ... partition='partition',
449
+ ... time='post',
450
+ ... covariates=['age', 'income']
451
+ ... )
452
+
453
+ Notes
454
+ -----
455
+ The DDD estimator is appropriate when:
456
+
457
+ 1. Treatment affects only units satisfying BOTH criteria:
458
+ - Belonging to a treated group (G=1), e.g., states with a policy
459
+ - Being in an eligible partition (P=1), e.g., women, low-income
460
+
461
+ 2. The DDD parallel trends assumption holds: the differential trend
462
+ between eligible and ineligible partitions would have been the same
463
+ across treated and control groups, absent treatment.
464
+
465
+ This is weaker than requiring separate parallel trends for two DiDs,
466
+ as biases can cancel out in the differencing.
467
+
468
+ References
469
+ ----------
470
+ .. [1] Ortiz-Villavicencio, M., & Sant'Anna, P. H. C. (2025).
471
+ Better Understanding Triple Differences Estimators.
472
+ arXiv:2505.09942.
473
+
474
+ .. [2] Gruber, J. (1994). The incidence of mandated maternity benefits.
475
+ American Economic Review, 84(3), 622-641.
476
+ """
477
+
478
+ def __init__(
479
+ self,
480
+ estimation_method: str = "dr",
481
+ robust: bool = True,
482
+ cluster: Optional[str] = None,
483
+ alpha: float = 0.05,
484
+ pscore_trim: float = 0.01,
485
+ rank_deficient_action: str = "warn",
486
+ epv_threshold: float = 10,
487
+ pscore_fallback: str = "error",
488
+ ):
489
+ if estimation_method not in ("dr", "reg", "ipw"):
490
+ raise ValueError(
491
+ f"estimation_method must be 'dr', 'reg', or 'ipw', " f"got '{estimation_method}'"
492
+ )
493
+ if rank_deficient_action not in ["warn", "error", "silent"]:
494
+ raise ValueError(
495
+ f"rank_deficient_action must be 'warn', 'error', or 'silent', "
496
+ f"got '{rank_deficient_action}'"
497
+ )
498
+ if epv_threshold <= 0:
499
+ raise ValueError(
500
+ f"epv_threshold must be > 0, got {epv_threshold}"
501
+ )
502
+ if pscore_fallback not in {"error", "unconditional"}:
503
+ raise ValueError(
504
+ f"pscore_fallback must be 'error' or 'unconditional', "
505
+ f"got '{pscore_fallback}'"
506
+ )
507
+ self.estimation_method = estimation_method
508
+ self.robust = robust
509
+ self.cluster = cluster
510
+ self.alpha = alpha
511
+ self.pscore_trim = pscore_trim
512
+ self.rank_deficient_action = rank_deficient_action
513
+ self.epv_threshold = epv_threshold
514
+ self.pscore_fallback = pscore_fallback
515
+
516
+ self.is_fitted_ = False
517
+ self.results_: Optional[TripleDifferenceResults] = None
518
+
519
+ def fit(
520
+ self,
521
+ data: pd.DataFrame,
522
+ outcome: str,
523
+ group: str,
524
+ partition: str,
525
+ time: str,
526
+ covariates: Optional[List[str]] = None,
527
+ survey_design=None,
528
+ ) -> TripleDifferenceResults:
529
+ """
530
+ Fit the Triple Difference model.
531
+
532
+ Parameters
533
+ ----------
534
+ data : pd.DataFrame
535
+ DataFrame containing all variables.
536
+ outcome : str
537
+ Name of the outcome variable column.
538
+ group : str
539
+ Name of the group indicator column (0/1).
540
+ 1 = treated group (e.g., states that enacted policy).
541
+ 0 = control group.
542
+ partition : str
543
+ Name of the partition/eligibility indicator column (0/1).
544
+ 1 = eligible partition (e.g., women, targeted demographic).
545
+ 0 = ineligible partition.
546
+ time : str
547
+ Name of the time period indicator column (0/1).
548
+ 1 = post-treatment period.
549
+ 0 = pre-treatment period.
550
+ covariates : list of str, optional
551
+ List of covariate column names to adjust for.
552
+ These are properly incorporated using the selected estimation
553
+ method (unlike naive DDD implementations).
554
+ survey_design : SurveyDesign, optional
555
+ Survey design specification for complex survey data. When
556
+ provided, uses survey weights for estimation and Taylor Series
557
+ Linearization (TSL) for variance estimation. Supported with
558
+ all estimation methods ("reg", "ipw", "dr").
559
+
560
+ Returns
561
+ -------
562
+ TripleDifferenceResults
563
+ Object containing estimation results.
564
+
565
+ Raises
566
+ ------
567
+ ValueError
568
+ If required columns are missing or data validation fails.
569
+ NotImplementedError
570
+ If survey_design is used with wild_bootstrap inference.
571
+ """
572
+ # Reset replicate state from any previous fit
573
+ self._replicate_n_valid = None
574
+
575
+ # Resolve survey design if provided
576
+ from diff_diff.survey import (
577
+ _inject_cluster_as_psu,
578
+ _resolve_effective_cluster,
579
+ _resolve_survey_for_fit,
580
+ compute_survey_metadata,
581
+ )
582
+
583
+ resolved_survey, survey_weights, survey_weight_type, survey_metadata = (
584
+ _resolve_survey_for_fit(survey_design, data, "analytical")
585
+ )
586
+
587
+ if resolved_survey is not None and resolved_survey.weight_type != "pweight":
588
+ raise ValueError(
589
+ f"TripleDifference survey support requires weight_type='pweight', "
590
+ f"got '{resolved_survey.weight_type}'. The survey variance math "
591
+ f"assumes probability weights (pweight)."
592
+ )
593
+
594
+ # Validate inputs
595
+ self._validate_data(data, outcome, group, partition, time, covariates)
596
+
597
+ # Extract data
598
+ y = data[outcome].values.astype(float)
599
+ G = data[group].values.astype(float)
600
+ P = data[partition].values.astype(float)
601
+ T = data[time].values.astype(float)
602
+
603
+ # Store cluster IDs for SE computation
604
+ self._cluster_ids = data[self.cluster].values if self.cluster is not None else None
605
+ if self._cluster_ids is not None and np.any(pd.isna(data[self.cluster])):
606
+ raise ValueError(f"Cluster column '{self.cluster}' contains missing values")
607
+
608
+ # Resolve effective cluster and inject cluster-as-PSU for survey variance
609
+ if resolved_survey is not None:
610
+ effective_cluster_ids = _resolve_effective_cluster(
611
+ resolved_survey, self._cluster_ids, self.cluster
612
+ )
613
+ if effective_cluster_ids is not None:
614
+ resolved_survey = _inject_cluster_as_psu(resolved_survey, effective_cluster_ids)
615
+ if resolved_survey.psu is not None and survey_metadata is not None:
616
+ raw_w = (
617
+ data[survey_design.weights].values.astype(np.float64)
618
+ if survey_design.weights
619
+ else np.ones(len(data), dtype=np.float64)
620
+ )
621
+ survey_metadata = compute_survey_metadata(resolved_survey, raw_w)
622
+
623
+ # Get covariates if specified
624
+ X = None
625
+ if covariates:
626
+ X = data[covariates].values.astype(float)
627
+ if np.any(np.isnan(X)):
628
+ raise ValueError("Covariates contain missing values")
629
+
630
+ # Count observations in each cell
631
+ n_obs = len(y)
632
+ n_treated_eligible = int(np.sum((G == 1) & (P == 1)))
633
+ n_treated_ineligible = int(np.sum((G == 1) & (P == 0)))
634
+ n_control_eligible = int(np.sum((G == 0) & (P == 1)))
635
+ n_control_ineligible = int(np.sum((G == 0) & (P == 0)))
636
+
637
+ # Compute cell means for diagnostics
638
+ group_means = self._compute_cell_means(y, G, P, T, weights=survey_weights)
639
+
640
+ # Estimate ATT based on method
641
+ if self.estimation_method == "reg":
642
+ att, se, r_squared, pscore_stats, epv_diag = self._regression_adjustment(
643
+ y,
644
+ G,
645
+ P,
646
+ T,
647
+ X,
648
+ survey_weights=survey_weights,
649
+ resolved_survey=resolved_survey,
650
+ )
651
+ elif self.estimation_method == "ipw":
652
+ att, se, r_squared, pscore_stats, epv_diag = self._ipw_estimation(
653
+ y,
654
+ G,
655
+ P,
656
+ T,
657
+ X,
658
+ survey_weights=survey_weights,
659
+ resolved_survey=resolved_survey,
660
+ )
661
+ else: # doubly robust
662
+ att, se, r_squared, pscore_stats, epv_diag = self._doubly_robust(
663
+ y,
664
+ G,
665
+ P,
666
+ T,
667
+ X,
668
+ survey_weights=survey_weights,
669
+ resolved_survey=resolved_survey,
670
+ )
671
+
672
+ # Compute inference
673
+ # When survey design is active, use survey df (n_PSU - n_strata)
674
+ if survey_metadata is not None and survey_metadata.df_survey is not None:
675
+ df = survey_metadata.df_survey
676
+ # Override with effective replicate df only when replicates were dropped
677
+ if (hasattr(self, '_replicate_n_valid') and self._replicate_n_valid is not None
678
+ and resolved_survey is not None
679
+ and self._replicate_n_valid < resolved_survey.n_replicates):
680
+ df = self._replicate_n_valid - 1
681
+ survey_metadata.df_survey = self._replicate_n_valid - 1
682
+ # df <= 0 means insufficient rank for t-based inference
683
+ if df is not None and df <= 0:
684
+ df = 0 # Forces NaN from t-distribution
685
+ elif (resolved_survey is not None
686
+ and hasattr(resolved_survey, 'uses_replicate_variance')
687
+ and resolved_survey.uses_replicate_variance):
688
+ # Replicate design with undefined df (rank <= 1) — NaN inference
689
+ df = 0 # Forces NaN from t-distribution
690
+ else:
691
+ df = n_obs - 8 # Approximate df (8 cell means)
692
+ if covariates:
693
+ df -= len(covariates)
694
+ df = max(df, 1)
695
+
696
+ t_stat, p_value, conf_int = safe_inference(att, se, alpha=self.alpha, df=df)
697
+
698
+ # Get number of clusters if clustering
699
+ n_clusters = None
700
+ if self.cluster is not None:
701
+ n_clusters = data[self.cluster].nunique()
702
+
703
+ # Create results object
704
+ self.results_ = TripleDifferenceResults(
705
+ att=att,
706
+ se=se,
707
+ t_stat=t_stat,
708
+ p_value=p_value,
709
+ conf_int=conf_int,
710
+ n_obs=n_obs,
711
+ n_treated_eligible=n_treated_eligible,
712
+ n_treated_ineligible=n_treated_ineligible,
713
+ n_control_eligible=n_control_eligible,
714
+ n_control_ineligible=n_control_ineligible,
715
+ estimation_method=self.estimation_method,
716
+ alpha=self.alpha,
717
+ group_means=group_means,
718
+ pscore_stats=pscore_stats,
719
+ r_squared=r_squared,
720
+ inference_method="analytical",
721
+ n_clusters=n_clusters,
722
+ survey_metadata=survey_metadata,
723
+ epv_diagnostics=epv_diag if epv_diag else None,
724
+ epv_threshold=self.epv_threshold,
725
+ pscore_fallback=self.pscore_fallback,
726
+ )
727
+
728
+ self.is_fitted_ = True
729
+ return self.results_
730
+
731
+ def _validate_data(
732
+ self,
733
+ data: pd.DataFrame,
734
+ outcome: str,
735
+ group: str,
736
+ partition: str,
737
+ time: str,
738
+ covariates: Optional[List[str]] = None,
739
+ ) -> None:
740
+ """Validate input data."""
741
+ if not isinstance(data, pd.DataFrame):
742
+ raise TypeError("data must be a pandas DataFrame")
743
+
744
+ # Check required columns exist
745
+ required_cols = [outcome, group, partition, time]
746
+ if covariates:
747
+ required_cols.extend(covariates)
748
+ if self.cluster is not None:
749
+ required_cols.append(self.cluster)
750
+
751
+ missing_cols = [col for col in required_cols if col not in data.columns]
752
+ if missing_cols:
753
+ raise ValueError(f"Missing columns in data: {missing_cols}")
754
+
755
+ # Check for missing values in required columns
756
+ for col in [outcome, group, partition, time]:
757
+ if data[col].isna().any():
758
+ raise ValueError(f"Column '{col}' contains missing values")
759
+
760
+ # Validate binary variables
761
+ for col, name in [(group, "group"), (partition, "partition"), (time, "time")]:
762
+ unique_vals = set(data[col].unique())
763
+ if not unique_vals.issubset({0, 1, 0.0, 1.0}):
764
+ raise ValueError(
765
+ f"'{name}' column must be binary (0/1), " f"got values: {sorted(unique_vals)}"
766
+ )
767
+ if len(unique_vals) < 2:
768
+ raise ValueError(f"'{name}' column must have both 0 and 1 values")
769
+
770
+ # Check we have observations in all cells
771
+ G = data[group].values
772
+ P = data[partition].values
773
+ T = data[time].values
774
+
775
+ cells = [
776
+ ((G == 1) & (P == 1) & (T == 0), "treated, eligible, pre"),
777
+ ((G == 1) & (P == 1) & (T == 1), "treated, eligible, post"),
778
+ ((G == 1) & (P == 0) & (T == 0), "treated, ineligible, pre"),
779
+ ((G == 1) & (P == 0) & (T == 1), "treated, ineligible, post"),
780
+ ((G == 0) & (P == 1) & (T == 0), "control, eligible, pre"),
781
+ ((G == 0) & (P == 1) & (T == 1), "control, eligible, post"),
782
+ ((G == 0) & (P == 0) & (T == 0), "control, ineligible, pre"),
783
+ ((G == 0) & (P == 0) & (T == 1), "control, ineligible, post"),
784
+ ]
785
+
786
+ for mask, cell_name in cells:
787
+ n_cell = int(np.sum(mask))
788
+ if n_cell == 0:
789
+ raise ValueError(
790
+ f"No observations in cell: {cell_name}. "
791
+ "DDD requires observations in all 8 cells."
792
+ )
793
+ elif n_cell < _MIN_CELL_SIZE:
794
+ warnings.warn(
795
+ f"Low observation count ({n_cell}) in cell: {cell_name}. "
796
+ f"Estimates may be unreliable with fewer than "
797
+ f"{_MIN_CELL_SIZE} observations per cell.",
798
+ UserWarning,
799
+ stacklevel=2,
800
+ )
801
+
802
+ def _compute_cell_means(
803
+ self,
804
+ y: np.ndarray,
805
+ G: np.ndarray,
806
+ P: np.ndarray,
807
+ T: np.ndarray,
808
+ weights: Optional[np.ndarray] = None,
809
+ ) -> Dict[str, float]:
810
+ """Compute mean outcomes for each of the 8 DDD cells."""
811
+ means = {}
812
+ for g_val, g_name in [(1, "Treated"), (0, "Control")]:
813
+ for p_val, p_name in [(1, "Eligible"), (0, "Ineligible")]:
814
+ for t_val, t_name in [(0, "Pre"), (1, "Post")]:
815
+ mask = (G == g_val) & (P == p_val) & (T == t_val)
816
+ cell_name = f"{g_name}, {p_name}, {t_name}"
817
+ if weights is not None:
818
+ w_cell = weights[mask]
819
+ if np.sum(w_cell) <= 0:
820
+ raise ValueError(
821
+ f"Cell '{cell_name}' has zero effective survey "
822
+ f"weight. Cannot compute weighted cell mean. "
823
+ f"Check subpopulation/domain definition."
824
+ )
825
+ means[cell_name] = float(np.average(y[mask], weights=w_cell))
826
+ else:
827
+ means[cell_name] = float(np.mean(y[mask]))
828
+ return means
829
+
830
+ # =========================================================================
831
+ # Three-DiD Decomposition (matches R's triplediff::ddd())
832
+ # =========================================================================
833
+ #
834
+ # The DDD is decomposed into three pairwise DiD comparisons:
835
+ # DiD_3: subgroup 3 (G=1,P=0) vs subgroup 4 (G=1,P=1)
836
+ # DiD_2: subgroup 2 (G=0,P=1) vs subgroup 4 (G=1,P=1)
837
+ # DiD_1: subgroup 1 (G=0,P=0) vs subgroup 4 (G=1,P=1)
838
+ #
839
+ # DDD = DiD_3 + DiD_2 - DiD_1
840
+ #
841
+ # Each DiD uses the selected estimation method (DR, IPW, or RA).
842
+ # SE is computed from the combined influence function:
843
+ # inf = w3*inf_3 + w2*inf_2 - w1*inf_1
844
+ # SE = std(inf, ddof=1) / sqrt(n)
845
+ #
846
+ # Reference: Ortiz-Villavicencio & Sant'Anna (2025), implemented in
847
+ # R's triplediff::ddd() with panel=FALSE (repeated cross-section).
848
+ # =========================================================================
849
+
850
+ def _regression_adjustment(
851
+ self,
852
+ y: np.ndarray,
853
+ G: np.ndarray,
854
+ P: np.ndarray,
855
+ T: np.ndarray,
856
+ X: Optional[np.ndarray],
857
+ survey_weights: Optional[np.ndarray] = None,
858
+ resolved_survey=None,
859
+ ) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]], Dict[int, Dict[str, Any]]]:
860
+ """
861
+ Estimate ATT using regression adjustment via three-DiD decomposition.
862
+
863
+ For each pairwise comparison (subgroup j vs subgroup 4), fits
864
+ separate outcome models per subgroup-time cell and computes
865
+ imputed counterfactual means. Matches R's triplediff::ddd()
866
+ with est_method="reg".
867
+ """
868
+ return self._estimate_ddd_decomposition(
869
+ y,
870
+ G,
871
+ P,
872
+ T,
873
+ X,
874
+ survey_weights=survey_weights,
875
+ resolved_survey=resolved_survey,
876
+ )
877
+
878
+ def _ipw_estimation(
879
+ self,
880
+ y: np.ndarray,
881
+ G: np.ndarray,
882
+ P: np.ndarray,
883
+ T: np.ndarray,
884
+ X: Optional[np.ndarray],
885
+ survey_weights: Optional[np.ndarray] = None,
886
+ resolved_survey=None,
887
+ ) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]], Dict[int, Dict[str, Any]]]:
888
+ """
889
+ Estimate ATT using inverse probability weighting via three-DiD
890
+ decomposition.
891
+
892
+ For each pairwise comparison, estimates propensity scores for
893
+ subgroup membership P(subgroup=4|X) within {j, 4} subset.
894
+ Matches R's triplediff::ddd() with est_method="ipw".
895
+ """
896
+ return self._estimate_ddd_decomposition(
897
+ y,
898
+ G,
899
+ P,
900
+ T,
901
+ X,
902
+ survey_weights=survey_weights,
903
+ resolved_survey=resolved_survey,
904
+ )
905
+
906
+ def _doubly_robust(
907
+ self,
908
+ y: np.ndarray,
909
+ G: np.ndarray,
910
+ P: np.ndarray,
911
+ T: np.ndarray,
912
+ X: Optional[np.ndarray],
913
+ survey_weights: Optional[np.ndarray] = None,
914
+ resolved_survey=None,
915
+ ) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]], Dict[int, Dict[str, Any]]]:
916
+ """
917
+ Estimate ATT using doubly robust estimation via three-DiD
918
+ decomposition.
919
+
920
+ Combines outcome regression and IPW for robustness: consistent
921
+ if either the outcome model or propensity score model is
922
+ correctly specified. Matches R's triplediff::ddd() with
923
+ est_method="dr".
924
+ """
925
+ return self._estimate_ddd_decomposition(
926
+ y,
927
+ G,
928
+ P,
929
+ T,
930
+ X,
931
+ survey_weights=survey_weights,
932
+ resolved_survey=resolved_survey,
933
+ )
934
+
935
+ def _estimate_ddd_decomposition(
936
+ self,
937
+ y: np.ndarray,
938
+ G: np.ndarray,
939
+ P: np.ndarray,
940
+ T: np.ndarray,
941
+ X: Optional[np.ndarray],
942
+ survey_weights: Optional[np.ndarray] = None,
943
+ resolved_survey=None,
944
+ ) -> Tuple[float, float, Optional[float], Optional[Dict[str, float]], Dict[int, Dict[str, Any]]]:
945
+ """
946
+ Core DDD estimation via three-DiD decomposition.
947
+
948
+ Implements the methodology from Ortiz-Villavicencio & Sant'Anna
949
+ (2025), matching R's triplediff::ddd() for repeated cross-section
950
+ data (panel=FALSE).
951
+
952
+ The DDD is decomposed into three pairwise DiD comparisons,
953
+ each using the selected estimation method (DR, IPW, or RA):
954
+ DDD = DiD_3 + DiD_2 - DiD_1
955
+
956
+ Standard errors use the efficient influence function:
957
+ SE = std(w3*IF_3 + w2*IF_2 - w1*IF_1) / sqrt(n)
958
+
959
+ When resolved_survey is provided, survey-weighted SE is computed
960
+ using TSL on the combined influence function.
961
+ """
962
+ n = len(y)
963
+ est_method = self.estimation_method
964
+
965
+ # Assign subgroups following R convention:
966
+ # 4: G=1, P=1 (treated, eligible - reference/"treated")
967
+ # 3: G=1, P=0 (treated, ineligible)
968
+ # 2: G=0, P=1 (control, eligible)
969
+ # 1: G=0, P=0 (control, ineligible)
970
+ subgroup = np.zeros(n, dtype=int)
971
+ subgroup[(G == 1) & (P == 1)] = 4
972
+ subgroup[(G == 1) & (P == 0)] = 3
973
+ subgroup[(G == 0) & (P == 1)] = 2
974
+ subgroup[(G == 0) & (P == 0)] = 1
975
+
976
+ post = T.astype(float)
977
+
978
+ # Covariate matrix (always includes intercept)
979
+ if X is not None and X.shape[1] > 0:
980
+ covX = np.column_stack([np.ones(n), X])
981
+ has_covariates = True
982
+ else:
983
+ covX = np.ones((n, 1))
984
+ has_covariates = False
985
+
986
+ # Three DiD comparisons: j vs 4 for j in {3, 2, 1}
987
+ did_results = {}
988
+ pscore_stats = None
989
+ all_pscores = {} # Collect pscores for diagnostics
990
+ overlap_issues = [] # Collect overlap diagnostics across comparisons
991
+ any_nonfinite_if = False
992
+ epv_all = {} # Collect EPV diagnostics per subgroup comparison
993
+
994
+ with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
995
+ for j in [3, 2, 1]:
996
+ mask = (subgroup == j) | (subgroup == 4)
997
+ y_sub = y[mask]
998
+ post_sub = post[mask]
999
+ sg_sub = subgroup[mask]
1000
+ covX_sub = covX[mask]
1001
+ n_sub = len(y_sub)
1002
+
1003
+ PA4 = (sg_sub == 4).astype(float)
1004
+ PAa = (sg_sub == j).astype(float)
1005
+
1006
+ # Subset survey weights for this comparison (needed for logit)
1007
+ w_sub = survey_weights[mask] if survey_weights is not None else None
1008
+
1009
+ # --- Propensity scores ---
1010
+ if est_method == "reg":
1011
+ # RA: no propensity scores needed
1012
+ pscore_sub = np.ones(n_sub)
1013
+ hessian = None
1014
+ elif has_covariates:
1015
+ # Logistic regression: P(subgroup=4 | X) within {j, 4}
1016
+ ps_estimated = True
1017
+ diag = {}
1018
+ try:
1019
+ _, pscore_sub = solve_logit(
1020
+ covX_sub[:, 1:],
1021
+ PA4,
1022
+ rank_deficient_action=self.rank_deficient_action,
1023
+ weights=w_sub,
1024
+ epv_threshold=self.epv_threshold,
1025
+ context_label=f"subgroup {j} vs 4",
1026
+ diagnostics_out=diag,
1027
+ )
1028
+ except Exception:
1029
+ if (
1030
+ self.pscore_fallback == "error"
1031
+ or self.rank_deficient_action == "error"
1032
+ ):
1033
+ raise
1034
+ if w_sub is not None:
1035
+ pos = w_sub > 0
1036
+ if np.any(pos):
1037
+ p_uc = float(np.average(PA4[pos], weights=w_sub[pos]))
1038
+ else:
1039
+ p_uc = float(np.mean(PA4))
1040
+ else:
1041
+ p_uc = float(np.mean(PA4))
1042
+ pscore_sub = np.full(n_sub, p_uc)
1043
+ ps_estimated = False
1044
+ warnings.warn(
1045
+ f"Propensity score estimation failed for subgroup "
1046
+ f"{j} vs 4; using unconditional probability. "
1047
+ f"For DR, outcome regression still uses covariates. "
1048
+ f"Consider estimation_method='reg' to avoid propensity "
1049
+ f"scores entirely.",
1050
+ UserWarning,
1051
+ stacklevel=3,
1052
+ )
1053
+ if diag:
1054
+ epv_all[j] = diag
1055
+
1056
+ pscore_sub = np.clip(pscore_sub, self.pscore_trim, 1 - self.pscore_trim)
1057
+ all_pscores[j] = pscore_sub
1058
+
1059
+ # Check overlap: count obs at trim bounds
1060
+ # (1e-10 tolerance for floating-point after np.clip)
1061
+ n_trimmed = int(
1062
+ np.sum(
1063
+ (pscore_sub <= self.pscore_trim + 1e-10)
1064
+ | (pscore_sub >= 1 - self.pscore_trim - 1e-10)
1065
+ )
1066
+ )
1067
+ frac_trimmed = n_trimmed / len(pscore_sub)
1068
+ if frac_trimmed > 0.05:
1069
+ overlap_issues.append((j, frac_trimmed))
1070
+
1071
+ # Hessian only when PS was actually estimated
1072
+ if ps_estimated:
1073
+ W_ps = pscore_sub * (1 - pscore_sub)
1074
+ if w_sub is not None:
1075
+ W_ps = W_ps * w_sub
1076
+ try:
1077
+ XWX = covX_sub.T @ (W_ps[:, None] * covX_sub)
1078
+ hessian = np.linalg.inv(XWX) * n_sub
1079
+ except np.linalg.LinAlgError:
1080
+ hessian = np.linalg.pinv(XWX) * n_sub
1081
+ else:
1082
+ hessian = None
1083
+ else:
1084
+ # No covariates: unconditional probability
1085
+ pscore_sub = np.full(n_sub, np.mean(PA4))
1086
+ pscore_sub = np.clip(pscore_sub, self.pscore_trim, 1 - self.pscore_trim)
1087
+ # Check overlap (same logic as covariate branch)
1088
+ n_trimmed = int(
1089
+ np.sum(
1090
+ (pscore_sub <= self.pscore_trim + 1e-10)
1091
+ | (pscore_sub >= 1 - self.pscore_trim - 1e-10)
1092
+ )
1093
+ )
1094
+ frac_trimmed = n_trimmed / len(pscore_sub)
1095
+ if frac_trimmed > 0.05:
1096
+ overlap_issues.append((j, frac_trimmed))
1097
+ hessian = None
1098
+
1099
+ # --- Outcome regression ---
1100
+ if est_method == "ipw":
1101
+ # IPW: no outcome regression
1102
+ or_ctrl_pre = np.zeros(n_sub)
1103
+ or_ctrl_post = np.zeros(n_sub)
1104
+ or_trt_pre = np.zeros(n_sub)
1105
+ or_trt_post = np.zeros(n_sub)
1106
+ else:
1107
+ # Fit separate OLS per subgroup-time cell, predict for all
1108
+ or_ctrl_pre = self._fit_predict_mu(
1109
+ y_sub,
1110
+ covX_sub,
1111
+ sg_sub == j,
1112
+ post_sub == 0,
1113
+ n_sub,
1114
+ weights=w_sub,
1115
+ )
1116
+ or_ctrl_post = self._fit_predict_mu(
1117
+ y_sub,
1118
+ covX_sub,
1119
+ sg_sub == j,
1120
+ post_sub == 1,
1121
+ n_sub,
1122
+ weights=w_sub,
1123
+ )
1124
+ or_trt_pre = self._fit_predict_mu(
1125
+ y_sub,
1126
+ covX_sub,
1127
+ sg_sub == 4,
1128
+ post_sub == 0,
1129
+ n_sub,
1130
+ weights=w_sub,
1131
+ )
1132
+ or_trt_post = self._fit_predict_mu(
1133
+ y_sub,
1134
+ covX_sub,
1135
+ sg_sub == 4,
1136
+ post_sub == 1,
1137
+ n_sub,
1138
+ weights=w_sub,
1139
+ )
1140
+
1141
+ # --- Compute DiD ATT and influence function ---
1142
+ att_j, inf_j = self._compute_did_rc(
1143
+ y_sub,
1144
+ post_sub,
1145
+ PA4,
1146
+ PAa,
1147
+ pscore_sub,
1148
+ covX_sub,
1149
+ or_ctrl_pre,
1150
+ or_ctrl_post,
1151
+ or_trt_pre,
1152
+ or_trt_post,
1153
+ hessian,
1154
+ est_method,
1155
+ n_sub,
1156
+ weights=w_sub,
1157
+ )
1158
+
1159
+ # Track non-finite IF values (flag for NaN SE later)
1160
+ if not np.all(np.isfinite(inf_j)):
1161
+ any_nonfinite_if = True
1162
+ inf_j = np.where(np.isfinite(inf_j), inf_j, 0.0)
1163
+
1164
+ # Pad influence function to full length
1165
+ inf_full = np.zeros(n)
1166
+ inf_full[mask] = inf_j
1167
+
1168
+ did_results[j] = {"att": att_j, "inf": inf_full}
1169
+
1170
+ # Emit overlap warning if >5% of observations trimmed in any comparison
1171
+ if overlap_issues:
1172
+ details = ", ".join(f"subgroup {j} vs 4: {frac:.0%}" for j, frac in overlap_issues)
1173
+ warnings.warn(
1174
+ f"Poor propensity score overlap ({details} of observations "
1175
+ f"trimmed at bounds). IPW/DR estimates may be unreliable.",
1176
+ UserWarning,
1177
+ stacklevel=3,
1178
+ )
1179
+
1180
+ # --- Combine three DiDs ---
1181
+ att = (
1182
+ float(did_results[3]["att"])
1183
+ + float(did_results[2]["att"])
1184
+ - float(did_results[1]["att"])
1185
+ )
1186
+
1187
+ # Influence function weights (matching R's att_dr_rc)
1188
+ if survey_weights is not None:
1189
+ n3 = np.sum(survey_weights[(subgroup == 3) | (subgroup == 4)])
1190
+ n2 = np.sum(survey_weights[(subgroup == 2) | (subgroup == 4)])
1191
+ n1 = np.sum(survey_weights[(subgroup == 1) | (subgroup == 4)])
1192
+ n_total = np.sum(survey_weights)
1193
+ else:
1194
+ n3 = np.sum((subgroup == 3) | (subgroup == 4))
1195
+ n2 = np.sum((subgroup == 2) | (subgroup == 4))
1196
+ n1 = np.sum((subgroup == 1) | (subgroup == 4))
1197
+ n_total = n
1198
+ w3 = n_total / n3
1199
+ w2 = n_total / n2
1200
+ w1 = n_total / n1
1201
+
1202
+ inf_func = (
1203
+ w3 * did_results[3]["inf"] + w2 * did_results[2]["inf"] - w1 * did_results[1]["inf"]
1204
+ )
1205
+
1206
+ if resolved_survey is not None:
1207
+ # Survey-weighted SE via TSL on the combined influence function.
1208
+ # For IPW/DR: pairwise IFs include survey weights via weighted Riesz
1209
+ # representers, so divide out to avoid double-weighting by TSL.
1210
+ # For reg: pairwise IFs are already on the unweighted scale (WLS
1211
+ # fits use weights but the IF is residual-based, not Riesz-weighted),
1212
+ # so pass directly to TSL without de-weighting.
1213
+ inf_for_tsl = inf_func.copy()
1214
+ if est_method in ("ipw", "dr") and survey_weights is not None:
1215
+ sw = survey_weights
1216
+ nz = sw > 0
1217
+ inf_for_tsl[nz] = inf_for_tsl[nz] / sw[nz]
1218
+
1219
+ if resolved_survey.uses_replicate_variance:
1220
+ from diff_diff.survey import compute_replicate_if_variance
1221
+
1222
+ # Score-scale to match TSL bread (1/sum(w)^2):
1223
+ # reg: psi = w * inf_func / sum(w)
1224
+ # ipw/dr: psi = inf_func / sum(w) (survey weights cancel)
1225
+ w_sum = float(resolved_survey.weights.sum())
1226
+ if est_method in ("ipw", "dr") and survey_weights is not None:
1227
+ psi_rep = inf_func / w_sum
1228
+ else:
1229
+ psi_rep = resolved_survey.weights * inf_func / w_sum
1230
+ variance, n_valid_rep = compute_replicate_if_variance(psi_rep, resolved_survey)
1231
+ se = float(np.sqrt(max(variance, 0.0))) if np.isfinite(variance) else np.nan
1232
+ # Store effective replicate count for df update in fit()
1233
+ self._replicate_n_valid = n_valid_rep
1234
+ else:
1235
+ from diff_diff.survey import compute_survey_vcov
1236
+
1237
+ vcov_survey = compute_survey_vcov(np.ones((n, 1)), inf_for_tsl, resolved_survey)
1238
+ se = float(np.sqrt(vcov_survey[0, 0]))
1239
+ elif self._cluster_ids is not None:
1240
+ # Cluster-robust SE: sum IF within clusters, then Liang-Zeger variance
1241
+ unique_clusters = np.unique(self._cluster_ids)
1242
+ n_clusters_val = len(unique_clusters)
1243
+ if n_clusters_val < 2:
1244
+ raise ValueError(
1245
+ f"Need at least 2 clusters for cluster-robust SEs, " f"got {n_clusters_val}"
1246
+ )
1247
+ cluster_sums = np.array(
1248
+ [np.sum(inf_func[self._cluster_ids == c]) for c in unique_clusters]
1249
+ )
1250
+ # V = (G/(G-1)) * (1/n^2) * sum(psi_c^2)
1251
+ se = float(
1252
+ np.sqrt((n_clusters_val / (n_clusters_val - 1)) * np.sum(cluster_sums**2) / n**2)
1253
+ )
1254
+ else:
1255
+ se = float(np.std(inf_func, ddof=1) / np.sqrt(n))
1256
+
1257
+ # Non-finite IF values make SE undefined
1258
+ if any_nonfinite_if:
1259
+ warnings.warn(
1260
+ "Non-finite values in influence function (likely due to "
1261
+ "extreme propensity scores or near-singular design). "
1262
+ "SE set to NaN.",
1263
+ UserWarning,
1264
+ stacklevel=3,
1265
+ )
1266
+ se = np.nan
1267
+
1268
+ # Propensity score stats (for IPW/DR with covariates)
1269
+ if has_covariates and est_method != "reg" and all_pscores:
1270
+ all_ps = np.concatenate(list(all_pscores.values()))
1271
+ pscore_stats = {
1272
+ "P(subgroup=4|X) mean": float(np.mean(all_ps)),
1273
+ "P(subgroup=4|X) std": float(np.std(all_ps)),
1274
+ "P(subgroup=4|X) min": float(np.min(all_ps)),
1275
+ "P(subgroup=4|X) max": float(np.max(all_ps)),
1276
+ }
1277
+
1278
+ # R-squared for regression-based methods
1279
+ r_squared = None
1280
+ if est_method in ("reg", "dr") and has_covariates:
1281
+ # Compute R-squared from fitted values on full data
1282
+ mu_fitted = np.zeros(n)
1283
+ for sg_val in [1, 2, 3, 4]:
1284
+ for t_val in [0, 1]:
1285
+ cell_mask = (subgroup == sg_val) & (post == t_val)
1286
+ if np.sum(cell_mask) > 0:
1287
+ X_fit = covX[cell_mask]
1288
+ y_fit = y[cell_mask]
1289
+ try:
1290
+ beta_rs, _, _ = solve_ols(
1291
+ X_fit,
1292
+ y_fit,
1293
+ rank_deficient_action=self.rank_deficient_action,
1294
+ )
1295
+ beta_rs = np.where(np.isnan(beta_rs), 0.0, beta_rs)
1296
+ mu_fitted[cell_mask] = X_fit @ beta_rs
1297
+ except (np.linalg.LinAlgError, ValueError):
1298
+ mu_fitted[cell_mask] = np.mean(y_fit)
1299
+ ss_res = np.sum((y - mu_fitted) ** 2)
1300
+ ss_tot = np.sum((y - np.mean(y)) ** 2)
1301
+ r_squared = 1 - (ss_res / ss_tot) if ss_tot > 0 else 0.0
1302
+
1303
+ return att, se, r_squared, pscore_stats, epv_all
1304
+
1305
+ def _fit_predict_mu(
1306
+ self,
1307
+ y: np.ndarray,
1308
+ covX: np.ndarray,
1309
+ subgroup_mask: np.ndarray,
1310
+ time_mask: np.ndarray,
1311
+ n_total: int,
1312
+ weights: Optional[np.ndarray] = None,
1313
+ ) -> np.ndarray:
1314
+ """Fit OLS (or WLS with survey weights) on a subgroup-time cell, predict for all observations."""
1315
+ fit_mask = subgroup_mask & time_mask
1316
+ n_fit = int(np.sum(fit_mask))
1317
+
1318
+ if n_fit == 0:
1319
+ return np.zeros(n_total)
1320
+
1321
+ X_fit = covX[fit_mask]
1322
+ y_fit = y[fit_mask]
1323
+
1324
+ try:
1325
+ if weights is not None:
1326
+ # WLS: transform by sqrt(weights) for weighted least squares
1327
+ w_fit = weights[fit_mask]
1328
+ # Check positive-weight effective sample — subpopulation()
1329
+ # can zero weights leaving rows but an underidentified WLS.
1330
+ n_eff = int(np.count_nonzero(w_fit > 0))
1331
+ n_cols = X_fit.shape[1]
1332
+ if n_eff <= n_cols:
1333
+ if np.sum(w_fit) > 0:
1334
+ return np.full(n_total, np.average(y_fit, weights=w_fit))
1335
+ return np.full(n_total, np.mean(y_fit))
1336
+ sqrt_w = np.sqrt(w_fit)
1337
+ beta, _, _ = solve_ols(
1338
+ X_fit * sqrt_w[:, np.newaxis],
1339
+ y_fit * sqrt_w,
1340
+ rank_deficient_action=self.rank_deficient_action,
1341
+ )
1342
+ else:
1343
+ beta, _, _ = solve_ols(
1344
+ X_fit,
1345
+ y_fit,
1346
+ rank_deficient_action=self.rank_deficient_action,
1347
+ )
1348
+ # Replace NaN coefficients (dropped columns) with 0 for prediction
1349
+ beta = np.where(np.isnan(beta), 0.0, beta)
1350
+ except ValueError:
1351
+ if self.rank_deficient_action == "error":
1352
+ raise
1353
+ if weights is not None:
1354
+ return np.full(n_total, np.average(y_fit, weights=weights[fit_mask]))
1355
+ return np.full(n_total, np.mean(y_fit))
1356
+ except np.linalg.LinAlgError:
1357
+ if weights is not None:
1358
+ return np.full(n_total, np.average(y_fit, weights=weights[fit_mask]))
1359
+ return np.full(n_total, np.mean(y_fit))
1360
+
1361
+ # Prediction uses original-scale X (unchanged)
1362
+ return covX @ beta
1363
+
1364
+ def _compute_did_rc(
1365
+ self,
1366
+ y: np.ndarray,
1367
+ post: np.ndarray,
1368
+ PA4: np.ndarray,
1369
+ PAa: np.ndarray,
1370
+ pscore: np.ndarray,
1371
+ covX: np.ndarray,
1372
+ or_ctrl_pre: np.ndarray,
1373
+ or_ctrl_post: np.ndarray,
1374
+ or_trt_pre: np.ndarray,
1375
+ or_trt_post: np.ndarray,
1376
+ hessian: Optional[np.ndarray],
1377
+ est_method: str,
1378
+ n: int,
1379
+ weights: Optional[np.ndarray] = None,
1380
+ ) -> Tuple[float, np.ndarray]:
1381
+ """
1382
+ Compute a single pairwise DiD (subgroup j vs 4) for RC data.
1383
+
1384
+ Returns ATT and per-observation influence function.
1385
+ Matches R's triplediff::compute_did_rc().
1386
+ """
1387
+ if est_method == "ipw":
1388
+ return self._compute_did_rc_ipw(
1389
+ y,
1390
+ post,
1391
+ PA4,
1392
+ PAa,
1393
+ pscore,
1394
+ covX,
1395
+ hessian,
1396
+ n,
1397
+ weights=weights,
1398
+ )
1399
+ elif est_method == "reg":
1400
+ return self._compute_did_rc_reg(
1401
+ y,
1402
+ post,
1403
+ PA4,
1404
+ PAa,
1405
+ covX,
1406
+ or_ctrl_pre,
1407
+ or_ctrl_post,
1408
+ or_trt_pre,
1409
+ or_trt_post,
1410
+ n,
1411
+ weights=weights,
1412
+ )
1413
+ else:
1414
+ return self._compute_did_rc_dr(
1415
+ y,
1416
+ post,
1417
+ PA4,
1418
+ PAa,
1419
+ pscore,
1420
+ covX,
1421
+ or_ctrl_pre,
1422
+ or_ctrl_post,
1423
+ or_trt_pre,
1424
+ or_trt_post,
1425
+ hessian,
1426
+ n,
1427
+ weights=weights,
1428
+ )
1429
+
1430
+ def _compute_did_rc_ipw(
1431
+ self,
1432
+ y: np.ndarray,
1433
+ post: np.ndarray,
1434
+ PA4: np.ndarray,
1435
+ PAa: np.ndarray,
1436
+ pscore: np.ndarray,
1437
+ covX: np.ndarray,
1438
+ hessian: Optional[np.ndarray],
1439
+ n: int,
1440
+ weights: Optional[np.ndarray] = None,
1441
+ ) -> Tuple[float, np.ndarray]:
1442
+ """IPW DiD for a single pairwise comparison (RC)."""
1443
+ # Riesz representers (IPW weights * indicators)
1444
+ riesz_treat_pre = PA4 * (1 - post)
1445
+ riesz_treat_post = PA4 * post
1446
+ riesz_control_pre = pscore * PAa * (1 - post) / (1 - pscore)
1447
+ riesz_control_post = pscore * PAa * post / (1 - pscore)
1448
+
1449
+ # Incorporate survey weights into Riesz representers
1450
+ if weights is not None:
1451
+ riesz_treat_pre = riesz_treat_pre * weights
1452
+ riesz_treat_post = riesz_treat_post * weights
1453
+ riesz_control_pre = riesz_control_pre * weights
1454
+ riesz_control_post = riesz_control_post * weights
1455
+
1456
+ # Hajek-normalized cell-time means
1457
+ def _hajek(riesz, y_vals):
1458
+ denom = np.mean(riesz)
1459
+ if denom <= 0:
1460
+ return np.zeros_like(riesz), 0.0
1461
+ eta = riesz * y_vals / denom
1462
+ return eta, float(np.mean(eta))
1463
+
1464
+ eta_treat_pre, att_treat_pre = _hajek(riesz_treat_pre, y)
1465
+ eta_treat_post, att_treat_post = _hajek(riesz_treat_post, y)
1466
+ eta_control_pre, att_control_pre = _hajek(riesz_control_pre, y)
1467
+ eta_control_post, att_control_post = _hajek(riesz_control_post, y)
1468
+
1469
+ att = (att_treat_post - att_treat_pre) - (att_control_post - att_control_pre)
1470
+
1471
+ # Influence function
1472
+ inf_treat_pre = eta_treat_pre - riesz_treat_pre * att_treat_pre / np.mean(riesz_treat_pre)
1473
+ inf_treat_post = eta_treat_post - riesz_treat_post * att_treat_post / np.mean(
1474
+ riesz_treat_post
1475
+ )
1476
+ inf_treat = inf_treat_post - inf_treat_pre
1477
+
1478
+ inf_control_pre = eta_control_pre - riesz_control_pre * att_control_pre / np.mean(
1479
+ riesz_control_pre
1480
+ )
1481
+ inf_control_post = eta_control_post - riesz_control_post * att_control_post / np.mean(
1482
+ riesz_control_post
1483
+ )
1484
+ inf_control = inf_control_post - inf_control_pre
1485
+
1486
+ # Propensity score correction for influence function
1487
+ if hessian is not None:
1488
+ score_ps = (PA4 - pscore)[:, None] * covX
1489
+ if weights is not None:
1490
+ score_ps = score_ps * weights[:, None]
1491
+ asy_lin_rep_ps = score_ps @ hessian
1492
+
1493
+ # Riesz representers already incorporate survey weights,
1494
+ # so use np.mean (not np.average with weights) to avoid double-weighting.
1495
+ M2_pre = np.mean(
1496
+ (riesz_control_pre * (y - att_control_pre))[:, None] * covX,
1497
+ axis=0,
1498
+ ) / np.mean(riesz_control_pre)
1499
+ M2_post = np.mean(
1500
+ (riesz_control_post * (y - att_control_post))[:, None] * covX,
1501
+ axis=0,
1502
+ ) / np.mean(riesz_control_post)
1503
+ inf_control_ps = asy_lin_rep_ps @ (M2_post - M2_pre)
1504
+ inf_control = inf_control + inf_control_ps
1505
+
1506
+ inf_func = inf_treat - inf_control
1507
+ return att, inf_func
1508
+
1509
+ def _compute_did_rc_reg(
1510
+ self,
1511
+ y: np.ndarray,
1512
+ post: np.ndarray,
1513
+ PA4: np.ndarray,
1514
+ PAa: np.ndarray,
1515
+ covX: np.ndarray,
1516
+ or_ctrl_pre: np.ndarray,
1517
+ or_ctrl_post: np.ndarray,
1518
+ or_trt_pre: np.ndarray,
1519
+ or_trt_post: np.ndarray,
1520
+ n: int,
1521
+ weights: Optional[np.ndarray] = None,
1522
+ ) -> Tuple[float, np.ndarray]:
1523
+ """Regression adjustment DiD for a single pairwise comparison (RC)."""
1524
+
1525
+ # Helper: weighted or unweighted mean
1526
+ def _wmean(x):
1527
+ if weights is not None:
1528
+ return np.average(x, weights=weights)
1529
+ return np.mean(x)
1530
+
1531
+ # Riesz representers
1532
+ riesz_treat_pre = PA4 * (1 - post)
1533
+ riesz_treat_post = PA4 * post
1534
+ riesz_control = PA4 # weights for OR prediction
1535
+
1536
+ # ATT components
1537
+ reg_att_treat_pre = riesz_treat_pre * y
1538
+ reg_att_treat_post = riesz_treat_post * y
1539
+ reg_att_control = riesz_control * (or_ctrl_post - or_ctrl_pre)
1540
+
1541
+ eta_treat_pre = _wmean(reg_att_treat_pre) / _wmean(riesz_treat_pre)
1542
+ eta_treat_post = _wmean(reg_att_treat_post) / _wmean(riesz_treat_post)
1543
+ eta_control = _wmean(reg_att_control) / _wmean(riesz_control)
1544
+
1545
+ att = (eta_treat_post - eta_treat_pre) - eta_control
1546
+
1547
+ # Influence function
1548
+ # OLS asymptotic linear representation for pre/post
1549
+ # When survey weights present, include them in both score and bread
1550
+ # for consistency with the weighted OLS fit
1551
+ weights_ols_pre = PAa * (1 - post)
1552
+ if weights is not None:
1553
+ wols_x_pre = (weights_ols_pre * weights)[:, None] * covX
1554
+ wols_eX_pre = (weights_ols_pre * weights * (y - or_ctrl_pre))[:, None] * covX
1555
+ XpX_pre = wols_x_pre.T @ covX / n
1556
+ else:
1557
+ wols_x_pre = weights_ols_pre[:, None] * covX
1558
+ wols_eX_pre = (weights_ols_pre * (y - or_ctrl_pre))[:, None] * covX
1559
+ XpX_pre = wols_x_pre.T @ covX / n
1560
+ try:
1561
+ XpX_inv_pre = np.linalg.inv(XpX_pre)
1562
+ except np.linalg.LinAlgError:
1563
+ XpX_inv_pre = np.linalg.pinv(XpX_pre)
1564
+ asy_lin_rep_ols_pre = wols_eX_pre @ XpX_inv_pre
1565
+
1566
+ weights_ols_post = PAa * post
1567
+ if weights is not None:
1568
+ wols_x_post = (weights_ols_post * weights)[:, None] * covX
1569
+ wols_eX_post = (weights_ols_post * weights * (y - or_ctrl_post))[:, None] * covX
1570
+ XpX_post = wols_x_post.T @ covX / n
1571
+ else:
1572
+ wols_x_post = weights_ols_post[:, None] * covX
1573
+ wols_eX_post = (weights_ols_post * (y - or_ctrl_post))[:, None] * covX
1574
+ XpX_post = wols_x_post.T @ covX / n
1575
+ try:
1576
+ XpX_inv_post = np.linalg.inv(XpX_post)
1577
+ except np.linalg.LinAlgError:
1578
+ XpX_inv_post = np.linalg.pinv(XpX_post)
1579
+ asy_lin_rep_ols_post = wols_eX_post @ XpX_inv_post
1580
+
1581
+ inf_treat_pre = (reg_att_treat_pre - riesz_treat_pre * eta_treat_pre) / _wmean(
1582
+ riesz_treat_pre
1583
+ )
1584
+ inf_treat_post = (reg_att_treat_post - riesz_treat_post * eta_treat_post) / _wmean(
1585
+ riesz_treat_post
1586
+ )
1587
+ inf_treat = inf_treat_post - inf_treat_pre
1588
+
1589
+ inf_control_1 = reg_att_control - riesz_control * eta_control
1590
+ if weights is not None:
1591
+ M1 = np.average(riesz_control[:, None] * covX, axis=0, weights=weights)
1592
+ else:
1593
+ M1 = np.mean(riesz_control[:, None] * covX, axis=0)
1594
+ inf_control_2_post = asy_lin_rep_ols_post @ M1
1595
+ inf_control_2_pre = asy_lin_rep_ols_pre @ M1
1596
+ inf_control = (inf_control_1 + inf_control_2_post - inf_control_2_pre) / _wmean(
1597
+ riesz_control
1598
+ )
1599
+
1600
+ inf_func = inf_treat - inf_control
1601
+ return att, inf_func
1602
+
1603
+ def _compute_did_rc_dr(
1604
+ self,
1605
+ y: np.ndarray,
1606
+ post: np.ndarray,
1607
+ PA4: np.ndarray,
1608
+ PAa: np.ndarray,
1609
+ pscore: np.ndarray,
1610
+ covX: np.ndarray,
1611
+ or_ctrl_pre: np.ndarray,
1612
+ or_ctrl_post: np.ndarray,
1613
+ or_trt_pre: np.ndarray,
1614
+ or_trt_post: np.ndarray,
1615
+ hessian: Optional[np.ndarray],
1616
+ n: int,
1617
+ weights: Optional[np.ndarray] = None,
1618
+ ) -> Tuple[float, np.ndarray]:
1619
+ """Doubly robust DiD for a single pairwise comparison (RC)."""
1620
+ or_ctrl = post * or_ctrl_post + (1 - post) * or_ctrl_pre
1621
+
1622
+ # Riesz representers
1623
+ riesz_treat_pre = PA4 * (1 - post)
1624
+ riesz_treat_post = PA4 * post
1625
+ riesz_control_pre = pscore * PAa * (1 - post) / (1 - pscore)
1626
+ riesz_control_post = pscore * PAa * post / (1 - pscore)
1627
+ riesz_d = PA4
1628
+ riesz_dt1 = PA4 * post
1629
+ riesz_dt0 = PA4 * (1 - post)
1630
+
1631
+ # Incorporate survey weights into Riesz representers
1632
+ if weights is not None:
1633
+ riesz_treat_pre = riesz_treat_pre * weights
1634
+ riesz_treat_post = riesz_treat_post * weights
1635
+ riesz_control_pre = riesz_control_pre * weights
1636
+ riesz_control_post = riesz_control_post * weights
1637
+ riesz_d = riesz_d * weights
1638
+ riesz_dt1 = riesz_dt1 * weights
1639
+ riesz_dt0 = riesz_dt0 * weights
1640
+
1641
+ # DR cell-time components
1642
+ def _safe_ratio(num, denom):
1643
+ return num / denom if denom > 0 else 0.0
1644
+
1645
+ eta_treat_pre = riesz_treat_pre * (y - or_ctrl) * _safe_ratio(1, np.mean(riesz_treat_pre))
1646
+ eta_treat_post = (
1647
+ riesz_treat_post * (y - or_ctrl) * _safe_ratio(1, np.mean(riesz_treat_post))
1648
+ )
1649
+ eta_control_pre = (
1650
+ riesz_control_pre * (y - or_ctrl) * _safe_ratio(1, np.mean(riesz_control_pre))
1651
+ )
1652
+ eta_control_post = (
1653
+ riesz_control_post * (y - or_ctrl) * _safe_ratio(1, np.mean(riesz_control_post))
1654
+ )
1655
+
1656
+ # Efficiency correction (OR bias correction)
1657
+ eta_d_post = riesz_d * (or_trt_post - or_ctrl_post) * _safe_ratio(1, np.mean(riesz_d))
1658
+ eta_dt1_post = riesz_dt1 * (or_trt_post - or_ctrl_post) * _safe_ratio(1, np.mean(riesz_dt1))
1659
+ eta_d_pre = riesz_d * (or_trt_pre - or_ctrl_pre) * _safe_ratio(1, np.mean(riesz_d))
1660
+ eta_dt0_pre = riesz_dt0 * (or_trt_pre - or_ctrl_pre) * _safe_ratio(1, np.mean(riesz_dt0))
1661
+
1662
+ att_treat_pre = float(np.mean(eta_treat_pre))
1663
+ att_treat_post = float(np.mean(eta_treat_post))
1664
+ att_control_pre = float(np.mean(eta_control_pre))
1665
+ att_control_post = float(np.mean(eta_control_post))
1666
+ att_d_post = float(np.mean(eta_d_post))
1667
+ att_dt1_post = float(np.mean(eta_dt1_post))
1668
+ att_d_pre = float(np.mean(eta_d_pre))
1669
+ att_dt0_pre = float(np.mean(eta_dt0_pre))
1670
+
1671
+ att = (
1672
+ (att_treat_post - att_treat_pre)
1673
+ - (att_control_post - att_control_pre)
1674
+ + (att_d_post - att_dt1_post)
1675
+ - (att_d_pre - att_dt0_pre)
1676
+ )
1677
+
1678
+ # --- Influence function ---
1679
+ # OLS asymptotic linear representations (control subgroup)
1680
+ weights_ols_pre = PAa * (1 - post)
1681
+ if weights is not None:
1682
+ wols_x_pre = (weights_ols_pre * weights)[:, None] * covX
1683
+ wols_eX_pre = (weights_ols_pre * weights * (y - or_ctrl_pre))[:, None] * covX
1684
+ XpX_pre = wols_x_pre.T @ covX / n
1685
+ else:
1686
+ wols_x_pre = weights_ols_pre[:, None] * covX
1687
+ wols_eX_pre = (weights_ols_pre * (y - or_ctrl_pre))[:, None] * covX
1688
+ XpX_pre = wols_x_pre.T @ covX / n
1689
+ try:
1690
+ XpX_inv_pre = np.linalg.inv(XpX_pre)
1691
+ except np.linalg.LinAlgError:
1692
+ XpX_inv_pre = np.linalg.pinv(XpX_pre)
1693
+ asy_lin_rep_ols_pre = wols_eX_pre @ XpX_inv_pre
1694
+
1695
+ weights_ols_post = PAa * post
1696
+ if weights is not None:
1697
+ wols_x_post = (weights_ols_post * weights)[:, None] * covX
1698
+ wols_eX_post = (weights_ols_post * weights * (y - or_ctrl_post))[:, None] * covX
1699
+ XpX_post = wols_x_post.T @ covX / n
1700
+ else:
1701
+ wols_x_post = weights_ols_post[:, None] * covX
1702
+ wols_eX_post = (weights_ols_post * (y - or_ctrl_post))[:, None] * covX
1703
+ XpX_post = wols_x_post.T @ covX / n
1704
+ try:
1705
+ XpX_inv_post = np.linalg.inv(XpX_post)
1706
+ except np.linalg.LinAlgError:
1707
+ XpX_inv_post = np.linalg.pinv(XpX_post)
1708
+ asy_lin_rep_ols_post = wols_eX_post @ XpX_inv_post
1709
+
1710
+ # OLS representations (treated subgroup)
1711
+ weights_ols_pre_treat = PA4 * (1 - post)
1712
+ if weights is not None:
1713
+ wols_x_pre_treat = (weights_ols_pre_treat * weights)[:, None] * covX
1714
+ wols_eX_pre_treat = (weights_ols_pre_treat * weights * (y - or_trt_pre))[:, None] * covX
1715
+ XpX_pre_treat = wols_x_pre_treat.T @ covX / n
1716
+ else:
1717
+ wols_x_pre_treat = weights_ols_pre_treat[:, None] * covX
1718
+ wols_eX_pre_treat = (weights_ols_pre_treat * (y - or_trt_pre))[:, None] * covX
1719
+ XpX_pre_treat = wols_x_pre_treat.T @ covX / n
1720
+ try:
1721
+ XpX_inv_pre_treat = np.linalg.inv(XpX_pre_treat)
1722
+ except np.linalg.LinAlgError:
1723
+ XpX_inv_pre_treat = np.linalg.pinv(XpX_pre_treat)
1724
+ asy_lin_rep_ols_pre_treat = wols_eX_pre_treat @ XpX_inv_pre_treat
1725
+
1726
+ weights_ols_post_treat = PA4 * post
1727
+ if weights is not None:
1728
+ wols_x_post_treat = (weights_ols_post_treat * weights)[:, None] * covX
1729
+ wols_eX_post_treat = (weights_ols_post_treat * weights * (y - or_trt_post))[
1730
+ :, None
1731
+ ] * covX
1732
+ XpX_post_treat = wols_x_post_treat.T @ covX / n
1733
+ else:
1734
+ wols_x_post_treat = weights_ols_post_treat[:, None] * covX
1735
+ wols_eX_post_treat = (weights_ols_post_treat * (y - or_trt_post))[:, None] * covX
1736
+ XpX_post_treat = wols_x_post_treat.T @ covX / n
1737
+ try:
1738
+ XpX_inv_post_treat = np.linalg.inv(XpX_post_treat)
1739
+ except np.linalg.LinAlgError:
1740
+ XpX_inv_post_treat = np.linalg.pinv(XpX_post_treat)
1741
+ asy_lin_rep_ols_post_treat = wols_eX_post_treat @ XpX_inv_post_treat
1742
+
1743
+ # Propensity score linear representation
1744
+ score_ps = (PA4 - pscore)[:, None] * covX
1745
+ if weights is not None:
1746
+ score_ps = score_ps * weights[:, None]
1747
+ if hessian is not None:
1748
+ asy_lin_rep_ps = score_ps @ hessian
1749
+ else:
1750
+ asy_lin_rep_ps = np.zeros_like(score_ps)
1751
+
1752
+ # Treat influence function components
1753
+ m_riesz_treat_pre = np.mean(riesz_treat_pre)
1754
+ m_riesz_treat_post = np.mean(riesz_treat_post)
1755
+
1756
+ inf_treat_pre = (
1757
+ (eta_treat_pre - riesz_treat_pre * att_treat_pre / m_riesz_treat_pre)
1758
+ if m_riesz_treat_pre > 0
1759
+ else np.zeros(n)
1760
+ )
1761
+ inf_treat_post = (
1762
+ (eta_treat_post - riesz_treat_post * att_treat_post / m_riesz_treat_post)
1763
+ if m_riesz_treat_post > 0
1764
+ else np.zeros(n)
1765
+ )
1766
+
1767
+ # OR correction for treated
1768
+ # Riesz representers already incorporate survey weights,
1769
+ # so use np.mean (not weighted average) to avoid double-weighting.
1770
+ M1_post = (
1771
+ (-np.mean((riesz_treat_post * post)[:, None] * covX, axis=0) / m_riesz_treat_post)
1772
+ if m_riesz_treat_post > 0
1773
+ else np.zeros(covX.shape[1])
1774
+ )
1775
+ M1_pre = (
1776
+ (-np.mean((riesz_treat_pre * (1 - post))[:, None] * covX, axis=0) / m_riesz_treat_pre)
1777
+ if m_riesz_treat_pre > 0
1778
+ else np.zeros(covX.shape[1])
1779
+ )
1780
+ inf_treat_or_post = asy_lin_rep_ols_post @ M1_post
1781
+ inf_treat_or_pre = asy_lin_rep_ols_pre @ M1_pre
1782
+
1783
+ # Control influence function components
1784
+ m_riesz_control_pre = np.mean(riesz_control_pre)
1785
+ m_riesz_control_post = np.mean(riesz_control_post)
1786
+
1787
+ inf_control_pre = (
1788
+ (eta_control_pre - riesz_control_pre * att_control_pre / m_riesz_control_pre)
1789
+ if m_riesz_control_pre > 0
1790
+ else np.zeros(n)
1791
+ )
1792
+ inf_control_post = (
1793
+ (eta_control_post - riesz_control_post * att_control_post / m_riesz_control_post)
1794
+ if m_riesz_control_post > 0
1795
+ else np.zeros(n)
1796
+ )
1797
+
1798
+ # PS correction for control
1799
+ M2_pre = (
1800
+ (
1801
+ np.mean(
1802
+ (riesz_control_pre * (y - or_ctrl - att_control_pre))[:, None] * covX, axis=0
1803
+ )
1804
+ / m_riesz_control_pre
1805
+ )
1806
+ if m_riesz_control_pre > 0
1807
+ else np.zeros(covX.shape[1])
1808
+ )
1809
+ M2_post = (
1810
+ (
1811
+ np.mean(
1812
+ (riesz_control_post * (y - or_ctrl - att_control_post))[:, None] * covX, axis=0
1813
+ )
1814
+ / m_riesz_control_post
1815
+ )
1816
+ if m_riesz_control_post > 0
1817
+ else np.zeros(covX.shape[1])
1818
+ )
1819
+ inf_control_ps = asy_lin_rep_ps @ (M2_post - M2_pre)
1820
+
1821
+ # OR correction for control
1822
+ M3_post = (
1823
+ (-np.mean((riesz_control_post * post)[:, None] * covX, axis=0) / m_riesz_control_post)
1824
+ if m_riesz_control_post > 0
1825
+ else np.zeros(covX.shape[1])
1826
+ )
1827
+ M3_pre = (
1828
+ (
1829
+ -np.mean((riesz_control_pre * (1 - post))[:, None] * covX, axis=0)
1830
+ / m_riesz_control_pre
1831
+ )
1832
+ if m_riesz_control_pre > 0
1833
+ else np.zeros(covX.shape[1])
1834
+ )
1835
+ inf_control_or_post = asy_lin_rep_ols_post @ M3_post
1836
+ inf_control_or_pre = asy_lin_rep_ols_pre @ M3_pre
1837
+
1838
+ # Efficiency correction
1839
+ m_riesz_d = np.mean(riesz_d)
1840
+ m_riesz_dt1 = np.mean(riesz_dt1)
1841
+ m_riesz_dt0 = np.mean(riesz_dt0)
1842
+
1843
+ inf_eff1 = (eta_d_post - riesz_d * att_d_post / m_riesz_d) if m_riesz_d > 0 else np.zeros(n)
1844
+ inf_eff2 = (
1845
+ (eta_dt1_post - riesz_dt1 * att_dt1_post / m_riesz_dt1)
1846
+ if m_riesz_dt1 > 0
1847
+ else np.zeros(n)
1848
+ )
1849
+ inf_eff3 = (eta_d_pre - riesz_d * att_d_pre / m_riesz_d) if m_riesz_d > 0 else np.zeros(n)
1850
+ inf_eff4 = (
1851
+ (eta_dt0_pre - riesz_dt0 * att_dt0_pre / m_riesz_dt0)
1852
+ if m_riesz_dt0 > 0
1853
+ else np.zeros(n)
1854
+ )
1855
+ inf_eff = (inf_eff1 - inf_eff2) - (inf_eff3 - inf_eff4)
1856
+
1857
+ # OR combination
1858
+ mom_post = (
1859
+ np.mean(
1860
+ (riesz_d[:, None] / m_riesz_d - riesz_dt1[:, None] / m_riesz_dt1) * covX, axis=0
1861
+ )
1862
+ if (m_riesz_d > 0 and m_riesz_dt1 > 0)
1863
+ else np.zeros(covX.shape[1])
1864
+ )
1865
+ mom_pre = (
1866
+ np.mean(
1867
+ (riesz_d[:, None] / m_riesz_d - riesz_dt0[:, None] / m_riesz_dt0) * covX, axis=0
1868
+ )
1869
+ if (m_riesz_d > 0 and m_riesz_dt0 > 0)
1870
+ else np.zeros(covX.shape[1])
1871
+ )
1872
+ inf_or_post = (asy_lin_rep_ols_post_treat - asy_lin_rep_ols_post) @ mom_post
1873
+ inf_or_pre = (asy_lin_rep_ols_pre_treat - asy_lin_rep_ols_pre) @ mom_pre
1874
+
1875
+ inf_treat_or = inf_treat_or_post + inf_treat_or_pre
1876
+ inf_control_or = inf_control_or_post + inf_control_or_pre
1877
+ inf_or = inf_or_post - inf_or_pre
1878
+
1879
+ inf_treat = inf_treat_post - inf_treat_pre + inf_treat_or
1880
+ inf_control = inf_control_post - inf_control_pre + inf_control_ps + inf_control_or
1881
+
1882
+ inf_func = inf_treat - inf_control + inf_eff + inf_or
1883
+ return att, inf_func
1884
+
1885
+ def get_params(self) -> Dict[str, Any]:
1886
+ """
1887
+ Get estimator parameters (sklearn-compatible).
1888
+
1889
+ Returns
1890
+ -------
1891
+ Dict[str, Any]
1892
+ Estimator parameters.
1893
+ """
1894
+ return {
1895
+ "estimation_method": self.estimation_method,
1896
+ "robust": self.robust,
1897
+ "cluster": self.cluster,
1898
+ "alpha": self.alpha,
1899
+ "pscore_trim": self.pscore_trim,
1900
+ "rank_deficient_action": self.rank_deficient_action,
1901
+ "epv_threshold": self.epv_threshold,
1902
+ "pscore_fallback": self.pscore_fallback,
1903
+ }
1904
+
1905
+ def set_params(self, **params) -> "TripleDifference":
1906
+ """
1907
+ Set estimator parameters (sklearn-compatible).
1908
+
1909
+ Parameters
1910
+ ----------
1911
+ **params
1912
+ Estimator parameters.
1913
+
1914
+ Returns
1915
+ -------
1916
+ self
1917
+ """
1918
+ for key, value in params.items():
1919
+ if hasattr(self, key):
1920
+ setattr(self, key, value)
1921
+ else:
1922
+ raise ValueError(f"Unknown parameter: {key}")
1923
+ return self
1924
+
1925
+ def summary(self) -> str:
1926
+ """
1927
+ Get summary of estimation results.
1928
+
1929
+ Returns
1930
+ -------
1931
+ str
1932
+ Formatted summary.
1933
+ """
1934
+ if not self.is_fitted_:
1935
+ raise RuntimeError("Model must be fitted before calling summary()")
1936
+ assert self.results_ is not None
1937
+ return self.results_.summary()
1938
+
1939
+ def print_summary(self) -> None:
1940
+ """Print summary to stdout."""
1941
+ print(self.summary())
1942
+
1943
+
1944
+ # =============================================================================
1945
+ # Convenience function
1946
+ # =============================================================================
1947
+
1948
+
1949
+ def triple_difference(
1950
+ data: pd.DataFrame,
1951
+ outcome: str,
1952
+ group: str,
1953
+ partition: str,
1954
+ time: str,
1955
+ covariates: Optional[List[str]] = None,
1956
+ estimation_method: str = "dr",
1957
+ robust: bool = True,
1958
+ cluster: Optional[str] = None,
1959
+ alpha: float = 0.05,
1960
+ rank_deficient_action: str = "warn",
1961
+ epv_threshold: float = 10,
1962
+ pscore_fallback: str = "error",
1963
+ survey_design: object = None,
1964
+ ) -> TripleDifferenceResults:
1965
+ """
1966
+ Estimate Triple Difference (DDD) treatment effect.
1967
+
1968
+ Convenience function that creates a TripleDifference estimator and
1969
+ fits it to the data in one step.
1970
+
1971
+ Parameters
1972
+ ----------
1973
+ data : pd.DataFrame
1974
+ DataFrame containing all variables.
1975
+ outcome : str
1976
+ Name of the outcome variable column.
1977
+ group : str
1978
+ Name of the group indicator column (0/1).
1979
+ 1 = treated group (e.g., states that enacted policy).
1980
+ partition : str
1981
+ Name of the partition/eligibility indicator column (0/1).
1982
+ 1 = eligible partition (e.g., women, targeted demographic).
1983
+ time : str
1984
+ Name of the time period indicator column (0/1).
1985
+ 1 = post-treatment period.
1986
+ covariates : list of str, optional
1987
+ List of covariate column names to adjust for.
1988
+ estimation_method : str, default="dr"
1989
+ Estimation method: "dr" (doubly robust), "reg" (regression),
1990
+ or "ipw" (inverse probability weighting).
1991
+ robust : bool, default=True
1992
+ Whether to use heteroskedasticity-robust standard errors.
1993
+ Note: influence function-based SEs are inherently robust to
1994
+ heteroskedasticity, so this parameter has no effect. Retained
1995
+ for API compatibility.
1996
+ cluster : str, optional
1997
+ Column name for cluster-robust standard errors.
1998
+ alpha : float, default=0.05
1999
+ Significance level for confidence intervals.
2000
+ rank_deficient_action : str, default="warn"
2001
+ Action when design matrix is rank-deficient:
2002
+ - "warn": Issue warning and drop linearly dependent columns (default)
2003
+ - "error": Raise ValueError
2004
+ - "silent": Drop columns silently without warning
2005
+ epv_threshold : float, default=10
2006
+ Events Per Variable threshold for propensity score logit.
2007
+ pscore_fallback : str, default="error"
2008
+ Action when propensity score estimation fails:
2009
+ - "error": Raise (default)
2010
+ - "unconditional": Fall back to unconditional propensity
2011
+
2012
+ Returns
2013
+ -------
2014
+ TripleDifferenceResults
2015
+ Object containing estimation results.
2016
+
2017
+ Examples
2018
+ --------
2019
+ >>> from diff_diff import triple_difference
2020
+ >>> results = triple_difference(
2021
+ ... data,
2022
+ ... outcome='earnings',
2023
+ ... group='policy_state',
2024
+ ... partition='female',
2025
+ ... time='post_policy',
2026
+ ... covariates=['age', 'education']
2027
+ ... )
2028
+ >>> print(f"ATT: {results.att:.3f} (SE: {results.se:.3f})")
2029
+ """
2030
+ estimator = TripleDifference(
2031
+ estimation_method=estimation_method,
2032
+ robust=robust,
2033
+ cluster=cluster,
2034
+ alpha=alpha,
2035
+ rank_deficient_action=rank_deficient_action,
2036
+ epv_threshold=epv_threshold,
2037
+ pscore_fallback=pscore_fallback,
2038
+ )
2039
+ return estimator.fit(
2040
+ data=data,
2041
+ outcome=outcome,
2042
+ group=group,
2043
+ partition=partition,
2044
+ time=time,
2045
+ covariates=covariates,
2046
+ survey_design=survey_design,
2047
+ )