-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathpower.py
More file actions
2588 lines (2293 loc) · 84.1 KB
/
power.py
File metadata and controls
2588 lines (2293 loc) · 84.1 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
"""
Power analysis tools for difference-in-differences study design.
This module provides power calculations and simulation-based power analysis
for DiD study design, helping practitioners answer questions like:
- "How many units do I need to detect an effect of size X?"
- "What is the minimum detectable effect given my sample size?"
- "What power do I have to detect a given effect?"
References
----------
Bloom, H. S. (1995). "Minimum Detectable Effects: A Simple Way to Report the
Statistical Power of Experimental Designs." Evaluation Review, 19(5), 547-556.
Burlig, F., Preonas, L., & Woerman, M. (2020). "Panel Data and Experimental Design."
Journal of Development Economics, 144, 102458.
Djimeu, E. W., & Houndolo, D.-G. (2016). "Power Calculation for Causal Inference
in Social Science: Sample Size and Minimum Detectable Effect Determination."
Journal of Development Effectiveness, 8(4), 508-527.
"""
import warnings
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from scipy import stats
# Maximum sample size returned when effect is too small to detect
# (e.g., zero effect or extremely small relative to noise)
MAX_SAMPLE_SIZE = 2**31 - 1
# ---------------------------------------------------------------------------
# Estimator registry — maps estimator class names to DGP/fit/extract profiles
# ---------------------------------------------------------------------------
@dataclass
class _EstimatorProfile:
"""Internal profile describing how to run power simulations for an estimator."""
default_dgp: Callable
dgp_kwargs_builder: Callable
fit_kwargs_builder: Callable
result_extractor: Callable
min_n: int = 20
# -- DGP kwargs adapters -----------------------------------------------------
def _basic_dgp_kwargs(
n_units: int,
n_periods: int,
treatment_effect: float,
treatment_fraction: float,
treatment_period: int,
sigma: float,
) -> Dict[str, Any]:
return dict(
n_units=n_units,
n_periods=n_periods,
treatment_effect=treatment_effect,
treatment_fraction=treatment_fraction,
treatment_period=treatment_period,
noise_sd=sigma,
)
def _staggered_dgp_kwargs(
n_units: int,
n_periods: int,
treatment_effect: float,
treatment_fraction: float,
treatment_period: int,
sigma: float,
) -> Dict[str, Any]:
return dict(
n_units=n_units,
n_periods=n_periods,
treatment_effect=treatment_effect,
never_treated_frac=1 - treatment_fraction,
cohort_periods=[treatment_period],
dynamic_effects=False,
noise_sd=sigma,
)
def _factor_dgp_kwargs(
n_units: int,
n_periods: int,
treatment_effect: float,
treatment_fraction: float,
treatment_period: int,
sigma: float,
) -> Dict[str, Any]:
n_pre = treatment_period
n_post = n_periods - treatment_period
return dict(
n_units=n_units,
n_pre=n_pre,
n_post=n_post,
n_treated=max(1, int(n_units * treatment_fraction)),
treatment_effect=treatment_effect,
noise_sd=sigma,
)
def _ddd_dgp_kwargs(
n_units: int,
n_periods: int,
treatment_effect: float,
treatment_fraction: float,
treatment_period: int,
sigma: float,
) -> Dict[str, Any]:
return dict(
n_per_cell=max(2, n_units // 8),
treatment_effect=treatment_effect,
noise_sd=sigma,
)
# -- Fit kwargs builders ------------------------------------------------------
def _basic_fit_kwargs(
data: pd.DataFrame,
n_units: int,
n_periods: int,
treatment_period: int,
) -> Dict[str, Any]:
return dict(outcome="outcome", treatment="treated", time="post")
def _twfe_fit_kwargs(
data: pd.DataFrame,
n_units: int,
n_periods: int,
treatment_period: int,
) -> Dict[str, Any]:
return dict(outcome="outcome", treatment="treated", time="post", unit="unit")
def _multiperiod_fit_kwargs(
data: pd.DataFrame,
n_units: int,
n_periods: int,
treatment_period: int,
) -> Dict[str, Any]:
return dict(
outcome="outcome",
treatment="treated",
time="period",
post_periods=list(range(treatment_period, n_periods)),
)
def _staggered_fit_kwargs(
data: pd.DataFrame,
n_units: int,
n_periods: int,
treatment_period: int,
) -> Dict[str, Any]:
return dict(outcome="outcome", unit="unit", time="period", first_treat="first_treat")
def _ddd_fit_kwargs(
data: pd.DataFrame,
n_units: int,
n_periods: int,
treatment_period: int,
) -> Dict[str, Any]:
return dict(outcome="outcome", group="group", partition="partition", time="time")
def _trop_fit_kwargs(
data: pd.DataFrame,
n_units: int,
n_periods: int,
treatment_period: int,
) -> Dict[str, Any]:
return dict(outcome="outcome", treatment="treated", unit="unit", time="period")
def _sdid_fit_kwargs(
data: pd.DataFrame,
n_units: int,
n_periods: int,
treatment_period: int,
) -> Dict[str, Any]:
periods = sorted(data["period"].unique())
post_periods = [p for p in periods if p >= treatment_period]
return dict(
outcome="outcome",
treatment="treat",
unit="unit",
time="period",
post_periods=post_periods,
)
# -- Result extractors --------------------------------------------------------
def _extract_simple(result: Any) -> Tuple[float, float, float, Tuple[float, float]]:
return (result.att, result.se, result.p_value, result.conf_int)
def _extract_multiperiod(
result: Any,
) -> Tuple[float, float, float, Tuple[float, float]]:
return (result.avg_att, result.avg_se, result.avg_p_value, result.avg_conf_int)
def _extract_staggered(
result: Any,
) -> Tuple[float, float, float, Tuple[float, float]]:
_nan = float("nan")
_nan_ci = (_nan, _nan)
def _first(r: Any, *attrs: str, default: Any = _nan) -> Any:
for a in attrs:
v = getattr(r, a, None)
if v is not None:
return v
return default
return (
result.overall_att,
_first(result, "overall_se", "overall_att_se"),
_first(result, "overall_p_value", "overall_att_p_value"),
_first(result, "overall_conf_int", "overall_att_ci", default=_nan_ci),
)
# Keys derived from simulate_power() public params — overriding these
# via data_generator_kwargs would desync the DGP from the result object.
_PROTECTED_DGP_KEYS = frozenset(
{
"treatment_effect", # → true_effect in results / MDE search variable
"noise_sd", # → sigma param
"n_units", # → sample-size search variable
"n_periods", # → n_periods param
"treatment_fraction", # → treatment_fraction param
"treatment_period", # → treatment_period param
"n_pre", # → derived from treatment_period in factor-model DGPs
"n_post", # → derived from n_periods - treatment_period in factor-model DGPs
}
)
# -- Staggered DGP compatibility check ----------------------------------------
_STAGGERED_ESTIMATORS = frozenset(
{
"CallawaySantAnna",
"SunAbraham",
"ImputationDiD",
"TwoStageDiD",
"StackedDiD",
"EfficientDiD",
}
)
def _check_staggered_dgp_compat(
estimator: Any,
data_generator_kwargs: Optional[Dict[str, Any]],
) -> None:
"""Warn if a staggered estimator's settings don't match the default DGP."""
name = type(estimator).__name__
if name not in _STAGGERED_ESTIMATORS:
return
dgp_overrides = data_generator_kwargs or {}
cohort_periods = dgp_overrides.get("cohort_periods")
has_multi_cohort = cohort_periods is not None and len(set(cohort_periods)) >= 2
issues: List[str] = []
# Check control_group="not_yet_treated" (CS, SA)
cg = getattr(estimator, "control_group", "never_treated")
if cg == "not_yet_treated" and not has_multi_cohort:
issues.append(
f' - {name} has control_group="not_yet_treated" but the default '
f"DGP generates a single treatment cohort with never-treated "
f"controls. Power may not reflect the intended not-yet-treated "
f"design.\n"
f" Fix: pass data_generator_kwargs="
f'{{"cohort_periods": [2, 4], "never_treated_frac": 0.0}} '
f"(or a custom data_generator)."
)
# Check anticipation > 0 (all staggered)
antic = getattr(estimator, "anticipation", 0)
if antic > 0:
issues.append(
f" - {name} has anticipation={antic} but the default DGP does "
f"not model anticipatory effects. The estimator will look for "
f"treatment effects {antic} period(s) before the DGP generates "
f"them, biasing power estimates.\n"
f" Fix: supply a custom data_generator that shifts the "
f"effect onset."
)
# Check clean_control on StackedDiD
if name == "StackedDiD":
cc = getattr(estimator, "clean_control", "not_yet_treated")
if cc == "strict" and not has_multi_cohort:
issues.append(
' - StackedDiD has clean_control="strict" but the default '
"single-cohort DGP makes strict controls equivalent to "
"never-treated controls.\n"
" Fix: pass data_generator_kwargs="
'{"cohort_periods": [2, 4]} '
"to test true strict clean-control behavior."
)
if issues:
msg = (
f"Staggered power DGP mismatch for {name}. The default "
f"single-cohort DGP may not match the estimator "
f"configuration:\n" + "\n".join(issues)
)
warnings.warn(msg, UserWarning, stacklevel=2)
def _ddd_effective_n(
n_units: int, data_generator_kwargs: Optional[Dict[str, Any]]
) -> Optional[int]:
"""Return effective DDD sample size, or None if no rounding occurred."""
overrides = data_generator_kwargs or {}
if "n_per_cell" in overrides:
eff = overrides["n_per_cell"] * 8
else:
eff = max(2, n_units // 8) * 8
return eff if eff != n_units else None
def _check_ddd_dgp_compat(
n_units: int,
n_periods: int,
treatment_fraction: float,
treatment_period: int,
data_generator_kwargs: Optional[Dict[str, Any]],
) -> None:
"""Warn when simulation inputs don't match DDD's fixed 2×2×2 design."""
issues: List[str] = []
# DDD is a fixed 2-period factorial; n_periods and treatment_period are ignored
if n_periods != 2:
issues.append(
f"n_periods={n_periods} is ignored (DDD uses a fixed " f"2-period design: pre/post)"
)
if treatment_period != 1:
issues.append(
f"treatment_period={treatment_period} is ignored (DDD "
f"always treats in the second period)"
)
# DDD's 2×2×2 factorial has inherent 50% treatment fraction
if treatment_fraction != 0.5:
issues.append(
f"treatment_fraction={treatment_fraction} is ignored "
f"(DDD uses a balanced 2×2×2 factorial where 50% of "
f"groups are treated)"
)
# n_units rounding: n_per_cell = max(2, n_units // 8)
eff_n = _ddd_effective_n(n_units, data_generator_kwargs)
if eff_n is not None:
eff_n_per_cell = eff_n // 8
issues.append(
f"effective sample size is {eff_n} "
f"(n_per_cell={eff_n_per_cell} × 8 cells), "
f"not the requested n_units={n_units}"
)
if issues:
warnings.warn(
"TripleDifference uses a fixed 2×2×2 factorial DGP "
"(group × partition × time). "
+ "; ".join(issues)
+ ". Pass a custom data_generator for non-standard DDD designs.",
UserWarning,
stacklevel=2,
)
def _check_sdid_placebo_data(
data: pd.DataFrame,
estimator: Any,
est_kwargs: Dict[str, Any],
) -> None:
"""Check SyntheticDiD placebo feasibility on realized data.
This catches infeasible designs on the custom-DGP path where the
pre-generation check (which uses ``n_units * treatment_fraction``)
cannot run because treatment allocation is determined by the DGP.
"""
vm = getattr(estimator, "variance_method", "placebo")
if vm != "placebo":
return
treat_col = est_kwargs.get("treatment", "treat")
unit_col = est_kwargs.get("unit", "unit")
if treat_col not in data.columns or unit_col not in data.columns:
return # fit will fail with a more specific error
unit_treat = data.groupby(unit_col)[treat_col].first()
n_treated = int(unit_treat.sum())
n_control = len(unit_treat) - n_treated
if n_control <= n_treated:
raise ValueError(
f"SyntheticDiD placebo variance requires more control than "
f"treated units, but the generated data has n_control={n_control}, "
f"n_treated={n_treated}. Either adjust your data_generator so that "
f"n_control > n_treated, or use "
f"SyntheticDiD(variance_method='bootstrap')."
)
# -- Registry construction (deferred to avoid import-time cost) ---------------
_ESTIMATOR_REGISTRY: Optional[Dict[str, _EstimatorProfile]] = None
def _get_registry() -> Dict[str, _EstimatorProfile]:
"""Lazily build and return the estimator registry."""
global _ESTIMATOR_REGISTRY # noqa: PLW0603
if _ESTIMATOR_REGISTRY is not None:
return _ESTIMATOR_REGISTRY
from diff_diff.prep import (
generate_ddd_data,
generate_did_data,
generate_factor_data,
generate_staggered_data,
)
_ESTIMATOR_REGISTRY = {
# --- Basic DiD group ---
"DifferenceInDifferences": _EstimatorProfile(
default_dgp=generate_did_data,
dgp_kwargs_builder=_basic_dgp_kwargs,
fit_kwargs_builder=_basic_fit_kwargs,
result_extractor=_extract_simple,
min_n=20,
),
"TwoWayFixedEffects": _EstimatorProfile(
default_dgp=generate_did_data,
dgp_kwargs_builder=_basic_dgp_kwargs,
fit_kwargs_builder=_twfe_fit_kwargs,
result_extractor=_extract_simple,
min_n=20,
),
"MultiPeriodDiD": _EstimatorProfile(
default_dgp=generate_did_data,
dgp_kwargs_builder=_basic_dgp_kwargs,
fit_kwargs_builder=_multiperiod_fit_kwargs,
result_extractor=_extract_multiperiod,
min_n=20,
),
# --- Staggered group ---
"CallawaySantAnna": _EstimatorProfile(
default_dgp=generate_staggered_data,
dgp_kwargs_builder=_staggered_dgp_kwargs,
fit_kwargs_builder=_staggered_fit_kwargs,
result_extractor=_extract_staggered,
min_n=40,
),
"SunAbraham": _EstimatorProfile(
default_dgp=generate_staggered_data,
dgp_kwargs_builder=_staggered_dgp_kwargs,
fit_kwargs_builder=_staggered_fit_kwargs,
result_extractor=_extract_staggered,
min_n=40,
),
"ImputationDiD": _EstimatorProfile(
default_dgp=generate_staggered_data,
dgp_kwargs_builder=_staggered_dgp_kwargs,
fit_kwargs_builder=_staggered_fit_kwargs,
result_extractor=_extract_staggered,
min_n=40,
),
"TwoStageDiD": _EstimatorProfile(
default_dgp=generate_staggered_data,
dgp_kwargs_builder=_staggered_dgp_kwargs,
fit_kwargs_builder=_staggered_fit_kwargs,
result_extractor=_extract_staggered,
min_n=40,
),
"StackedDiD": _EstimatorProfile(
default_dgp=generate_staggered_data,
dgp_kwargs_builder=_staggered_dgp_kwargs,
fit_kwargs_builder=_staggered_fit_kwargs,
result_extractor=_extract_staggered,
min_n=40,
),
"EfficientDiD": _EstimatorProfile(
default_dgp=generate_staggered_data,
dgp_kwargs_builder=_staggered_dgp_kwargs,
fit_kwargs_builder=_staggered_fit_kwargs,
result_extractor=_extract_staggered,
min_n=40,
),
# --- Factor model group ---
"TROP": _EstimatorProfile(
default_dgp=generate_factor_data,
dgp_kwargs_builder=_factor_dgp_kwargs,
fit_kwargs_builder=_trop_fit_kwargs,
result_extractor=_extract_simple,
min_n=30,
),
"SyntheticDiD": _EstimatorProfile(
default_dgp=generate_factor_data,
dgp_kwargs_builder=_factor_dgp_kwargs,
fit_kwargs_builder=_sdid_fit_kwargs,
result_extractor=_extract_simple,
min_n=30,
),
# --- Triple difference ---
"TripleDifference": _EstimatorProfile(
default_dgp=generate_ddd_data,
dgp_kwargs_builder=_ddd_dgp_kwargs,
fit_kwargs_builder=_ddd_fit_kwargs,
result_extractor=_extract_simple,
min_n=64,
),
}
return _ESTIMATOR_REGISTRY
@dataclass
class PowerResults:
"""
Results from analytical power analysis.
Attributes
----------
power : float
Statistical power (probability of rejecting H0 when effect exists).
mde : float
Minimum detectable effect size.
required_n : int
Required total sample size (treated + control).
effect_size : float
Effect size used in calculation.
alpha : float
Significance level.
alternative : str
Alternative hypothesis ('two-sided', 'greater', 'less').
n_treated : int
Number of treated units.
n_control : int
Number of control units.
n_pre : int
Number of pre-treatment periods.
n_post : int
Number of post-treatment periods.
sigma : float
Residual standard deviation.
rho : float
Intra-cluster correlation (for panel data).
design : str
Study design type ('basic_did', 'panel', 'staggered').
"""
power: float
mde: float
required_n: int
effect_size: float
alpha: float
alternative: str
n_treated: int
n_control: int
n_pre: int
n_post: int
sigma: float
rho: float = 0.0
design: str = "basic_did"
def __repr__(self) -> str:
"""Concise string representation."""
return (
f"PowerResults(power={self.power:.3f}, mde={self.mde:.4f}, "
f"required_n={self.required_n})"
)
def summary(self) -> str:
"""
Generate a formatted summary of power analysis results.
Returns
-------
str
Formatted summary table.
"""
lines = [
"=" * 60,
"Power Analysis for Difference-in-Differences".center(60),
"=" * 60,
"",
f"{'Design:':<30} {self.design}",
f"{'Significance level (alpha):':<30} {self.alpha:.3f}",
f"{'Alternative hypothesis:':<30} {self.alternative}",
"",
"-" * 60,
"Sample Size".center(60),
"-" * 60,
f"{'Treated units:':<30} {self.n_treated:>10}",
f"{'Control units:':<30} {self.n_control:>10}",
f"{'Total units:':<30} {self.n_treated + self.n_control:>10}",
f"{'Pre-treatment periods:':<30} {self.n_pre:>10}",
f"{'Post-treatment periods:':<30} {self.n_post:>10}",
"",
"-" * 60,
"Variance Parameters".center(60),
"-" * 60,
f"{'Residual SD (sigma):':<30} {self.sigma:>10.4f}",
f"{'Intra-cluster correlation:':<30} {self.rho:>10.4f}",
"",
"-" * 60,
"Power Analysis Results".center(60),
"-" * 60,
f"{'Effect size:':<30} {self.effect_size:>10.4f}",
f"{'Power:':<30} {self.power:>10.1%}",
f"{'Minimum detectable effect:':<30} {self.mde:>10.4f}",
f"{'Required sample size:':<30} {self.required_n:>10}",
"=" * 60,
]
return "\n".join(lines)
def print_summary(self) -> None:
"""Print the summary to stdout."""
print(self.summary())
def to_dict(self) -> Dict[str, Any]:
"""
Convert results to a dictionary.
Returns
-------
Dict[str, Any]
Dictionary containing all power analysis results.
"""
return {
"power": self.power,
"mde": self.mde,
"required_n": self.required_n,
"effect_size": self.effect_size,
"alpha": self.alpha,
"alternative": self.alternative,
"n_treated": self.n_treated,
"n_control": self.n_control,
"n_pre": self.n_pre,
"n_post": self.n_post,
"sigma": self.sigma,
"rho": self.rho,
"design": self.design,
}
def to_dataframe(self) -> pd.DataFrame:
"""
Convert results to a pandas DataFrame.
Returns
-------
pd.DataFrame
DataFrame with power analysis results.
"""
return pd.DataFrame([self.to_dict()])
@dataclass
class SimulationPowerResults:
"""
Results from simulation-based power analysis.
Attributes
----------
power : float
Estimated power (proportion of simulations rejecting H0).
power_se : float
Standard error of power estimate.
power_ci : Tuple[float, float]
Confidence interval for power estimate.
rejection_rate : float
Proportion of simulations with p-value < alpha.
mean_estimate : float
Mean treatment effect estimate across simulations.
std_estimate : float
Standard deviation of estimates across simulations.
mean_se : float
Mean standard error across simulations.
coverage : float
Proportion of CIs containing true effect.
n_simulations : int
Number of simulations performed.
effect_sizes : List[float]
Effect sizes tested (if multiple).
powers : List[float]
Power at each effect size (if multiple).
true_effect : float
True treatment effect used in simulation.
alpha : float
Significance level.
estimator_name : str
Name of the estimator used.
effective_n_units : int or None
Effective sample size when it differs from the requested ``n_units``
(e.g., due to DDD grid rounding). ``None`` when no rounding occurred.
"""
power: float
power_se: float
power_ci: Tuple[float, float]
rejection_rate: float
mean_estimate: float
std_estimate: float
mean_se: float
coverage: float
n_simulations: int
effect_sizes: List[float]
powers: List[float]
true_effect: float
alpha: float
estimator_name: str
bias: float = field(init=False)
rmse: float = field(init=False)
simulation_results: Optional[List[Dict[str, Any]]] = field(default=None, repr=False)
effective_n_units: Optional[int] = None
def __post_init__(self):
"""Compute derived statistics."""
self.bias = self.mean_estimate - self.true_effect
self.rmse = np.sqrt(self.bias**2 + self.std_estimate**2)
def __repr__(self) -> str:
"""Concise string representation."""
return (
f"SimulationPowerResults(power={self.power:.3f} "
f"[{self.power_ci[0]:.3f}, {self.power_ci[1]:.3f}], "
f"n_simulations={self.n_simulations})"
)
def summary(self) -> str:
"""
Generate a formatted summary of simulation power results.
Returns
-------
str
Formatted summary table.
"""
lines = [
"=" * 65,
"Simulation-Based Power Analysis Results".center(65),
"=" * 65,
"",
f"{'Estimator:':<35} {self.estimator_name}",
f"{'Number of simulations:':<35} {self.n_simulations}",
f"{'True treatment effect:':<35} {self.true_effect:.4f}",
f"{'Significance level (alpha):':<35} {self.alpha:.3f}",
"",
"-" * 65,
"Power Estimates".center(65),
"-" * 65,
f"{'Power (rejection rate):':<35} {self.power:.1%}",
f"{'Standard error:':<35} {self.power_se:.4f}",
f"{'95% CI:':<35} [{self.power_ci[0]:.3f}, {self.power_ci[1]:.3f}]",
"",
"-" * 65,
"Estimation Performance".center(65),
"-" * 65,
f"{'Mean estimate:':<35} {self.mean_estimate:.4f}",
f"{'Bias:':<35} {self.bias:.4f}",
f"{'Std. deviation of estimates:':<35} {self.std_estimate:.4f}",
f"{'RMSE:':<35} {self.rmse:.4f}",
f"{'Mean standard error:':<35} {self.mean_se:.4f}",
f"{'Coverage (CI contains true):':<35} {self.coverage:.1%}",
]
if self.effective_n_units is not None:
lines.append(
f"{'Effective sample size:':<35} {self.effective_n_units}" f" (DDD grid-rounded)"
)
lines.append("=" * 65)
return "\n".join(lines)
def print_summary(self) -> None:
"""Print the summary to stdout."""
print(self.summary())
def to_dict(self) -> Dict[str, Any]:
"""
Convert results to a dictionary.
Returns
-------
Dict[str, Any]
Dictionary containing simulation power results.
"""
d: Dict[str, Any] = {
"power": self.power,
"power_se": self.power_se,
"power_ci_lower": self.power_ci[0],
"power_ci_upper": self.power_ci[1],
"rejection_rate": self.rejection_rate,
"mean_estimate": self.mean_estimate,
"std_estimate": self.std_estimate,
"bias": self.bias,
"rmse": self.rmse,
"mean_se": self.mean_se,
"coverage": self.coverage,
"n_simulations": self.n_simulations,
"true_effect": self.true_effect,
"alpha": self.alpha,
"estimator_name": self.estimator_name,
"effective_n_units": self.effective_n_units,
}
return d
def to_dataframe(self) -> pd.DataFrame:
"""
Convert results to a pandas DataFrame.
Returns
-------
pd.DataFrame
DataFrame with simulation power results.
"""
return pd.DataFrame([self.to_dict()])
def power_curve_df(self) -> pd.DataFrame:
"""
Get power curve data as a DataFrame.
Returns
-------
pd.DataFrame
DataFrame with effect_size and power columns.
"""
return pd.DataFrame({"effect_size": self.effect_sizes, "power": self.powers})
class PowerAnalysis:
"""
Power analysis for difference-in-differences designs.
Provides analytical power calculations for basic 2x2 DiD and panel DiD
designs. For complex designs like staggered adoption, use simulate_power()
instead.
Parameters
----------
alpha : float, default=0.05
Significance level for hypothesis testing.
power : float, default=0.80
Target statistical power.
alternative : str, default='two-sided'
Alternative hypothesis: 'two-sided', 'greater', or 'less'.
Examples
--------
Calculate minimum detectable effect:
>>> from diff_diff import PowerAnalysis
>>> pa = PowerAnalysis(alpha=0.05, power=0.80)
>>> results = pa.mde(n_treated=50, n_control=50, sigma=1.0)
>>> print(f"MDE: {results.mde:.3f}")
Calculate required sample size:
>>> results = pa.sample_size(effect_size=0.5, sigma=1.0)
>>> print(f"Required N: {results.required_n}")
Calculate power for given sample and effect:
>>> results = pa.power(effect_size=0.5, n_treated=50, n_control=50, sigma=1.0)
>>> print(f"Power: {results.power:.1%}")
Notes
-----
The power calculations are based on the variance of the DiD estimator:
For basic 2x2 DiD:
Var(ATT) = sigma^2 * (1/n_treated_post + 1/n_treated_pre
+ 1/n_control_post + 1/n_control_pre)
For panel DiD with T periods:
Var(ATT) = sigma^2 * (1/(N_treated * T) + 1/(N_control * T))
* (1 + (T-1)*rho) / (1 + (T-1)*rho)
Where rho is the intra-cluster correlation coefficient.
References
----------
Bloom, H. S. (1995). "Minimum Detectable Effects."
Burlig, F., Preonas, L., & Woerman, M. (2020). "Panel Data and Experimental Design."
"""
def __init__(
self,
alpha: float = 0.05,
power: float = 0.80,
alternative: str = "two-sided",
):
if not 0 < alpha < 1:
raise ValueError("alpha must be between 0 and 1")
if not 0 < power < 1:
raise ValueError("power must be between 0 and 1")
if alternative not in ("two-sided", "greater", "less"):
raise ValueError("alternative must be 'two-sided', 'greater', or 'less'")
self.alpha = alpha
self.target_power = power
self.alternative = alternative
def _get_critical_values(self) -> Tuple[float, float]:
"""Get z critical values for alpha and power."""
if self.alternative == "two-sided":
z_alpha = stats.norm.ppf(1 - self.alpha / 2)
else:
z_alpha = stats.norm.ppf(1 - self.alpha)
z_beta = stats.norm.ppf(self.target_power)
return z_alpha, z_beta
def _compute_variance(
self,
n_treated: int,
n_control: int,
n_pre: int,
n_post: int,
sigma: float,
rho: float = 0.0,
design: str = "basic_did",
) -> float:
"""
Compute variance of the DiD estimator.
Parameters
----------
n_treated : int
Number of treated units.
n_control : int
Number of control units.
n_pre : int
Number of pre-treatment periods.
n_post : int
Number of post-treatment periods.
sigma : float
Residual standard deviation.
rho : float
Intra-cluster correlation (for panel data).
design : str
Study design type.
Returns
-------
float
Variance of the DiD estimator.
"""
if design == "basic_did":
# For basic 2x2 DiD, each cell has n_treated/2 or n_control/2 obs
# assuming balanced design
n_t_pre = n_treated # treated units in pre-period
n_t_post = n_treated # treated units in post-period
n_c_pre = n_control
n_c_post = n_control
variance = sigma**2 * (1 / n_t_post + 1 / n_t_pre + 1 / n_c_post + 1 / n_c_pre)
elif design == "panel":
# Panel DiD with multiple periods
# Account for serial correlation via ICC
T = n_pre + n_post
# Design effect for clustering
design_effect = 1 + (T - 1) * rho
# Base variance (as if independent)
base_var = sigma**2 * (1 / n_treated + 1 / n_control)
# Adjust for clustering (Moulton factor)
variance = base_var * design_effect / T
else:
raise ValueError(f"Unknown design: {design}")
return variance
def power(
self,
effect_size: float,
n_treated: int,
n_control: int,
sigma: float,