diff --git a/TODO.md b/TODO.md index 340f99b9..f8dc9616 100644 --- a/TODO.md +++ b/TODO.md @@ -21,6 +21,10 @@ Related tracking surfaces: | Issue | Location | Origin | Effort | Priority | |-------|----------|--------|--------|----------| +| Sensitivity planning at the design stage: what HonestDiD `M` a planned design could rule out, from the placebo event studies `diagnose_design(event_study=True)` records (needs an effect-injected surface and HonestDiD run inside each placebo draw; the Rambachan-Roth review has no planning formula). Lifts the `HonestDiD` and `sensitivity_to_honest_did` refusals of `estimand="placebo"` surfaces. | `design.py::_placebo_event_study`, `honest_did.py::_extract_event_study_params` | pre-trend planning PR | Heavy | Medium | +| Placebo event studies for more `diagnose_design` candidates: `SunAbraham` (its container is not an admitted `PreTrendsPower` input; only the fitted results object is) and the `TwoWayFixedEffects` event-study mode (a different fit from the static one the diagnosis runs). Recorded today for `CallawaySantAnna` and `StackedDiD` only. | `design.py::_EVENT_STUDY_ESTIMATORS`, `pretrends.py::_extract_container_pre_period_params` | pre-trend planning PR | Mid | Low | +| Planned pre-trend power for the joint Wald form: `PreTrendsPower(pretest_form="wald")` refuses a design-stage input because the placebo record keeps each coefficient over its own standard error (the NIS test) and not each draw's event-study covariance. Supporting it needs the per-draw covariance blocks, a counted Wald rejection rate for the tested set, and a direct-injection check like the one in `benchmarks/python/pretrend_planning_check.py`. | `pretrends.py::_planned_pretest_check`, `design.py::_event_study_record` | pre-trend planning PR | Mid | Low | +| `PreTrendsPower` Wald form on a numerically singular pre-period covariance from a fitted model: `_compute_mdv_wald` and `_compute_power_wald` call `np.linalg.inv`, which does not raise on a numerically singular matrix (`pinv` is only the fallback after an exception), so the MDV can be meaningless. The design-stage path gates such a covariance out; the fitted path is unchanged. Decide between a rank guard and `pinv`. | `pretrends.py::_compute_mdv_wald` | pre-trend planning PR | Quick | Medium | | `diagnose_design` staggered placebo for `DifferenceInDifferences` / `TwoWayFixedEffects`: both are refused under a staggered declaration (two or more `cohort_periods`) because they are fitted with one `post` dummy. Supporting them needs a staggered TWFE placebo fit (a time-varying treatment column) and a stated estimand, since static TWFE under staggered timing does not target the injected effect cleanly. | `design.py::_validate_estimators` | design diagnosis PR-B | Mid | Low | | `diagnose_design` with `anticipation > 0`: refused today because the candidate's aggregate averages periods before adoption where no effect is injected. Inject the effect from `g - anticipation` so that bias and coverage are scored against the right target. | `design.py::_validate_estimators`, `design.py::_make_placebo_generator` | design diagnosis PR-B | Mid | Low | | `diagnose_design` size verdict near the threshold: the size check passes a no-effect rejection rate up to `alpha + 1.96 * sqrt(alpha * (1 - alpha) / R)`, so a candidate whose true size is just above `alpha` passes one run and fails the next. In `benchmarks/data/design_lock_rerun.json` (500 replicates, 40 units) candidates with reference size 6.4-6.7% passed the comparison and were then flagged by the lock rerun in 30-36% of locks. The lock already reports the rerun's verdict and warns when the two differ; decide whether the rule itself should change (a stricter bound, a reported interval for the size, or a three-way verdict). | `design.py::_size_controlled` | design lock PR | Mid | Medium | diff --git a/benchmarks/data/pretrend_planning_check.json b/benchmarks/data/pretrend_planning_check.json new file mode 100644 index 00000000..f5469ea1 --- /dev/null +++ b/benchmarks/data/pretrend_planning_check.json @@ -0,0 +1,19 @@ +{ + "meta": {"alpha": 0.05, "band_no_violation": 0.03, "band_power": 0.05, "band_selection": 0.03, "minutes": 4.1, "n_cells": 48, "n_cells_check_failed": 20, "n_cells_check_passed": 28, "n_diagnosis": 500, "n_direct": 1000, "n_flag_no_violation": 15, "n_flag_no_violation_check_failed": 15, "n_flag_no_violation_check_passed": 0, "n_flag_power": 2, "n_flag_power_check_failed": 2, "n_flag_power_check_passed": 0, "n_periods": 12, "seed": 20261126, "target_power": 0.8, "treated_share": 0.25, "workers": 8}, + "design_points": [ + {"design": "common", "index": 0, "n_units": 40, "rho": 0.0, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": false, "direct_no_violation": 0.147, "direct_no_violation_pvalue": 0.147, "direct_power_at_mdv": 0.809, "direct_power_at_mdv_pvalue": 0.809, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.15, "planned_mdv": 0.627828, "planned_no_violation": 0.097}, {"check_passed": false, "direct_no_violation": 0.261, "direct_no_violation_pvalue": 0.261, "direct_power_at_mdv": 0.846, "direct_power_at_mdv_pvalue": 0.846, "flag_no_violation": true, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.26, "planned_mdv": 0.239557, "planned_no_violation": 0.1772}, {"check_passed": false, "direct_no_violation": 0.387, "direct_no_violation_pvalue": 0.387, "direct_power_at_mdv": 0.859, "direct_power_at_mdv_pvalue": 0.859, "flag_no_violation": true, "flag_power": false, "k": 7, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.368, "planned_mdv": 0.13628, "planned_no_violation": 0.266}], "n_draws": 500, "n_excluded": 0, "n_pre": 7, "pretest_agrees": false, "pretest_counted": 0.368, "pretest_expected": 0.266, "recorded": true, "se_ratio_max": 0.9752, "se_ratio_min": 0.9297, "size": 0.062}, {"candidate": "StackedDiD", "cells": [{"check_passed": false, "direct_no_violation": 0.122, "direct_no_violation_pvalue": 0.112, "direct_power_at_mdv": 0.789, "direct_power_at_mdv_pvalue": 0.769, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.126, "planned_mdv": 0.627828, "planned_no_violation": 0.097}, {"check_passed": false, "direct_no_violation": 0.228, "direct_no_violation_pvalue": 0.205, "direct_power_at_mdv": 0.825, "direct_power_at_mdv_pvalue": 0.794, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.232, "planned_mdv": 0.239557, "planned_no_violation": 0.1772}], "n_draws": 500, "n_excluded": 0, "n_pre": 4, "pretest_agrees": false, "pretest_counted": 0.232, "pretest_expected": 0.1772, "recorded": true, "se_ratio_max": 1.0118, "se_ratio_min": 0.9646, "size": 0.044}], "seconds_event_study_off": 2.59, "seconds_event_study_on": 2.79}, + {"design": "staggered", "index": 1, "n_units": 40, "rho": 0.0, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": false, "direct_no_violation": 0.1542, "direct_no_violation_pvalue": 0.1542, "direct_power_at_mdv": 0.8068, "direct_power_at_mdv_pvalue": 0.8068, "flag_no_violation": true, "flag_power": false, "k": 2, "n_direct_mdv": 999, "n_direct_null": 999, "placebo_rejection_rate": 0.1383, "planned_mdv": 0.576065, "planned_no_violation": 0.0899}, {"check_passed": false, "direct_no_violation": 0.2523, "direct_no_violation_pvalue": 0.2523, "direct_power_at_mdv": 0.8398, "direct_power_at_mdv_pvalue": 0.8398, "flag_no_violation": true, "flag_power": false, "k": 4, "n_direct_mdv": 999, "n_direct_null": 999, "placebo_rejection_rate": 0.2405, "planned_mdv": 0.279732, "planned_no_violation": 0.1585}, {"check_passed": false, "direct_no_violation": 0.4755, "direct_no_violation_pvalue": 0.4755, "direct_power_at_mdv": 0.9019, "direct_power_at_mdv_pvalue": 0.9019, "flag_no_violation": true, "flag_power": true, "k": 8, "n_direct_mdv": 999, "n_direct_null": 999, "placebo_rejection_rate": 0.4589, "planned_mdv": 0.163205, "planned_no_violation": 0.2603}], "n_draws": 499, "n_excluded": 1, "n_pre": 8, "pretest_agrees": false, "pretest_counted": 0.4589, "pretest_expected": 0.2603, "recorded": true, "se_ratio_max": 1.0086, "se_ratio_min": 0.8239, "size": 0.076}], "seconds_event_study_off": 1.18, "seconds_event_study_on": 1.49}, + {"design": "common", "index": 2, "n_units": 200, "rho": 0.0, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": true, "direct_no_violation": 0.1, "direct_no_violation_pvalue": 0.1, "direct_power_at_mdv": 0.735, "direct_power_at_mdv_pvalue": 0.735, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.092, "planned_mdv": 0.301429, "planned_no_violation": 0.0899}, {"check_passed": true, "direct_no_violation": 0.172, "direct_no_violation_pvalue": 0.172, "direct_power_at_mdv": 0.784, "direct_power_at_mdv_pvalue": 0.784, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.15, "planned_mdv": 0.14227, "planned_no_violation": 0.1533}, {"check_passed": true, "direct_no_violation": 0.24, "direct_no_violation_pvalue": 0.24, "direct_power_at_mdv": 0.789, "direct_power_at_mdv_pvalue": 0.789, "flag_no_violation": false, "flag_power": false, "k": 7, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.232, "planned_mdv": 0.078075, "planned_no_violation": 0.2229}], "n_draws": 500, "n_excluded": 0, "n_pre": 7, "pretest_agrees": true, "pretest_counted": 0.232, "pretest_expected": 0.223, "recorded": true, "se_ratio_max": 1.0792, "se_ratio_min": 0.9802, "size": 0.042}, {"candidate": "StackedDiD", "cells": [{"check_passed": true, "direct_no_violation": 0.1, "direct_no_violation_pvalue": 0.099, "direct_power_at_mdv": 0.73, "direct_power_at_mdv_pvalue": 0.727, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.084, "planned_mdv": 0.301429, "planned_no_violation": 0.0899}, {"check_passed": true, "direct_no_violation": 0.167, "direct_no_violation_pvalue": 0.165, "direct_power_at_mdv": 0.779, "direct_power_at_mdv_pvalue": 0.773, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.14, "planned_mdv": 0.14227, "planned_no_violation": 0.1533}], "n_draws": 500, "n_excluded": 0, "n_pre": 4, "pretest_agrees": true, "pretest_counted": 0.14, "pretest_expected": 0.1533, "recorded": true, "se_ratio_max": 1.087, "se_ratio_min": 0.9874, "size": 0.036}], "seconds_event_study_off": 2.98, "seconds_event_study_on": 3.24}, + {"design": "staggered", "index": 3, "n_units": 200, "rho": 0.0, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": true, "direct_no_violation": 0.093, "direct_no_violation_pvalue": 0.093, "direct_power_at_mdv": 0.744, "direct_power_at_mdv_pvalue": 0.744, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.076, "planned_mdv": 0.265666, "planned_no_violation": 0.0906}, {"check_passed": true, "direct_no_violation": 0.173, "direct_no_violation_pvalue": 0.173, "direct_power_at_mdv": 0.779, "direct_power_at_mdv_pvalue": 0.779, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.14, "planned_mdv": 0.122567, "planned_no_violation": 0.1588}, {"check_passed": true, "direct_no_violation": 0.29, "direct_no_violation_pvalue": 0.29, "direct_power_at_mdv": 0.833, "direct_power_at_mdv_pvalue": 0.833, "flag_no_violation": false, "flag_power": false, "k": 8, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.296, "planned_mdv": 0.065341, "planned_no_violation": 0.2724}], "n_draws": 500, "n_excluded": 0, "n_pre": 8, "pretest_agrees": true, "pretest_counted": 0.296, "pretest_expected": 0.2724, "recorded": true, "se_ratio_max": 1.0514, "se_ratio_min": 0.932, "size": 0.058}], "seconds_event_study_off": 1.26, "seconds_event_study_on": 1.57}, + {"design": "common", "index": 4, "n_units": 40, "rho": 0.5, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": true, "direct_no_violation": 0.126, "direct_no_violation_pvalue": 0.126, "direct_power_at_mdv": 0.821, "direct_power_at_mdv_pvalue": 0.821, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.112, "planned_mdv": 0.557724, "planned_no_violation": 0.0879}, {"check_passed": false, "direct_no_violation": 0.211, "direct_no_violation_pvalue": 0.211, "direct_power_at_mdv": 0.807, "direct_power_at_mdv_pvalue": 0.807, "flag_no_violation": true, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.186, "planned_mdv": 0.330626, "planned_no_violation": 0.1526}, {"check_passed": false, "direct_no_violation": 0.296, "direct_no_violation_pvalue": 0.296, "direct_power_at_mdv": 0.824, "direct_power_at_mdv_pvalue": 0.824, "flag_no_violation": true, "flag_power": false, "k": 7, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.286, "planned_mdv": 0.223199, "planned_no_violation": 0.2099}], "n_draws": 500, "n_excluded": 0, "n_pre": 7, "pretest_agrees": false, "pretest_counted": 0.286, "pretest_expected": 0.2099, "recorded": true, "se_ratio_max": 1.0029, "se_ratio_min": 0.937, "size": 0.084}, {"candidate": "StackedDiD", "cells": [{"check_passed": true, "direct_no_violation": 0.109, "direct_no_violation_pvalue": 0.101, "direct_power_at_mdv": 0.796, "direct_power_at_mdv_pvalue": 0.778, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.098, "planned_mdv": 0.557724, "planned_no_violation": 0.0879}, {"check_passed": true, "direct_no_violation": 0.184, "direct_no_violation_pvalue": 0.169, "direct_power_at_mdv": 0.783, "direct_power_at_mdv_pvalue": 0.765, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.164, "planned_mdv": 0.330628, "planned_no_violation": 0.1526}], "n_draws": 500, "n_excluded": 0, "n_pre": 4, "pretest_agrees": true, "pretest_counted": 0.164, "pretest_expected": 0.1526, "recorded": true, "se_ratio_max": 1.0406, "se_ratio_min": 1.0055, "size": 0.062}], "seconds_event_study_off": 2.56, "seconds_event_study_on": 2.91}, + {"design": "staggered", "index": 5, "n_units": 40, "rho": 0.5, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": false, "direct_no_violation": 0.1612, "direct_no_violation_pvalue": 0.1612, "direct_power_at_mdv": 0.8448, "direct_power_at_mdv_pvalue": 0.8448, "flag_no_violation": true, "flag_power": false, "k": 2, "n_direct_mdv": 999, "n_direct_null": 999, "placebo_rejection_rate": 0.1643, "planned_mdv": 0.642729, "planned_no_violation": 0.0892}, {"check_passed": false, "direct_no_violation": 0.2382, "direct_no_violation_pvalue": 0.2382, "direct_power_at_mdv": 0.8278, "direct_power_at_mdv_pvalue": 0.8278, "flag_no_violation": true, "flag_power": false, "k": 4, "n_direct_mdv": 999, "n_direct_null": 999, "placebo_rejection_rate": 0.2405, "planned_mdv": 0.370676, "planned_no_violation": 0.1423}, {"check_passed": false, "direct_no_violation": 0.4264, "direct_no_violation_pvalue": 0.4264, "direct_power_at_mdv": 0.8669, "direct_power_at_mdv_pvalue": 0.8669, "flag_no_violation": true, "flag_power": false, "k": 8, "n_direct_mdv": 999, "n_direct_null": 999, "placebo_rejection_rate": 0.4269, "planned_mdv": 0.236, "planned_no_violation": 0.222}], "n_draws": 499, "n_excluded": 1, "n_pre": 8, "pretest_agrees": false, "pretest_counted": 0.4269, "pretest_expected": 0.222, "recorded": true, "se_ratio_max": 0.9289, "se_ratio_min": 0.8269, "size": 0.09}], "seconds_event_study_off": 1.17, "seconds_event_study_on": 1.66}, + {"design": "common", "index": 6, "n_units": 200, "rho": 0.5, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": true, "direct_no_violation": 0.092, "direct_no_violation_pvalue": 0.092, "direct_power_at_mdv": 0.811, "direct_power_at_mdv_pvalue": 0.811, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.096, "planned_mdv": 0.324384, "planned_no_violation": 0.0869}, {"check_passed": true, "direct_no_violation": 0.161, "direct_no_violation_pvalue": 0.161, "direct_power_at_mdv": 0.838, "direct_power_at_mdv_pvalue": 0.838, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.162, "planned_mdv": 0.171478, "planned_no_violation": 0.1441}, {"check_passed": true, "direct_no_violation": 0.218, "direct_no_violation_pvalue": 0.218, "direct_power_at_mdv": 0.829, "direct_power_at_mdv_pvalue": 0.829, "flag_no_violation": false, "flag_power": false, "k": 7, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.216, "planned_mdv": 0.103546, "planned_no_violation": 0.2003}], "n_draws": 500, "n_excluded": 0, "n_pre": 7, "pretest_agrees": true, "pretest_counted": 0.216, "pretest_expected": 0.2003, "recorded": true, "se_ratio_max": 1.0, "se_ratio_min": 0.9563, "size": 0.052}, {"candidate": "StackedDiD", "cells": [{"check_passed": true, "direct_no_violation": 0.09, "direct_no_violation_pvalue": 0.088, "direct_power_at_mdv": 0.809, "direct_power_at_mdv_pvalue": 0.807, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.092, "planned_mdv": 0.324384, "planned_no_violation": 0.0869}, {"check_passed": true, "direct_no_violation": 0.157, "direct_no_violation_pvalue": 0.155, "direct_power_at_mdv": 0.834, "direct_power_at_mdv_pvalue": 0.832, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.156, "planned_mdv": 0.171478, "planned_no_violation": 0.1441}], "n_draws": 500, "n_excluded": 0, "n_pre": 4, "pretest_agrees": true, "pretest_counted": 0.156, "pretest_expected": 0.1441, "recorded": true, "se_ratio_max": 0.9874, "se_ratio_min": 0.9633, "size": 0.044}], "seconds_event_study_off": 2.99, "seconds_event_study_on": 3.31}, + {"design": "staggered", "index": 7, "n_units": 200, "rho": 0.5, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": true, "direct_no_violation": 0.09, "direct_no_violation_pvalue": 0.09, "direct_power_at_mdv": 0.784, "direct_power_at_mdv_pvalue": 0.784, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.09, "planned_mdv": 0.260303, "planned_no_violation": 0.0866}, {"check_passed": true, "direct_no_violation": 0.151, "direct_no_violation_pvalue": 0.151, "direct_power_at_mdv": 0.816, "direct_power_at_mdv_pvalue": 0.816, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.152, "planned_mdv": 0.151488, "planned_no_violation": 0.1468}, {"check_passed": true, "direct_no_violation": 0.27, "direct_no_violation_pvalue": 0.27, "direct_power_at_mdv": 0.811, "direct_power_at_mdv_pvalue": 0.811, "flag_no_violation": false, "flag_power": false, "k": 8, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.256, "planned_mdv": 0.084306, "planned_no_violation": 0.2441}], "n_draws": 500, "n_excluded": 0, "n_pre": 8, "pretest_agrees": true, "pretest_counted": 0.256, "pretest_expected": 0.2441, "recorded": true, "se_ratio_max": 1.0382, "se_ratio_min": 0.9583, "size": 0.048}], "seconds_event_study_off": 1.28, "seconds_event_study_on": 1.66}, + {"design": "common", "index": 8, "n_units": 40, "rho": 0.8, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": true, "direct_no_violation": 0.129, "direct_no_violation_pvalue": 0.129, "direct_power_at_mdv": 0.77, "direct_power_at_mdv_pvalue": 0.77, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.112, "planned_mdv": 0.557686, "planned_no_violation": 0.0892}, {"check_passed": false, "direct_no_violation": 0.204, "direct_no_violation_pvalue": 0.204, "direct_power_at_mdv": 0.775, "direct_power_at_mdv_pvalue": 0.775, "flag_no_violation": true, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.184, "planned_mdv": 0.41577, "planned_no_violation": 0.1391}, {"check_passed": false, "direct_no_violation": 0.27, "direct_no_violation_pvalue": 0.27, "direct_power_at_mdv": 0.853, "direct_power_at_mdv_pvalue": 0.853, "flag_no_violation": true, "flag_power": false, "k": 7, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.228, "planned_mdv": 0.269436, "planned_no_violation": 0.1855}], "n_draws": 500, "n_excluded": 0, "n_pre": 7, "pretest_agrees": false, "pretest_counted": 0.228, "pretest_expected": 0.1855, "recorded": true, "se_ratio_max": 0.9924, "se_ratio_min": 0.9172, "size": 0.082}, {"candidate": "StackedDiD", "cells": [{"check_passed": true, "direct_no_violation": 0.115, "direct_no_violation_pvalue": 0.107, "direct_power_at_mdv": 0.744, "direct_power_at_mdv_pvalue": 0.727, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.092, "planned_mdv": 0.557686, "planned_no_violation": 0.0892}, {"check_passed": true, "direct_no_violation": 0.191, "direct_no_violation_pvalue": 0.177, "direct_power_at_mdv": 0.752, "direct_power_at_mdv_pvalue": 0.731, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.158, "planned_mdv": 0.415774, "planned_no_violation": 0.1391}], "n_draws": 500, "n_excluded": 0, "n_pre": 4, "pretest_agrees": true, "pretest_counted": 0.158, "pretest_expected": 0.1391, "recorded": true, "se_ratio_max": 1.0297, "se_ratio_min": 0.9953, "size": 0.072}], "seconds_event_study_off": 2.52, "seconds_event_study_on": 2.99}, + {"design": "staggered", "index": 9, "n_units": 40, "rho": 0.8, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": false, "direct_no_violation": 0.1576, "direct_no_violation_pvalue": 0.1576, "direct_power_at_mdv": 0.7922, "direct_power_at_mdv_pvalue": 0.7922, "flag_no_violation": true, "flag_power": false, "k": 2, "n_direct_mdv": 996, "n_direct_null": 996, "placebo_rejection_rate": 0.163, "planned_mdv": 0.638618, "planned_no_violation": 0.0889}, {"check_passed": false, "direct_no_violation": 0.2329, "direct_no_violation_pvalue": 0.2329, "direct_power_at_mdv": 0.8213, "direct_power_at_mdv_pvalue": 0.8213, "flag_no_violation": true, "flag_power": false, "k": 4, "n_direct_mdv": 996, "n_direct_null": 996, "placebo_rejection_rate": 0.2555, "planned_mdv": 0.418564, "planned_no_violation": 0.1373}, {"check_passed": false, "direct_no_violation": 0.4056, "direct_no_violation_pvalue": 0.4056, "direct_power_at_mdv": 0.8775, "direct_power_at_mdv_pvalue": 0.8775, "flag_no_violation": true, "flag_power": true, "k": 8, "n_direct_mdv": 996, "n_direct_null": 996, "placebo_rejection_rate": 0.4346, "planned_mdv": 0.314572, "planned_no_violation": 0.2186}], "n_draws": 497, "n_excluded": 3, "n_pre": 8, "pretest_agrees": false, "pretest_counted": 0.4346, "pretest_expected": 0.2186, "recorded": true, "se_ratio_max": 0.951, "se_ratio_min": 0.7863, "size": 0.088}], "seconds_event_study_off": 1.18, "seconds_event_study_on": 1.55}, + {"design": "common", "index": 10, "n_units": 200, "rho": 0.8, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": true, "direct_no_violation": 0.084, "direct_no_violation_pvalue": 0.084, "direct_power_at_mdv": 0.771, "direct_power_at_mdv_pvalue": 0.771, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.084, "planned_mdv": 0.31916, "planned_no_violation": 0.0846}, {"check_passed": true, "direct_no_violation": 0.143, "direct_no_violation_pvalue": 0.143, "direct_power_at_mdv": 0.772, "direct_power_at_mdv_pvalue": 0.772, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.13, "planned_mdv": 0.178055, "planned_no_violation": 0.1328}, {"check_passed": true, "direct_no_violation": 0.187, "direct_no_violation_pvalue": 0.187, "direct_power_at_mdv": 0.787, "direct_power_at_mdv_pvalue": 0.787, "flag_no_violation": false, "flag_power": false, "k": 7, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.198, "planned_mdv": 0.12477, "planned_no_violation": 0.1846}], "n_draws": 500, "n_excluded": 0, "n_pre": 7, "pretest_agrees": true, "pretest_counted": 0.198, "pretest_expected": 0.1846, "recorded": true, "se_ratio_max": 1.051, "se_ratio_min": 0.9983, "size": 0.046}, {"candidate": "StackedDiD", "cells": [{"check_passed": true, "direct_no_violation": 0.081, "direct_no_violation_pvalue": 0.081, "direct_power_at_mdv": 0.766, "direct_power_at_mdv_pvalue": 0.763, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.084, "planned_mdv": 0.31916, "planned_no_violation": 0.0846}, {"check_passed": true, "direct_no_violation": 0.137, "direct_no_violation_pvalue": 0.135, "direct_power_at_mdv": 0.768, "direct_power_at_mdv_pvalue": 0.765, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.126, "planned_mdv": 0.178055, "planned_no_violation": 0.1328}], "n_draws": 500, "n_excluded": 0, "n_pre": 4, "pretest_agrees": true, "pretest_counted": 0.126, "pretest_expected": 0.1328, "recorded": true, "se_ratio_max": 1.0587, "se_ratio_min": 1.0056, "size": 0.044}], "seconds_event_study_off": 2.99, "seconds_event_study_on": 3.46}, + {"design": "staggered", "index": 11, "n_units": 200, "rho": 0.8, "runs": [{"candidate": "CallawaySantAnna", "cells": [{"check_passed": false, "direct_no_violation": 0.107, "direct_no_violation_pvalue": 0.107, "direct_power_at_mdv": 0.807, "direct_power_at_mdv_pvalue": 0.807, "flag_no_violation": false, "flag_power": false, "k": 2, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.114, "planned_mdv": 0.294862, "planned_no_violation": 0.0843}, {"check_passed": false, "direct_no_violation": 0.157, "direct_no_violation_pvalue": 0.157, "direct_power_at_mdv": 0.813, "direct_power_at_mdv_pvalue": 0.813, "flag_no_violation": false, "flag_power": false, "k": 4, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.166, "planned_mdv": 0.186022, "planned_no_violation": 0.131}, {"check_passed": true, "direct_no_violation": 0.244, "direct_no_violation_pvalue": 0.244, "direct_power_at_mdv": 0.808, "direct_power_at_mdv_pvalue": 0.808, "flag_no_violation": false, "flag_power": false, "k": 8, "n_direct_mdv": 1000, "n_direct_null": 1000, "placebo_rejection_rate": 0.234, "planned_mdv": 0.119555, "planned_no_violation": 0.2119}], "n_draws": 500, "n_excluded": 0, "n_pre": 8, "pretest_agrees": true, "pretest_counted": 0.234, "pretest_expected": 0.2119, "recorded": true, "se_ratio_max": 1.0043, "se_ratio_min": 0.9539, "size": 0.064}], "seconds_event_study_off": 1.27, "seconds_event_study_on": 1.76} + ], + "stability": [{"mdv_mean": 0.225429, "mdv_sd": 0.009314, "n_seeds": 20, "n_simulations": 200, "n_units": 40, "n_unreported": 0, "relative_spread": 0.0413}, {"mdv_mean": 0.227645, "mdv_sd": 0.007198, "n_seeds": 20, "n_simulations": 500, "n_units": 40, "n_unreported": 0, "relative_spread": 0.0316}, {"mdv_mean": 0.228731, "mdv_sd": 0.00557, "n_seeds": 20, "n_simulations": 1000, "n_units": 40, "n_unreported": 0, "relative_spread": 0.0244}, {"mdv_mean": 0.10226, "mdv_sd": 0.00475, "n_seeds": 20, "n_simulations": 200, "n_units": 200, "n_unreported": 0, "relative_spread": 0.0465}, {"mdv_mean": 0.102938, "mdv_sd": 0.003998, "n_seeds": 20, "n_simulations": 500, "n_units": 200, "n_unreported": 0, "relative_spread": 0.0388}, {"mdv_mean": 0.103363, "mdv_sd": 0.002261, "n_seeds": 20, "n_simulations": 1000, "n_units": 200, "n_unreported": 0, "relative_spread": 0.0219}], + "selection": [{"flag": false, "injected_effect": 0.780822, "measurable": true, "n_units": 40, "picked": {"never_treated": 37, "not_yet_treated": 13}, "relative_difference_mean": -0.0167, "relative_difference_sd": 0.0457, "relative_difference_se": 0.0065, "repetitions": 50}, {"flag": false, "injected_effect": 0.34795, "measurable": true, "n_units": 200, "picked": {"never_treated": 35, "not_yet_treated": 15}, "relative_difference_mean": 0.0136, "relative_difference_sd": 0.042, "relative_difference_se": 0.0059, "repetitions": 50}] +} diff --git a/benchmarks/python/pretrend_planning_check.py b/benchmarks/python/pretrend_planning_check.py new file mode 100644 index 00000000..5bb845cd --- /dev/null +++ b/benchmarks/python/pretrend_planning_check.py @@ -0,0 +1,576 @@ +#!/usr/bin/env python3 +"""Does pre-trend power planned from placebo event studies match what happens? + +``diagnose_design(..., event_study=True)`` records, for each candidate, the +covariance of its event-study coefficients across placebo draws. +``PreTrendsPower`` turns that covariance into planned pre-trend power with +Roth's (2022) formula. Roth calibrates the formula to the covariance of an +estimated event study; using the covariance across placebo draws of a design +that has not been run is this library's extension. This script checks it: + +1. Planned numbers. For each design point and candidate, the planned minimum + detectable violation (``mdv``, target power 0.80, the default NIS pre-test) + and the planned rejection probability with no violation, for several + numbers ``K`` of tested pre-periods. +2. Direct check. On fresh placebo draws, add a linear trend + ``gamma * (t - g + 1)`` to the placebo-treated units over all periods + (``g`` the unit's adoption period, so the trend is zero in the reference + period ``g - 1``), fit, apply the NIS test to the ``K`` pre-period + coefficients nearest to treatment with that fit's own reported standard + errors, and count rejections: once with ``gamma = 0`` and once per ``K`` + with ``gamma`` set to that ``K``'s planned ``mdv``. If the plan is right + the second rate is 0.80 and the first equals the planned no-violation + rate. +3. Monte Carlo stability. The planned ``mdv`` over 20 diagnosis seeds at 200, + 500 and 1,000 replicates. +4. Selection effect. A diagnosis compares two candidates and the one with the + higher power at an injected effect is picked; its planned ``mdv`` on the + comparison draws is compared with its planned ``mdv`` from a rerun alone + on a new seed. + +The formula assumes that each coefficient's own test rejects at its nominal +level when nothing is wrong. ``PreTrendsPower`` therefore reports planned +power for a set of pre-periods only when the pre-trend test over that set +rejected, in the placebo draws of the diagnosis, at the rate the formula +assumes (the "pre-test check"). So that the planned numbers of the cells the +check withholds can still be shown, this script computes them from the same +internal pieces without the check, and records the check's verdict per cell. +The question it answers is then: does the formula hold on the cells the check +lets through, and does the check catch the cells on which it does not? + +Everything below was fixed before the first run and is not searched. (The +pre-test check was added after a first run of steps 1-4, which showed the +formula failing on the 40-unit points; the check adds the verdict columns +and changes nothing else.) The NIS formula is integrated by a randomized +routine, so a rerun reproduces the planned numbers to about five decimals +and the direct rates to within a draw or two; the committed JSON is the +record. + +Panels: ``y_it = a_i + d_t + e_it``, ``a_i`` and ``d_t`` ``N(0, 1)``, ``e_it`` +an AR(1) with coefficient ``rho`` and innovation sd 1 started from its +stationary distribution. 12 periods; ``rho`` in {0, 0.5, 0.8}; 40 and 200 +units; treated share 0.25; units resampled in every draw (the default). +Common adoption at period 9, and a staggered design with adoption at 8 and +10. 12 design points, one fixed panel each. + +Candidates: ``CallawaySantAnna(base_period="universal")`` on all 12 points; +``StackedDiD(kappa_pre=5, kappa_post=3)`` on the 6 common-adoption points +only (in a staggered design its default comparison group uses later cohorts +as controls, and those would receive the injected trend too, so the injected +alternative would not be the one the formula evaluates). ``K`` = 2, 4 and all +testable pre-periods for ``CallawaySantAnna``; 2 and 4 for ``StackedDiD``. + +Steps 1-2 use 500 diagnosis replicates and 1,000 direct draws. Step 3 runs on +the two common-adoption ``rho = 0.5`` points, ``CallawaySantAnna`` only. +Step 4 runs on the two staggered ``rho = 0.5`` points with +``CallawaySantAnna(base_period="universal")`` under +``control_group="never_treated"`` and ``"not_yet_treated"`` (two candidates +whose estimates differ, so either can be picked), 50 repetitions of 500 +replicates, the injected effect set to twice the no-effect spread of the +first candidate in a 200-replicate pilot. + +Flag rules (set in advance; they flag, they hide nothing). A ``(run, K)`` +cell is flagged when the direct rejection rate at the planned ``mdv`` differs +from 0.80 by more than 5 percentage points plus two Monte Carlo standard +errors of that rate, or when the direct no-violation rate differs from the +planned one by more than 3 points plus two such standard errors. The +selection step is flagged when the picked candidate's planned ``mdv`` on the +comparison draws is on average more than 3% below its rerun value. + +The output JSON underwrites the "Placebo event study" notes in +``docs/methodology/REGISTRY.md`` section ``DesignDiagnosis``. + +Usage: + python benchmarks/python/pretrend_planning_check.py \\ + --output benchmarks/data/pretrend_planning_check.json +""" + +import argparse +import json +import os +import sys +import time +import warnings +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +os.environ.setdefault("OMP_NUM_THREADS", "1") +os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") +os.environ.setdefault("VECLIB_MAXIMUM_THREADS", "1") + +import numpy as np # noqa: E402 +import pandas as pd # noqa: E402 +from scipy import stats # noqa: E402 + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from diff_diff import CallawaySantAnna, PreTrendsPower, StackedDiD, diagnose_design # noqa: E402 +from diff_diff import design as _design # noqa: E402 + +SEED = 20261126 +N_PERIODS = 12 +TREATED_SHARE = 0.25 +ALPHA = 0.05 +TARGET = 0.80 +N_DIAGNOSIS = 500 +N_DIRECT = 1000 +RHOS = (0.0, 0.5, 0.8) +UNITS = (40, 200) +DESIGNS = {"common": [9], "staggered": [8, 10]} +STABILITY_SEEDS = 20 +STABILITY_SIZES = (200, 500, 1000) +SELECTION_REPS = 50 +BAND_POWER = 0.05 +BAND_NULL = 0.03 +BAND_SELECTION = 0.03 + + +def make_panel(n_units, rho, rng): + """A fixed untreated panel with unit and period effects and AR(1) errors.""" + unit_effect = rng.normal(size=n_units) + period_effect = rng.normal(size=N_PERIODS) + errors = np.empty((n_units, N_PERIODS)) + errors[:, 0] = rng.normal(scale=1.0 / np.sqrt(1.0 - rho**2), size=n_units) + for t in range(1, N_PERIODS): + errors[:, t] = rho * errors[:, t - 1] + rng.normal(size=n_units) + y = unit_effect[:, None] + period_effect[None, :] + errors + return pd.DataFrame( + { + "id": np.repeat(np.arange(n_units), N_PERIODS), + "t": np.tile(np.arange(1, N_PERIODS + 1), n_units), + "y": y.ravel(), + } + ) + + +def candidates(design): + out = {"CallawaySantAnna": CallawaySantAnna(base_period="universal")} + if design == "common": + out["StackedDiD"] = StackedDiD(kappa_pre=5, kappa_post=3) + return out + + +def pre_labels(surface): + keep = (~surface.is_reference) & (surface.event_time < 0) + return sorted(surface.event_time[keep].tolist()) + + +def k_values(label, n_pre): + if label == "StackedDiD": + return [2, 4] + return [2, 4, n_pre] + + +def diagnose(panel, estimators, cohorts, n_simulations, seed, event_study=True, effect_sizes=None): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return diagnose_design( + panel, + outcome="y", + unit="id", + time="t", + estimators=estimators, + cohort_periods=cohorts, + treatment_fraction=TREATED_SHARE, + n_simulations=n_simulations, + alpha=ALPHA, + seed=seed, + progress=False, + event_study=event_study, + effect_sizes=effect_sizes, + ) + + +def planned(surface, tested): + """Planned MDV and no-violation rate for ``tested``, with the check's verdict. + + The numbers are computed whether or not the check passes (``fit`` would + refuse the cells on which it fails). + """ + planner = PreTrendsPower(alpha=ALPHA, power=TARGET) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + _, _, vcov, n_pre, relative_times, _ = planner._extract_pre_period_params(surface, tested) + weights = planner._get_violation_weights(n_pre, relative_times=relative_times) + counted, expected, _, agrees = planner._planned_pretest_check(surface, tested, weights, vcov) + return float(planner._compute_mdv(weights, vcov)), float(expected), float(counted), bool(agrees) + + +def score_event_study(surface, required, tested_sets, critical): + """Rejection indicators of the NIS test on one fitted event study, or ``None``. + + The draw is scored only if every label in ``required`` (all the planned + pre-periods) has a finite coefficient-to-standard-error ratio, so that + every tested set of a run is scored on the same draws and a draw of + another layout (a cohort that received no treated unit) is never counted + for some sets and dropped for others. Returns, per tested set, whether + any ratio exceeds ``critical`` and whether any reported p-value is below + ``ALPHA``. + """ + position = {label: i for i, label in enumerate(surface.event_time.tolist())} + if any(label not in position for label in required): + return None + rows = [position[label] for label in required] + if not np.all(np.isfinite(surface.att[rows] / surface.se[rows])): + return None + indicators = [] + for tested in tested_sets: + rows = [position[label] for label in tested] + ratio = np.abs(surface.att[rows] / surface.se[rows]) + indicators.append( + (bool(np.any(ratio > critical)), bool(np.any(surface.p_value[rows] < ALPHA))) + ) + return indicators + + +def direct_rejections(panel, estimator, cohorts, gammas, tested_sets, seeds, required): + """Rejection counts of the NIS test on fresh draws, per injected trend. + + ``gammas[j]`` is injected and scored on ``tested_sets[j]`` (a list of + lists of event times: the no-trend entry is scored on every set). + ``required`` is the full list of planned pre-periods (see + ``score_event_study``). Returns the counts by the normal critical value, + the counts by the fits' reported p-values, and the number of draws + scored, per injected trend. + """ + n_units = panel["id"].nunique() + n_treated = int(n_units * TREATED_SHARE) + generator = _design._make_placebo_generator(panel, "y", "id", "t", n_treated, cohorts, True) + fit_kwargs = _design._fit_kwargs(estimator, "y", "id", "t", {}) + z = stats.norm.ppf(1.0 - ALPHA / 2.0) + counts = [np.zeros(len(sets), dtype=int) for sets in tested_sets] + counts_p = [np.zeros(len(sets), dtype=int) for sets in tested_sets] + scored = np.zeros(len(gammas), dtype=int) + for seed in seeds: + frame = generator(treatment_effect=0.0, seed=int(seed)) + base = frame["y"].to_numpy(dtype=float) + first = frame[_design._FIRST_TREAT_COLUMN].to_numpy(dtype=float) + trend = np.where(first > 0, frame["t"].to_numpy(dtype=float) - first + 1.0, 0.0) + for j, gamma in enumerate(gammas): + frame["y"] = base + gamma * trend + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fitted = type(estimator)(**estimator.get_params()).fit(frame, **fit_kwargs) + surface = fitted.aggregate("event_study") + except (ValueError, np.linalg.LinAlgError, KeyError, RuntimeError, ZeroDivisionError): + continue + indicators = score_event_study(surface, required, tested_sets[j], z) + if indicators is None: + continue + scored[j] += 1 + for s, (by_critical, by_p_value) in enumerate(indicators): + counts[j][s] += int(by_critical) + counts_p[j][s] += int(by_p_value) + return counts, counts_p, scored + + +def run_point(task): + """Steps 1 and 2 for one design point.""" + index, rho, n_units, design, panel_seed, diag_seed, direct_seeds = task + cohorts = DESIGNS[design] + panel = make_panel(n_units, rho, np.random.default_rng(panel_seed)) + estimators = candidates(design) + started = time.perf_counter() + diagnose(panel, estimators, cohorts, N_DIAGNOSIS, diag_seed, event_study=False) + seconds_off = time.perf_counter() - started + started = time.perf_counter() + diagnosis = diagnose(panel, estimators, cohorts, N_DIAGNOSIS, diag_seed) + seconds_on = time.perf_counter() - started + runs = [] + for label, estimator in estimators.items(): + surface = diagnosis.event_study_results.get(label) + if surface is None: + runs.append({"candidate": label, "recorded": False}) + continue + labels = pre_labels(surface) + checks = diagnosis._event_study_checks[label] + ks = k_values(label, len(labels)) + tested = [labels[-k:] for k in ks] + plans = [planned(surface, t) for t in tested] + gammas = [0.0] + [plan[0] for plan in plans] + tested_sets = [tested] + [[t] for t in tested] + counts, counts_p, scored = direct_rejections( + panel, estimator, cohorts, gammas, tested_sets, direct_seeds, labels + ) + cells = [] + for j, k in enumerate(ks): + mdv, planned_null, counted_null, check_passed = plans[j] + n_null = int(scored[0]) + n_alt = int(scored[j + 1]) + direct_null = counts[0][j] / n_null if n_null else float("nan") + direct_alt = counts[j + 1][0] / n_alt if n_alt else float("nan") + se_null = np.sqrt(direct_null * (1 - direct_null) / n_null) if n_null else float("nan") + se_alt = np.sqrt(direct_alt * (1 - direct_alt) / n_alt) if n_alt else float("nan") + flag_power = bool(abs(direct_alt - TARGET) > BAND_POWER + 2 * se_alt) + flag_null = bool(abs(direct_null - planned_null) > BAND_NULL + 2 * se_null) + cells.append( + { + "k": int(k), + "check_passed": check_passed, + "placebo_rejection_rate": round(counted_null, 4), + "planned_mdv": round(mdv, 6), + "planned_no_violation": round(planned_null, 4), + "direct_no_violation": round(float(direct_null), 4), + "direct_no_violation_pvalue": round(counts_p[0][j] / n_null, 4), + "direct_power_at_mdv": round(float(direct_alt), 4), + "direct_power_at_mdv_pvalue": round(counts_p[j + 1][0] / n_alt, 4), + "n_direct_null": n_null, + "n_direct_mdv": n_alt, + "flag_power": flag_power, + "flag_no_violation": flag_null, + } + ) + ratios = list(checks["se_ratio"].values()) + runs.append( + { + "candidate": label, + "recorded": True, + "n_draws": checks["n_draws"], + "n_excluded": checks["n_excluded"], + "n_pre": len(labels), + "se_ratio_min": round(min(ratios), 4), + "se_ratio_max": round(max(ratios), 4), + "size": round(float(diagnosis.results[label][0].rejection_rate), 4), + "pretest_counted": round(checks["pretest_rejection_rate"], 4), + "pretest_expected": round(checks["pretest_expected_rate"], 4), + "pretest_agrees": bool(checks["pretest_agrees"]), + "cells": cells, + } + ) + return { + "index": index, + "rho": rho, + "n_units": n_units, + "design": design, + "seconds_event_study_off": round(seconds_off, 2), + "seconds_event_study_on": round(seconds_on, 2), + "runs": runs, + } + + +def run_stability(task): + """Step 3: the planned mdv over diagnosis seeds, one (point, size) per task.""" + n_units, n_simulations, panel_seed, seeds = task + panel = make_panel(n_units, 0.5, np.random.default_rng(panel_seed)) + estimators = {"CallawaySantAnna": CallawaySantAnna(base_period="universal")} + values = [] + for seed in seeds: + diagnosis = diagnose(panel, estimators, DESIGNS["common"], n_simulations, int(seed)) + surface = diagnosis.event_study_results.get("CallawaySantAnna") + if surface is None: + values.append(float("nan")) + continue + values.append(planned(surface, pre_labels(surface))[0]) + values = np.asarray(values) + return { + "n_units": n_units, + "n_simulations": n_simulations, + "n_seeds": len(seeds), + "mdv_mean": round(float(np.nanmean(values)), 6), + "mdv_sd": round(float(np.nanstd(values, ddof=1)), 6), + "relative_spread": round(float(np.nanstd(values, ddof=1) / np.nanmean(values)), 4), + "n_unreported": int(np.sum(~np.isfinite(values))), + } + + +def selection_candidates(): + return { + "never_treated": CallawaySantAnna(base_period="universal", control_group="never_treated"), + "not_yet_treated": CallawaySantAnna( + base_period="universal", control_group="not_yet_treated" + ), + } + + +def run_selection(task): + """Step 4: one repetition of pick-then-rerun on one staggered point.""" + n_units, panel_seed, effect, compare_seed, rerun_seed = task + cohorts = DESIGNS["staggered"] + panel = make_panel(n_units, 0.5, np.random.default_rng(panel_seed)) + estimators = selection_candidates() + comparison = diagnose( + panel, estimators, cohorts, N_DIAGNOSIS, int(compare_seed), effect_sizes=[effect] + ) + powers = {label: float(comparison.results[label][1].power) for label in estimators} + picked = max(estimators, key=lambda label: powers[label]) + surface = comparison.event_study_results.get(picked) + rerun = diagnose(panel, {picked: estimators[picked]}, cohorts, N_DIAGNOSIS, int(rerun_seed)) + rerun_surface = rerun.event_study_results.get(picked) + if surface is None or rerun_surface is None: + return {"n_units": n_units, "picked": picked, "relative_difference": float("nan")} + mdv_comparison = planned(surface, pre_labels(surface))[0] + mdv_rerun = planned(rerun_surface, pre_labels(rerun_surface))[0] + return { + "n_units": n_units, + "picked": picked, + "relative_difference": (mdv_comparison - mdv_rerun) / mdv_rerun, + } + + +def selection_effect_size(n_units, panel_seed, pilot_seed): + panel = make_panel(n_units, 0.5, np.random.default_rng(panel_seed)) + pilot = diagnose( + panel, + {"never_treated": selection_candidates()["never_treated"]}, + DESIGNS["staggered"], + 200, + int(pilot_seed), + event_study=False, + ) + return 2.0 * float(pilot.results["never_treated"][0].std_estimate) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--output", required=True) + parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 2)) + parser.add_argument( + "--timing-only", + action="store_true", + help="time 20 replicates on the largest design point and exit", + ) + args = parser.parse_args() + + root = np.random.SeedSequence(SEED) + panel_children, diag_children, direct_children, stability_child, selection_child = root.spawn(5) + grid = [(rho, n, design) for rho in RHOS for n in UNITS for design in DESIGNS] + panel_seeds = panel_children.spawn(len(grid)) + diag_seeds = diag_children.generate_state(len(grid)) + direct_seed_seqs = direct_children.spawn(len(grid)) + + if args.timing_only: + panel = make_panel(200, 0.5, np.random.default_rng(panel_seeds[0])) + started = time.perf_counter() + diagnose(panel, candidates("common"), DESIGNS["common"], 20, 1) + per_fit = (time.perf_counter() - started) / 40 + print( + f"about {per_fit * 1e3:.1f} ms per fit at 200 units; 393,000 fits = " + f"{393000 * per_fit / 60:.0f} core-minutes" + ) + return + + started = time.perf_counter() + point_tasks = [ + ( + i, + rho, + n, + design, + panel_seeds[i], + int(diag_seeds[i]), + direct_seed_seqs[i].generate_state(N_DIRECT).tolist(), + ) + for i, (rho, n, design) in enumerate(grid) + ] + point_index = {(rho, n, design): i for i, (rho, n, design) in enumerate(grid)} + + stability_tasks = [] + stability_seeds = stability_child.spawn(len(UNITS) * len(STABILITY_SIZES)) + position = 0 + for n in UNITS: + for size in STABILITY_SIZES: + stability_tasks.append( + ( + n, + size, + panel_seeds[point_index[(0.5, n, "common")]], + stability_seeds[position].generate_state(STABILITY_SEEDS).tolist(), + ) + ) + position += 1 + + selection_tasks = [] + selection_effects = {} + selection_seeds = selection_child.spawn(len(UNITS)) + for u, n in enumerate(UNITS): + panel_seed = panel_seeds[point_index[(0.5, n, "staggered")]] + state = selection_seeds[u].generate_state(1 + 2 * SELECTION_REPS).tolist() + effect = selection_effect_size(n, panel_seed, state[0]) + selection_effects[n] = effect + for r in range(SELECTION_REPS): + selection_tasks.append((n, panel_seed, effect, state[1 + 2 * r], state[2 + 2 * r])) + + with ProcessPoolExecutor(max_workers=args.workers) as pool: + points = list(pool.map(run_point, point_tasks)) + stability = list(pool.map(run_stability, stability_tasks)) + selection_raw = list(pool.map(run_selection, selection_tasks, chunksize=2)) + + selection = [] + for n in UNITS: + rows = [row for row in selection_raw if row["n_units"] == n] + diffs = np.asarray([row["relative_difference"] for row in rows], dtype=float) + picks = {} + for row in rows: + picks[row["picked"]] = picks.get(row["picked"], 0) + 1 + mean = float(np.nanmean(diffs)) + selection.append( + { + "n_units": n, + "injected_effect": round(selection_effects[n], 6), + "repetitions": len(rows), + "picked": picks, + "measurable": bool(max(picks.values()) / len(rows) <= 0.9), + "relative_difference_mean": round(mean, 4), + "relative_difference_sd": round(float(np.nanstd(diffs, ddof=1)), 4), + "relative_difference_se": round( + float(np.nanstd(diffs, ddof=1) / np.sqrt(np.sum(np.isfinite(diffs)))), 4 + ), + "flag": bool(mean < -BAND_SELECTION), + } + ) + + n_cells = sum(len(run.get("cells", [])) for point in points for run in point["runs"]) + all_cells = [cell for point in points for run in point["runs"] for cell in run.get("cells", [])] + passed_cells = [cell for cell in all_cells if cell["check_passed"]] + failed_cells = [cell for cell in all_cells if not cell["check_passed"]] + + def _count(cells, key): + return int(sum(cell[key] for cell in cells)) + + n_flag_power = _count(all_cells, "flag_power") + n_flag_null = _count(all_cells, "flag_no_violation") + payload = { + "meta": { + "seed": SEED, + "n_periods": N_PERIODS, + "treated_share": TREATED_SHARE, + "alpha": ALPHA, + "target_power": TARGET, + "n_diagnosis": N_DIAGNOSIS, + "n_direct": N_DIRECT, + "band_power": BAND_POWER, + "band_no_violation": BAND_NULL, + "band_selection": BAND_SELECTION, + "n_cells": n_cells, + "n_cells_check_passed": len(passed_cells), + "n_cells_check_failed": len(failed_cells), + "n_flag_power_check_passed": _count(passed_cells, "flag_power"), + "n_flag_no_violation_check_passed": _count(passed_cells, "flag_no_violation"), + "n_flag_power_check_failed": _count(failed_cells, "flag_power"), + "n_flag_no_violation_check_failed": _count(failed_cells, "flag_no_violation"), + "n_flag_power": int(n_flag_power), + "n_flag_no_violation": int(n_flag_null), + "minutes": round((time.perf_counter() - started) / 60.0, 1), + "workers": args.workers, + }, + "design_points": points, + "stability": stability, + "selection": selection, + } + lines = ["{", f' "meta": {json.dumps(payload["meta"], sort_keys=True)},', ' "design_points": ['] + rows = [json.dumps(record, sort_keys=True) for record in payload["design_points"]] + lines.append(",\n".join(" " + row for row in rows)) + lines.append(" ],") + lines.append(f' "stability": {json.dumps(payload["stability"], sort_keys=True)},') + lines.append(f' "selection": {json.dumps(payload["selection"], sort_keys=True)}') + lines.append("}") + Path(args.output).write_text("\n".join(lines) + "\n") + print( + f"wrote {args.output}: {n_cells} cells, {n_flag_power} power flags, " + f"{n_flag_null} no-violation flags, {payload['meta']['minutes']} minutes" + ) + + +if __name__ == "__main__": + main() diff --git a/changelog.d/20261126-pretrend-planning.md b/changelog.d/20261126-pretrend-planning.md new file mode 100644 index 00000000..77cc79c7 --- /dev/null +++ b/changelog.d/20261126-pretrend-planning.md @@ -0,0 +1,42 @@ +### Added +- **Planned pre-trend power at the design stage.** + `diagnose_design(..., event_study=True)` keeps, for each `CallawaySantAnna` + and `StackedDiD` estimator, a placebo event study: the mean and the + covariance, across the no-effect placebo draws, of the event-study + coefficients of each fit (`DesignDiagnosisResults.event_study_results`, an + `EventStudyResults` labelled `estimand="placebo"`). `PreTrendsPower.fit`, + `power_at`, `power_curve`, `compute_pretrends_power` and `compute_mdv` accept + the diagnosis (or one of its surfaces) and return planned pre-trend power from + Roth's (2022) formula before any outcome exists + (`covariance_source="placebo_draws"`). The new + `PreTrendsPower.power_by_pre_periods(diagnosis)` tabulates the minimum + detectable violation and the test's no-violation rejection rate by the number + of pre-periods tested. + - The formula assumes that each coefficient's own test rejects at its nominal + level. For the pre-periods being planned, `PreTrendsPower` counts how often + the pre-trend test rejected in the placebo draws (none of which contains a + violation) and compares that with the rate the formula assumes. Planned + power is reported only where the two agree within Monte Carlo error: `fit` + raises with both rates otherwise, and the by-pre-period table shows both + rates on every row (`power_no_violation`, `placebo_rejection_rate`) and + leaves the planned numbers blank on rows that disagree. In the library's + simulation the formula matched direct trend injection on all 28 cells that + passed this check (power at the planned minimum detectable violation 73% + to 84% against a target of 80%), and every cell on which it did not match + was one the check withholds (mostly 40-unit panels with 10 treated units). + - Planned power is available for the default pre-test form + (`pretest_form="nis"`) only. + - No placebo event study is recorded for a `vcov_type="jackknife"` candidate + or for the other estimator classes. + - `HonestDiD`, `PreTrendsPower.sensitivity_to_honest_did`, and + `precomputed["pretrends_power"]` in `DiagnosticReport` / `BusinessReport` + refuse a placebo event study or a result planned from one. + +### Fixed +- `PreTrendsPower.fit`, `power_at`, `power_curve` and + `PreTrendsPowerResults.power_at` reported a power of 100% (default pre-test + form) or of `alpha` (Wald form) for a violation magnitude `M` that was NaN. + A non-finite `M` now raises `ValueError`. +- The `PreTrendsPower` example in the bundled `llms-full.txt` guide called a + method and an argument that do not exist (`ptp.compute`, `M_grid=` on + `compute_pretrends_power`). diff --git a/diff_diff/_reporting_helpers.py b/diff_diff/_reporting_helpers.py index 66f829b5..ed760678 100644 --- a/diff_diff/_reporting_helpers.py +++ b/diff_diff/_reporting_helpers.py @@ -42,6 +42,27 @@ def results_design(results: Any) -> Optional[str]: return getattr(results, "design", None) +def check_precomputed_pretrends_power(precomputed: Dict[str, Any], owner: str) -> None: + """ + Refuse a planned pre-trends power result in ``precomputed=``. + + A ``PreTrendsPowerResults`` computed from a placebo event study + (``covariance_source == "placebo_draws"``) describes a design that had + not been run. A report describes one fitted model, so the two cannot be + combined. + """ + supplied = precomputed.get("pretrends_power") + if supplied is None: + return + if getattr(supplied, "covariance_source", None) == "placebo_draws": + raise ValueError( + f"{owner}: precomputed['pretrends_power'] was computed from a " + f"placebo event study of diagnose_design (a planned design, not " + f"the fit being reported). Pass pre-trends power computed from the " + f"fitted results, or omit the key." + ) + + def check_design_reconciliation(reconciliation: Any, results: Any, owner: str) -> None: """ Refuse a ``design_reconciliation=`` input the report cannot stand behind. diff --git a/diff_diff/business_report.py b/diff_diff/business_report.py index c813a2a6..aea83b7b 100644 --- a/diff_diff/business_report.py +++ b/diff_diff/business_report.py @@ -51,6 +51,7 @@ from diff_diff._reporting_helpers import ( check_design_reconciliation, + check_precomputed_pretrends_power, describe_design_reconciliation, describe_target_parameter, design_reconciliation_lines, @@ -429,6 +430,7 @@ def __init__( "aggregate('event_study') surface) and do not accept " "precomputed overrides." ) + check_precomputed_pretrends_power(self._dr_precomputed, "BusinessReport") resolved_alpha = alpha if alpha is not None else getattr(results, "alpha", 0.05) self._context = BusinessContext( diff --git a/diff_diff/design.py b/diff_diff/design.py index a8ae82b0..6cf42920 100644 --- a/diff_diff/design.py +++ b/diff_diff/design.py @@ -54,6 +54,7 @@ import numpy as np import pandas as pd +from scipy import stats from diff_diff.power import ( SimulationMDEResults, @@ -61,7 +62,8 @@ simulate_mde, simulate_power, ) -from diff_diff.results_base import Diagnostic +from diff_diff.results_base import Diagnostic, EventStudyResults +from diff_diff.utils import safe_inference __all__ = [ "diagnose_design", @@ -122,6 +124,21 @@ _MIN_PRE_PERIODS = 2 _MAX_ERROR_MESSAGES = 5 +# Candidates whose placebo event study is recorded under event_study=True: the +# classes whose aggregate("event_study") container PreTrendsPower admits. +_EVENT_STUDY_ESTIMATORS = ("CallawaySantAnna", "StackedDiD") +# Attribute of a placebo event study that holds, per placebo draw, each +# pre-period coefficient over its own reported standard error (absolute +# value). PreTrendsPower counts the pre-trend test's rejections from it for +# whichever pre-periods it is asked to plan (see placebo_pretest_rate). +_PRETEST_RECORD = "_placebo_pretest" +# The placebo covariance is not reported when its smallest eigenvalue is at or +# below this multiple of its largest (the near-singularity threshold +# results_base._validate_vcov_subblock applies when allow_singular=False). +_RANK_TOLERANCE = 1e-10 +# The estimand label of a placebo event-study surface (EventStudyResults.estimand). +PLACEBO_ESTIMAND = "placebo" + # Printed by both summaries: what a placebo diagnosis does and does not test. _SCOPE_LINES = ( "Placebo treatment is assigned at random, so these runs test inference", @@ -190,6 +207,21 @@ class DesignDiagnosisResults(Diagnostic): Columns the fingerprint covers. time_periods : list Period values of the panel actually used. + event_study : bool + Whether placebo event studies were requested. + event_study_results : dict + Label -> :class:`~diff_diff.EventStudyResults`, the placebo event + study of each ``CallawaySantAnna`` or ``StackedDiD`` estimator for + which one could be recorded; empty when ``event_study`` is False. + Its ``att`` column is the mean of the no-effect replicates' + event-study coefficients, ``vcov`` their sample covariance across the + replicates, and ``se`` the square root of its diagonal: the spread of + one fit's coefficient, which is what a single fit's standard error + should equal. ``t_stat``, ``p_value`` and the interval compare that + mean with that spread; they are not inference on an effect, and the + error bars of a plot of the surface show the spread. The surface + carries ``estimand="placebo"``. Pass this object (or one entry) to + :class:`~diff_diff.PreTrendsPower` for planned pre-trend power. """ results: Dict[str, List[SimulationPowerResults]] @@ -218,12 +250,31 @@ class DesignDiagnosisResults(Diagnostic): data_sha256: str data_columns: List[str] time_periods: List[Any] + event_study: bool = False + # Excluded from ==: the surfaces hold arrays, on which dataclass equality + # raises. + event_study_results: Dict[str, EventStudyResults] = field(default_factory=dict, compare=False) # The configuration as diagnosed (lock() refuses one that was changed # afterwards) and the labels lock() has rerun. _classes: Dict[str, type] = field(default_factory=dict, repr=False, compare=False) _params: Dict[str, Dict[str, Any]] = field(default_factory=dict, repr=False, compare=False) _fit_keywords: Optional[Dict[str, Any]] = field(default=None, repr=False, compare=False) _rerun_labels: List[str] = field(default_factory=list, repr=False, compare=False) + # Per label, how its placebo event study was reduced: draws used, draws + # excluded, the reported-SE ratio per pre-period, and how often a + # pre-trend test over all pre-periods rejected in the no-effect draws + # against the rate the power formula assumes. + _event_study_checks: Dict[str, Dict[str, Any]] = field( + default_factory=dict, repr=False, compare=False + ) + + def __setstate__(self, state: Dict[str, Any]) -> None: + """Restore a pickled object, filling fields added after it was pickled.""" + self.__dict__.update(state) + # Fields with a default_factory have no class-level fallback. + self.__dict__.setdefault("event_study", False) + self.__dict__.setdefault("event_study_results", {}) + self.__dict__.setdefault("_event_study_checks", {}) def __repr__(self) -> str: """Concise string representation.""" @@ -288,6 +339,7 @@ def to_dict(self) -> Dict[str, Any]: "resample_units": self.resample_units, "estimator_kwargs": dict(self.estimator_kwargs), "seed": self.seed, + "event_study": self.event_study, "n_units": self.n_units, "n_periods": self.n_periods, "n_obs": self.n_obs, @@ -359,6 +411,8 @@ def summary(self) -> str: f"{_fmt_rate(cell.power):>8}{_fmt_num(cell.bias):>11}" f"{_fmt_num(cell.rmse):>11}{_fmt_rate(cell.coverage):>10}" ) + if self.event_study: + lines.extend(_event_study_lines(self, width)) lines.extend( [ "", @@ -536,8 +590,11 @@ class _PlaceboFit: anything else propagates. """ - def __init__(self, estimator: Any) -> None: + def __init__(self, estimator: Any, capture: Optional[List[Any]] = None) -> None: self._estimator = estimator + # None, or the list that receives one event-study record per scored + # replicate (see _event_study_record). + self._capture = capture self.n_fits = 0 self.n_nan = 0 self.n_raised = 0 @@ -560,6 +617,8 @@ def fit(self, data: pd.DataFrame, **kwargs: Any) -> Any: if not _has_scalar_inference(result) or not _has_finite_inference(result): self.n_nan += 1 raise ValueError("non-finite inference") + if self._capture is not None: + self._capture.append(_event_study_record(result)) return result @@ -568,6 +627,307 @@ def _clone(estimator: Any) -> Any: return type(estimator)(**estimator.get_params()) +# --------------------------------------------------------------------------- +# Placebo event study +# --------------------------------------------------------------------------- + + +def _event_study_skip_reason(estimator: Any) -> Optional[str]: + """Why no placebo event study is recorded for this estimator, else None.""" + name = type(estimator).__name__ + if name not in _EVENT_STUDY_ESTIMATORS: + return ( + f"{name} event studies are not an input PreTrendsPower accepts from " + f"diagnose_design (recorded for: {', '.join(_EVENT_STUDY_ESTIMATORS)})" + ) + if estimator.get_params().get("vcov_type") == "jackknife": + return ( + "the pre-trend check of a cluster-jackknife fit compares each " + "coefficient with a t(H-1) reference under a Bonferroni correction, " + "which is not the test PreTrendsPower models (reports skip pre-trends " + "power for such fits too)" + ) + return None + + +def _plain(value: Any) -> Any: + """A numpy scalar as the Python scalar it wraps; anything else unchanged.""" + return value.item() if isinstance(value, np.generic) else value + + +def _event_study_record(result: Any) -> Optional[Tuple[Any, np.ndarray, np.ndarray]]: + """One replicate's event study: its layout and its coefficient and SE vectors. + + The layout is the rows that are a reference row or carry a finite estimate + and a finite positive standard error, together with the provenance the + consumers read. Two replicates are averaged only if their layouts are + equal, so a surface's provenance is that of every draw behind it. ``None`` + when the aggregation fails on this draw. + """ + try: + surface = result.aggregate("event_study") + except _DATA_DEPENDENT_ERRORS: + return None + event_time = [_plain(v) for v in surface.event_time.tolist()] + is_reference = np.asarray(surface.is_reference, dtype=bool) + att = np.asarray(surface.att, dtype=float) + se = np.asarray(surface.se, dtype=float) + estimated = ~is_reference & np.isfinite(att) & np.isfinite(se) & (se > 0) + keep = is_reference | estimated + rows = tuple((event_time[i], bool(is_reference[i])) for i in range(len(event_time)) if keep[i]) + reference_event_times = surface.reference_event_times + provenance = ( + surface.source, + surface.base_period, + ( + None + if reference_event_times is None + else tuple(_plain(v) for v in reference_event_times) + ), + surface.event_time_convention, + ) + return (rows, provenance), att[estimated], se[estimated] + + +def _placebo_event_study( + estimator: Any, + records: Sequence[Optional[Tuple[Any, np.ndarray, np.ndarray]]], + alpha: float, +) -> Tuple[Optional[EventStudyResults], Optional[Dict[str, Any]], Optional[str]]: + """Reduce one estimator's no-effect event studies to one planned surface. + + Returns ``(surface, checks, None)`` when a surface is reported and + ``(None, None, reason)`` when it is not. + + The coefficients are the means over the draws and the covariance is the + sample covariance of the coefficient vectors across the draws. The other + inference columns follow from those two; they describe how one draw varies + around the mean of the draws, not an estimated effect. + """ + n_captured = len(records) + usable = [record for record in records if record is not None] + if not usable: + return None, None, "no no-effect replicate produced an event study" + counts: Dict[Any, int] = {} + for layout, _att, _se in usable: + counts[layout] = counts.get(layout, 0) + 1 + # Most frequent layout; ties to the one with more rows, then to a fixed + # order, so the choice never depends on iteration order. + layout = min(counts, key=lambda key: (-counts[key], -len(key[0]), repr(key))) + rows, provenance = layout + used = [record for record in usable if record[0] == layout] + n_used = len(used) + n_excluded = n_captured - n_used + if n_excluded / n_captured > _MAX_LOST_SHARE: + return ( + None, + None, + f"{n_excluded} of {n_captured} no-effect replicates had a different " + f"event-study layout or no event study (more than {_MAX_LOST_SHARE:.0%})", + ) + labels = [label for label, is_ref in rows if not is_ref] + k = len(labels) + pre = [position for position, label in enumerate(labels) if label < 0] + if not pre: + name = type(estimator).__name__ + hint = ( + " (StackedDiD estimates no pre-period at kappa_pre=1; set kappa_pre >= 2)" + if name == "StackedDiD" + else "" + ) + return None, None, f"the event study has no estimated pre-treatment period{hint}" + if n_used < 2 * k + 1: + return ( + None, + None, + f"{n_used} replicates are too few for the covariance of {k} " + f"coefficients (the library requires at least {2 * k + 1}); raise n_simulations", + ) + draws = np.vstack([record[1] for record in used]) + vcov = np.atleast_2d(np.cov(draws, rowvar=False, ddof=1)) + singular = "the placebo covariance of the event-study coefficients is " + if not np.all(np.isfinite(vcov)): + return None, None, singular + "not finite" + eigenvalues = np.linalg.eigvalsh((vcov + vcov.T) / 2.0) + if eigenvalues[-1] <= 0.0 or eigenvalues[0] <= _RANK_TOLERANCE * eigenvalues[-1]: + return ( + None, + None, + singular + "rank-deficient (the replicates contain too few distinct " + "placebo assignments; this happens on a small panel with " + "resample_units=False)", + ) + means = draws.mean(axis=0) + spread = np.sqrt(np.diag(vcov)) + n_rows = len(rows) + att = np.zeros(n_rows) + columns = { + name: np.full(n_rows, np.nan) + for name in ("se", "t_stat", "p_value", "conf_int_lower", "conf_int_upper") + } + position = 0 + for i, (_label, is_ref) in enumerate(rows): + if is_ref: + continue + t_stat, p_value, conf_int = safe_inference( + float(means[position]), float(spread[position]), alpha=alpha + ) + att[i] = means[position] + columns["se"][i] = spread[position] + columns["t_stat"][i] = t_stat + columns["p_value"][i] = p_value + columns["conf_int_lower"][i] = conf_int[0] + columns["conf_int_upper"][i] = conf_int[1] + position += 1 + source, base_period, reference_event_times, convention = provenance + surface = EventStudyResults( + event_time=np.asarray([label for label, _ in rows]), + att=att, + se=columns["se"], + t_stat=columns["t_stat"], + p_value=columns["p_value"], + conf_int_lower=columns["conf_int_lower"], + conf_int_upper=columns["conf_int_upper"], + is_reference=np.asarray([is_ref for _, is_ref in rows], dtype=bool), + n=np.full(n_rows, np.nan), + n_kind=None, + time_scale="relative", + event_time_convention=convention, + vcov=vcov, + vcov_index=np.asarray(labels), + alpha=alpha, + source=source, + base_period=base_period, + anticipation=0, + reference_event_times=reference_event_times, + estimand=PLACEBO_ESTIMAND, + ) + reported = np.vstack([record[2] for record in used]) + mean_reported = reported.mean(axis=0) + pre_labels = [labels[i] for i in pre] + # Kept on the surface so that the check below can be repeated for any + # subset of the pre-periods (PreTrendsPower does, for the set it plans). + setattr( + surface, + _PRETEST_RECORD, + {"labels": pre_labels, "abs_t": np.abs(draws[:, pre] / reported[:, pre])}, + ) + counted, _ = placebo_pretest_rate(surface, pre_labels, alpha) + expected = _formula_pretest_rate(vcov[np.ix_(pre, pre)], alpha) + checks = { + "n_draws": n_used, + "n_excluded": n_excluded, + "n_pre": len(pre), + "n_post": k - len(pre), + "se_ratio": {labels[i]: float(mean_reported[i] / spread[i]) for i in pre}, + "pretest_rejection_rate": counted, + "pretest_expected_rate": expected, + "pretest_agrees": _pretest_size_ok(counted, expected, n_used), + } + return surface, checks, None + + +def placebo_pretest_rate(surface: Any, tested: Sequence[Any], alpha: float) -> Tuple[float, int]: + """How often the pre-trend test rejected in the placebo draws, for ``tested``. + + The test is the one PreTrendsPower models by default: reject when any of + the tested pre-period coefficients is individually significant at + ``alpha`` (normal critical value), with each draw's own reported standard + errors, as a fitted model would run it. No violation is present in any + draw, so this is the test's false-alarm rate on this panel. + + Returns the rate and the number of draws. Raises ``ValueError`` when the + surface does not carry its per-draw record (it was rebuilt or copied + field by field) or ``tested`` names a period that is not in it. + """ + record = getattr(surface, _PRETEST_RECORD, None) + if record is None: + raise ValueError( + "This placebo event study carries no per-draw record, so the " + "pre-trend test's rejection rate in the placebo draws cannot be " + "counted. Pass the object diagnose_design(..., event_study=True) " + "returned (its event_study_results entry), not a rebuilt copy." + ) + position = {label: i for i, label in enumerate(record["labels"])} + missing = [label for label in tested if label not in position] + if missing: + raise ValueError( + f"Pre-periods {missing} are not in this placebo event study's " + f"per-draw record (recorded: {record['labels']})." + ) + columns = [position[label] for label in tested] + critical = float(stats.norm.ppf(1.0 - alpha / 2.0)) + abs_t = record["abs_t"] + rejected = np.any(abs_t[:, columns] > critical, axis=1) + return float(rejected.mean()), int(abs_t.shape[0]) + + +def _formula_pretest_rate(vcov: np.ndarray, alpha: float) -> float: + """Rejection rate of the any-coefficient pre-test with no violation. + + The rate Roth's (2022) formula implies: the coefficients are normal with + covariance ``vcov`` and each is compared with the normal critical value + times its own standard deviation. This is PreTrendsPower's NIS power at a + violation of zero. + """ + from diff_diff.pretrends import _compute_nis_acceptance_prob + + critical = float(stats.norm.ppf(1.0 - alpha / 2.0)) + accept = _compute_nis_acceptance_prob(0.0, np.zeros(vcov.shape[0]), vcov, critical) + return float(1.0 - accept) + + +def _pretest_size_ok(counted: float, expected: float, n_draws: int) -> bool: + """Whether the counted no-violation rejection rate agrees with the expected one. + + True when the two differ by at most 1.96 Monte Carlo standard errors of a + rate estimated from ``n_draws`` replicates at the expected rate (the form + of ``_size_controlled``, applied in both directions: a pre-test that + rejects less often than the formula assumes makes the planned power too + high, one that rejects more often makes it meaningless). + """ + if n_draws <= 0 or not np.isfinite(counted) or not np.isfinite(expected): + return False + tolerance = 1.96 * math.sqrt(expected * (1.0 - expected) / n_draws) + return bool(abs(counted - expected) <= tolerance) + + +def _event_study_lines(diagnosis: "DesignDiagnosisResults", width: int) -> List[str]: + """The placebo event-study block of ``DesignDiagnosisResults.summary()``.""" + lines = ["", "-" * width, "Placebo event studies (no-effect runs)".center(width), "-" * width] + if not diagnosis._event_study_checks: + lines.append("None recorded.") + return lines + lines.append(f"{'':<22}{'':>6}{'':>6}{'':>5}{'':>14}{'All pre-periods test':>25}") + lines.append( + f"{'Estimator':<22}{'Draws':>6}{'Excl.':>6}{'Pre':>5}{'SE ratio':>14}" + f"{'counted':>9}{'assumed':>9}{'Agree':>7}" + ) + for label, checks in diagnosis._event_study_checks.items(): + ratios = list(checks["se_ratio"].values()) + lines.append( + f"{label[:21]:<22}{checks['n_draws']:>6}{checks['n_excluded']:>6}" + f"{checks['n_pre']:>5}{f'{min(ratios):.2f} to {max(ratios):.2f}':>14}" + f"{_fmt_rate(checks['pretest_rejection_rate']):>9}" + f"{_fmt_rate(checks['pretest_expected_rate']):>9}" + f"{('yes' if checks['pretest_agrees'] else 'NO'):>7}" + ) + lines.extend( + [ + "", + "'All pre-periods test': how often a pre-trend test over every pre-period", + "(any coefficient individually significant) rejected in the no-effect", + "draws, and how often the power formula assumes it does. PreTrendsPower", + "repeats this comparison for the pre-periods it is asked to plan and", + "reports planned power only where the two agree;", + "PreTrendsPower().power_by_pre_periods(...) shows it by number tested.", + "'SE ratio': mean reported standard error of a pre-period coefficient", + "over its spread across the draws.", + ] + ) + return lines + + # --------------------------------------------------------------------------- # Size gate # --------------------------------------------------------------------------- @@ -1203,10 +1563,11 @@ def _run_cell( n_simulations: int, alpha: float, seed: int, + capture: Optional[List[Any]] = None, ) -> Tuple[Any, _PlaceboFit]: """One estimator at one effect size, through ``simulate_power``.""" name = type(estimator).__name__ - adapter = _PlaceboFit(_clone(estimator)) + adapter = _PlaceboFit(_clone(estimator), capture) try: cell = simulate_power( adapter, @@ -1319,18 +1680,26 @@ def _run_estimator( seed: int, progress: bool, stacklevel: int = 4, -) -> Tuple[List[Any], List[int], bool, Optional[Any], float]: + event_study: bool = False, +) -> Tuple[List[Any], List[int], bool, Optional[Any], float, Optional[List[Any]]]: """Every effect size, the size check and the MDE search for one estimator. Returns the cells, the non-finite-inference counts, whether the size - check passed, the MDE search result (``None`` when it did not run) and - the reported MDE (NaN when not reported). Warnings are re-emitted with - the label. + check passed, the MDE search result (``None`` when it did not run), the + reported MDE (NaN when not reported), and the event-study records of the + no-effect cell (``None`` unless ``event_study`` is set and the estimator + records a placebo event study). Warnings are re-emitted with the label. + + Only the no-effect cell captures event studies: the other effect cells and + the MDE search build their adapters without a capture list. """ cells: List[Any] = [] nan_counts: List[int] = [] null_adapter: Optional[_PlaceboFit] = None - for effect in effects: + captured: Optional[List[Any]] = None + if event_study and _event_study_skip_reason(estimator) is None: + captured = [] + for position, effect in enumerate(effects): with _WarningCapture() as capture: cell, adapter = _run_cell( estimator, @@ -1342,6 +1711,7 @@ def _run_estimator( n_simulations, alpha, seed, + capture=captured if position == 0 else None, ) _reemit(label, capture.records, stacklevel) cells.append(cell) @@ -1381,7 +1751,7 @@ def _run_estimator( _reemit(label, capture.records, stacklevel) if progress: print(f" {caller}: {label}, MDE search: {_fmt_num(value)}") - return cells, nan_counts, size_ok, found, value + return cells, nan_counts, size_ok, found, value, captured # --------------------------------------------------------------------------- @@ -1407,6 +1777,7 @@ def diagnose_design( estimator_kwargs: Optional[Dict[str, Any]] = None, seed: Optional[int] = None, progress: bool = True, + event_study: bool = False, ) -> DesignDiagnosisResults: """ Diagnose a planned DiD design on your own untreated panel. @@ -1474,12 +1845,29 @@ def diagnose_design( Seed of the placebo draws. ``None`` draws one and records it. progress : bool, default=True Print one line per estimator and effect. + event_study : bool, default=False + Also record a placebo event study for each ``CallawaySantAnna`` and + ``StackedDiD`` estimator (not for one with ``vcov_type="jackknife"``): + the mean and the covariance, across the no-effect replicates, of the + event-study coefficients of each fit. The result is stored in + ``event_study_results`` and is what + :class:`~diff_diff.PreTrendsPower` reads to plan pre-trend power + before any outcome exists. The record also keeps, per replicate, + each pre-period coefficient over its own reported standard error, so + that the pre-trend test's rejection rate with no violation can be + counted for any set of pre-periods; ``PreTrendsPower`` reports + planned power for a set only where that count agrees with the rate + its formula assumes. ``summary()`` shows the comparison for the test + over all pre-periods, and a warning is issued when it disagrees. + Unrelated to a ``fit()`` keyword of the same name passed through + ``estimator_kwargs``. Returns ------- DesignDiagnosisResults One :class:`~diff_diff.SimulationPowerResults` per estimator and - effect, the size check, and the minimum detectable effects. + effect, the size check, the minimum detectable effects, and the + placebo event studies when requested. Notes ----- @@ -1490,6 +1878,14 @@ def diagnose_design( every rate and counted; an estimator that loses more than 10% of its no-effect replicates fails the size check. + A placebo event study is computed on the same draws as the comparison of + estimators. If you compared several estimators and picked one, its placebo + event study comes from draws that informed the pick. For pre-trend + planning that the choice did not see, rerun ``diagnose_design`` with the + chosen estimator alone and a new ``seed``, and use that run for pre-trend + planning only: the lock is still taken from the comparison run, because a + lock made from a single-estimator run records no comparison and no rerun. + The methodology, its sources and the choices that have no paper source are documented in ``docs/methodology/REGISTRY.md`` ``## DesignDiagnosis``. @@ -1512,6 +1908,9 @@ def diagnose_design( raise ValueError(f"alpha must be in (0, 1), got {alpha}.") if power is not None and not alpha < power < 1.0: raise ValueError(f"power must satisfy alpha < power < 1, got {power}.") + if not isinstance(event_study, (bool, np.bool_)): + raise ValueError(f"event_study must be True or False, got {event_study!r}.") + event_study = bool(event_study) resolved = _resolve_estimators(estimators) # A private copy: the caller's dict and the lists in it stay theirs. @@ -1562,6 +1961,14 @@ def diagnose_design( UserWarning, stacklevel=2, ) + if event_study: + reason = _event_study_skip_reason(est) + if reason is not None: + warnings.warn( + f"[{label}] no placebo event study is recorded: {reason}.", + UserWarning, + stacklevel=2, + ) data_sha256, data_columns = _data_fingerprint(panel, unit, time) data_generator = _make_placebo_generator( @@ -1581,9 +1988,11 @@ def diagnose_design( size_controlled: Dict[str, bool] = {} mde_results: Dict[str, SimulationMDEResults] = {} mde: Dict[str, float] = {} + event_study_results: Dict[str, EventStudyResults] = {} + event_study_checks: Dict[str, Dict[str, Any]] = {} for label, est in resolved.items(): - cells, nan_counts, size_ok, found, value = _run_estimator( + cells, nan_counts, size_ok, found, value, captured = _run_estimator( "diagnose_design", label, est, @@ -1597,6 +2006,7 @@ def diagnose_design( power, resolved_seed, progress, + event_study=event_study, ) results[label] = cells n_nan_inference[label] = nan_counts @@ -1604,6 +2014,38 @@ def diagnose_design( if found is not None: mde_results[label] = found mde[label] = value + if captured is not None: + surface, checks, reason = _placebo_event_study(est, captured, alpha) + if surface is None or checks is None: + warnings.warn( + f"[{label}] no placebo event study is recorded: {reason}.", + UserWarning, + stacklevel=2, + ) + continue + event_study_results[label] = surface + event_study_checks[label] = checks + if not checks["pretest_agrees"]: + warnings.warn( + f"[{label}] a pre-trend test over all {checks['n_pre']} " + f"pre-periods (any coefficient individually significant at " + f"{alpha:g}) rejected {checks['pretest_rejection_rate']:.1%} of " + f"the {checks['n_draws']} no-effect replicates, against " + f"{checks['pretest_expected_rate']:.1%} assumed by the " + f"pre-trend power formula. PreTrendsPower repeats this " + f"comparison for the pre-periods it plans and reports planned " + f"power only where the two agree; a test of fewer pre-periods " + f"may still agree (see PreTrendsPower.power_by_pre_periods).", + UserWarning, + stacklevel=2, + ) + if not size_ok: + warnings.warn( + f"[{label}] did not pass the size check, so pre-trend power " + f"planned from its placebo event study may be overstated.", + UserWarning, + stacklevel=2, + ) return DesignDiagnosisResults( results=results, @@ -1632,6 +2074,9 @@ def diagnose_design( data_sha256=data_sha256, data_columns=data_columns, time_periods=periods.tolist(), + event_study=event_study, + event_study_results=event_study_results, + _event_study_checks=event_study_checks, _classes={label: type(est) for label, est in resolved.items()}, _params={label: _snapshot(est.get_params()) for label, est in resolved.items()}, _fit_keywords=_snapshot(fit_extras), @@ -1773,7 +2218,7 @@ def _lock( with _WarningCapture() as capture: _preflight(label, chosen, generator, fit_kwargs, lock_seed) _reemit(label, capture.records, stacklevel=4) - cells, nan_counts, size_ok, _found, mde = _run_estimator( + cells, nan_counts, size_ok, _found, mde, _captured = _run_estimator( "lock", label, chosen, diff --git a/diff_diff/diagnostic_report.py b/diff_diff/diagnostic_report.py index 95bf171a..071d57cd 100644 --- a/diff_diff/diagnostic_report.py +++ b/diff_diff/diagnostic_report.py @@ -51,6 +51,7 @@ from diff_diff._reporting_helpers import ( # noqa: E402 (top-level import) check_design_reconciliation, + check_precomputed_pretrends_power, describe_design_reconciliation, describe_target_parameter, design_reconciliation_lines, @@ -614,6 +615,7 @@ def __init__( "aggregate('event_study') surface) and do not accept " "precomputed overrides." ) + check_precomputed_pretrends_power(self._precomputed, "DiagnosticReport") # Post-fit event-study derivation cache (see # _resolve_event_study_surface): a triple # (surface, surface_dict, why) once resolved, plus the bare diff --git a/diff_diff/guides/llms-autonomous.txt b/diff_diff/guides/llms-autonomous.txt index 358d891b..ef317564 100644 --- a/diff_diff/guides/llms-autonomous.txt +++ b/diff_diff/guides/llms-autonomous.txt @@ -1129,6 +1129,9 @@ section is the API-reference index. version; adds a "believable-magnitude" check against a power curve. - `equivalence_test_trends(df, ...)` - Bilinski-Hatfield-style equivalence test (alternative framing of the PT test). +- `PreTrendsPower().fit(diagnose_design(..., event_study=True))` - the same + analysis for a design that has not been run (planned pre-trend power); + `power_by_pre_periods` tabulates it by number of pre-periods tested - `compute_pretrends_power(results, ...)` - standalone power analysis for the PT test; takes a fitted event-study results object (CS / SA results or an `EventStudyResults` container, e.g. the TWFE diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index b493770d..9eb95d57 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -2442,7 +2442,9 @@ every listed estimator on the same placebo draws. It never estimates a real treatment effect. ```python -from diff_diff import CallawaySantAnna, ImputationDiD, TwoWayFixedEffects, diagnose_design +from diff_diff import ( + CallawaySantAnna, ImputationDiD, PreTrendsPower, TwoWayFixedEffects, diagnose_design, +) # `panel`: balanced, pre-treatment only (or pass first_treat= to truncate at # the earliest real adoption). One row per unit and period. @@ -2464,6 +2466,27 @@ size = null_run.rejection_rate # should be near alpha ok = result.size_controlled["cs"] # False -> power is not meaningful mde = result.mde["cs"] # NaN unless size is controlled +# Planned pre-trend power, before any outcome exists: keep the placebo event +# studies (CallawaySantAnna and StackedDiD candidates), then ask PreTrendsPower. +plan = diagnose_design( + panel, outcome="sales", unit="store", time="year", + estimators=[CallawaySantAnna(base_period="universal")], + cohort_periods=[2019], n_treated=12, n_simulations=500, seed=2, + event_study=True, +) +table = PreTrendsPower().power_by_pre_periods(plan) # one row per number tested +# columns: n_pre_periods, pre_periods, mdv, max_abs_pre_violation, +# power_no_violation (rate the formula assumes with no violation), +# placebo_rejection_rate (the same rate counted in the placebo draws), power +planned = PreTrendsPower().fit(plan, pre_periods=[-4, -3, -2]) # PreTrendsPowerResults +planned.mdv # smallest violation detected at 80% power +# The formula assumes each coefficient's own test holds its level. For the +# pre-periods being planned, PreTrendsPower compares the pre-trend test's +# rejection rate in the placebo draws with the rate the formula assumes and +# reports planned power only where they agree: a row that disagrees has NaN +# mdv, and fit() on such a set raises ValueError with both rates (typical with +# few treated units or many pre-periods). NIS form only (the default). + # Several estimators were compared, so locking the choice reruns "cs" alone on # the same panel with new placebo draws; the lock reports that run. lock = result.lock("cs", data=panel) @@ -2571,10 +2594,11 @@ from diff_diff import PreTrendsPower, compute_pretrends_power, compute_mdv # Class-based ptp = PreTrendsPower() -results = ptp.compute(event_study_results, M_grid=[0, 0.5, 1.0, 2.0]) +results = ptp.fit(event_study_results) # results.mdv, results.power +curve = ptp.power_curve(event_study_results, M_grid=[0, 0.5, 1.0, 2.0]) # Convenience functions -results = compute_pretrends_power(event_study_results, M_grid=[0, 0.5, 1.0, 2.0]) +results = compute_pretrends_power(event_study_results, M=0.5) mdv = compute_mdv(event_study_results, target_power=0.80) ``` diff --git a/diff_diff/guides/llms-practitioner.txt b/diff_diff/guides/llms-practitioner.txt index f8325637..6d8309ba 100644 --- a/diff_diff/guides/llms-practitioner.txt +++ b/diff_diff/guides/llms-practitioner.txt @@ -633,6 +633,15 @@ does not reject, the summary reflects whether the test is well-powered trends hold". See `docs/methodology/REPORTING.md` for the full verdict and tier rules. +Before the study has run, the same question can be asked of the planned +design: `diagnose_design(..., event_study=True)` followed by +`PreTrendsPower().fit(diagnosis)` gives the smallest trend violation the +planned pre-trend test would detect, and +`PreTrendsPower().power_by_pre_periods(diagnosis)` shows it by number of +pre-periods tested. No number is given for a set of pre-periods whose +pre-trend test, in the placebo draws, does not reject at the rate the power +formula assumes (typical with few treated units or many pre-periods). + ### Runtime guidance ```python from diff_diff import practitioner_next_steps diff --git a/diff_diff/guides/llms.txt b/diff_diff/guides/llms.txt index 4440484d..00ecdd2d 100644 --- a/diff_diff/guides/llms.txt +++ b/diff_diff/guides/llms.txt @@ -93,7 +93,7 @@ The site is organized into 5 sections, each with a landing page: - [Honest DiD](https://diff-diff.readthedocs.io/en/stable/api/honest_did.html): Rambachan & Roth (2023) sensitivity analysis — robust CI under parallel trends violations, breakdown values - [Pre-Trends Power Analysis](https://diff-diff.readthedocs.io/en/stable/api/pretrends.html): Roth (2022) Section II.A-B no-individually-significant (NIS) box-probability pretest power + minimum detectable violation; `pretest_form='nis'` (default) implements the paper's primary form, `pretest_form='wald'` retained as paper-supported alternative (Propositions 1+3+4 all apply); linear-violation MDV in Roth's γ units when relative-time labels are threaded through `fit()`; full Σ_22 routing on non-bootstrap CallawaySantAnna and SunAbraham adapters and on admitted CS-/StackedDiD-sourced `aggregate('event_study')` containers (StackedDiD persists its ES VCV in every inference mode) - [Power Analysis](https://diff-diff.readthedocs.io/en/stable/api/power.html): Analytical and simulation-based power analysis — MDE, sample size, power curves for study design -- [Design Diagnosis](https://diff-diff.readthedocs.io/en/stable/api/design.html): `diagnose_design(data, outcome=, unit=, time=, estimators=, cohort_periods=, n_treated= | treatment_fraction=, effect_sizes=, power=)` checks a planned design on the user's own UNTREATED panel before any real analysis (Bertrand, Duflo & Mullainathan 2004 placebo assignment and effect injection; Mizushima & Powell 2025 staggered placebos; Blair et al. 2019 diagnosands). It assigns placebo treatments that follow the declared design, fits every listed estimator on the same placebo draws, and returns per estimator the rejection rate under no effect (size), and power, bias, RMSE and coverage at each injected effect, plus an optional MDE. Outcome-blind (no real effect is estimated; pass `first_treat=` to truncate at the earliest real adoption). Estimators are returned in input order and never ranked; `size_controlled` flags estimators whose null rejection rate is consistent with `alpha`. Supports DifferenceInDifferences, TwoWayFixedEffects, CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, StackedDiD, EfficientDiD. Random placebo assignment tests inference, not parallel trends. `result.lock(label, data=)` records the chosen estimator as a JSON-serializable `DesignLock` (`to_json()` / `DesignLock.from_json()`, `to_estimator()`); when several estimators were compared it first reruns the chosen one alone with new placebo draws and reports that run. `lock.fit(data, first_treat= | treatment=, post=)` fits the locked analysis and returns the status `match` or `deviates` with the estimate in `.results`; `lock.reconcile(estimator, outcome=, unit=, time=, first_treat=, data=, results=)` does the same for an analysis fitted by hand (reconciliation idea: Blair et al. 2019). Pass either result to `BusinessReport` / `DiagnosticReport` as `design_reconciliation=`; `match` means agreement with the lock on the checks run, not that the design was fixed before the outcomes were seen +- [Design Diagnosis](https://diff-diff.readthedocs.io/en/stable/api/design.html): `diagnose_design(data, outcome=, unit=, time=, estimators=, cohort_periods=, n_treated= | treatment_fraction=, effect_sizes=, power=)` checks a planned design on the user's own UNTREATED panel before any real analysis (Bertrand, Duflo & Mullainathan 2004 placebo assignment and effect injection; Mizushima & Powell 2025 staggered placebos; Blair et al. 2019 diagnosands). It assigns placebo treatments that follow the declared design, fits every listed estimator on the same placebo draws, and returns per estimator the rejection rate under no effect (size), and power, bias, RMSE and coverage at each injected effect, plus an optional MDE. Outcome-blind (no real effect is estimated; pass `first_treat=` to truncate at the earliest real adoption). Estimators are returned in input order and never ranked; `size_controlled` flags estimators whose null rejection rate is consistent with `alpha`. Supports DifferenceInDifferences, TwoWayFixedEffects, CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, StackedDiD, EfficientDiD. Random placebo assignment tests inference, not parallel trends. `result.lock(label, data=)` records the chosen estimator as a JSON-serializable `DesignLock` (`to_json()` / `DesignLock.from_json()`, `to_estimator()`); when several estimators were compared it first reruns the chosen one alone with new placebo draws and reports that run. `lock.fit(data, first_treat= | treatment=, post=)` fits the locked analysis and returns the status `match` or `deviates` with the estimate in `.results`; `lock.reconcile(estimator, outcome=, unit=, time=, first_treat=, data=, results=)` does the same for an analysis fitted by hand (reconciliation idea: Blair et al. 2019). Pass either result to `BusinessReport` / `DiagnosticReport` as `design_reconciliation=`; `match` means agreement with the lock on the checks run, not that the design was fixed before the outcomes were seen With `event_study=True` it also keeps a placebo event study per `CallawaySantAnna` / `StackedDiD` estimator (`event_study_results`), which `PreTrendsPower().fit(diagnosis)` turns into planned pre-trend power before any outcome exists (Roth 2022 formula on the placebo covariance; `power_by_pre_periods` tabulates it by pre-periods tested); planned power is reported for a set of pre-periods only when the pre-trend test over that set rejected, in the placebo draws, at the rate the formula assumes (NIS form only). - [MMM Calibration Export](https://diff-diff.readthedocs.io/en/stable/api/mmm.html): Assemble Marketing Mix Model calibration inputs from experiment results. Two input routes: explicit already-scoped numbers, or the pinned `AggregationResult` container from post-fit `results.aggregate('simple'|'group')` via `aggregation_result=` + `scale=`, or a `results.aggregate('total')` container ALONE (its single row is the estimator-owned total; scale is rejected - for overall totals this supersedes scale="auto") (effect = att x scale per row, in `to_dataframe()` order; `scale="auto"` reads the container's treated-obs count and is honored ONLY for ImputationDiD/TwoStageDiD fits - it acknowledges an additive-level outcome, an unweighted fit, and fully identified effects; other estimators and raw results objects fail closed). `to_pymc_marketing_lift_test(channel, x, delta_x, delta_y=, sigma=, aggregation_result=, scale=, dims=, on_wrong_sign=)` builds the PyMC-Marketing/prophetverse lift-test DataFrame with sign/zero/positivity guards. `to_meridian_roi_prior(incremental_outcome=, incremental_outcome_se=, aggregation_result=, scale=, spend, parameter="roi_m"|"mroi_m", se_widening=)` builds Google Meridian lognormal ROI priors (spend-weighted pooling, lognormal parity with `lognormal_dist_from_mean_std`, channel- and time-scoped `.to_code()` snippet setting `media_prior_type` - time scope via `meridian_calibration_mask(media_times=, media_channels=, channel=, window=)`, which builds the boolean (n_media_times, n_media_channels) mask (window = inclusive (start, end) tuple or explicit-labels list; experiment channel True on the window, every other channel ALL-TRUE per Meridian's documented convention; roi_m priors only - Meridian rejects the mask for mroi_m) and whose array `.to_code()` serializes into the snippet, or via a mask expression string, or full_model_window=True; widen `se_widening` when pooling a group-level container's same-fit cohorts). Pure numpy/pandas; imports no MMM package; never calls `aggregate()` itself. - Conley spatial HAC SE (`vcov_type="conley"`) on cross-sectional `LinearRegression` / `compute_robust_vcov` PLUS panel `DifferenceInDifferences` / `TwoWayFixedEffects` (with `conley_lag_cutoff=` for within-unit Bartlett temporal HAC) — Conley (1999) spatial-correlation-aware SEs with haversine/euclidean/callable distance metric and Bartlett/uniform spatial kernel; panel path uses the R `conleyreg`-form block-decomposed sandwich (within-period spatial + within-unit Bartlett serial, same-time excluded); parity vs R `conleyreg` (Düsterhöft 2021) on cross-sectional AND panel `lag_cutoff > 0` fixtures. Combining with explicit `cluster=` applies the combined spatial + cluster product kernel `K_total[i,j] = K_space · 1{c_i = c_j}` (cluster must be constant within each unit across periods on the panel path; validator-enforced). DiD takes `unit=` as a fit-time kwarg when `vcov_type="conley"` (not on `__init__`). Sparse k-d-tree fast path auto-activates for `n > 5_000` with bartlett kernel + haversine/euclidean metric diff --git a/diff_diff/honest_did.py b/diff_diff/honest_did.py index cd7e7c94..f0368bc1 100644 --- a/diff_diff/honest_did.py +++ b/diff_diff/honest_did.py @@ -1178,6 +1178,17 @@ def _extract_event_study_params( from diff_diff.results_base import EventStudyResults if isinstance(results, EventStudyResults): + from diff_diff.design import PLACEBO_ESTIMAND + + if results.estimand == PLACEBO_ESTIMAND: + raise ValueError( + "This is a placebo event study from diagnose_design(..., " + "event_study=True): its coefficients are means over placebo " + "draws, not estimates of an effect, so HonestDiD bounds on it " + "have no meaning. Sensitivity planning at the design stage is " + "not implemented; PreTrendsPower accepts this object for " + "planned pre-trend power." + ) return _extract_container_params(results) # Try CallawaySantAnnaResults diff --git a/diff_diff/pretrends.py b/diff_diff/pretrends.py index 4f54692a..7fa228f3 100644 --- a/diff_diff/pretrends.py +++ b/diff_diff/pretrends.py @@ -277,9 +277,99 @@ def _extract_container_vcov_subblock( sub = _validate_vcov_subblock( np.asarray(surface.vcov)[np.ix_(indices, indices)], ses, "PreTrendsPower" ) + # A placebo event study from diagnose_design: the covariance is the sample + # covariance of the coefficients across placebo draws, not a fit's own. + if _is_placebo_surface(surface): + return sub, "placebo_draws" return sub, "full_pre_period_vcov" +def _validate_violation_magnitude(M: Any) -> None: + """Refuse a violation magnitude that is not a finite number. + + A NaN magnitude makes every comparison in the NIS acceptance region + false, which would be reported as a rejection probability of one. + """ + values = np.atleast_1d(np.asarray(M, dtype=float)) + if not np.all(np.isfinite(values)): + raise ValueError(f"Violation magnitude M must be finite, got {M!r}.") + + +def _is_placebo_surface(obj: Any) -> bool: + """Whether ``obj`` is a placebo event study recorded by ``diagnose_design``.""" + from diff_diff.design import PLACEBO_ESTIMAND + from diff_diff.results_base import EventStudyResults + + return isinstance(obj, EventStudyResults) and obj.estimand == PLACEBO_ESTIMAND + + +def _resolve_planned_input(results: Any) -> Any: + """Unwrap a ``DesignDiagnosisResults`` to the placebo event study it holds. + + Any other input is returned unchanged. Called once at the top of every + public method that takes ``results``; the methods pass the resolved object + to each other, so the size warning below is issued once per public call. + """ + from diff_diff.design import DesignDiagnosisResults + + if not isinstance(results, DesignDiagnosisResults): + return results + if not results.event_study: + raise ValueError( + "This design diagnosis holds no placebo event study. Run " + "diagnose_design(..., event_study=True) to record one." + ) + surfaces = results.event_study_results + if not surfaces: + raise ValueError( + "This design diagnosis recorded no placebo event study for any of " + f"its estimators ({', '.join(results.estimators)}). One is recorded " + "for CallawaySantAnna and StackedDiD estimators; see the warnings " + "diagnose_design issued." + ) + if len(surfaces) > 1: + raise ValueError( + "This design diagnosis holds placebo event studies for several " + f"estimators ({', '.join(surfaces)}). Pass one of them: " + "diagnosis.event_study_results[label]." + ) + ((label, surface),) = surfaces.items() + if not results.size_controlled.get(label, True): + warnings.warn( + f"Estimator '{label}' did not pass the size check of the design " + "diagnosis, so pre-trend power planned from its placebo event study " + "may be overstated.", + UserWarning, + stacklevel=3, + ) + return surface + + +def _planned_pre_periods(surface: Any, pre_periods: Optional[List[int]]) -> List[Any]: + """The pre-periods a planned fit tests, in chronological order.""" + if pre_periods is not None: + return sorted(pre_periods) + eligible = ( + (~surface.is_reference) + & np.isfinite(surface.se) + & (surface.se > 0) + & (surface.event_time < 0) + ) + return sorted(surface.event_time[eligible].tolist()) + + +def _planned_withheld_message(tested: List[Any], counted: float, expected: float, n: int) -> str: + direction = "more" if counted > expected else "less" + return ( + f"Planned pre-trend power is not reported for a test of " + f"{len(tested)} pre-period(s) {tested}: in the {n} placebo draws that " + f"test rejected {counted:.1%} of the time with no violation, against " + f"{expected:.1%} assumed by the power formula (it rejects {direction} " + f"often than assumed, so the formula does not describe it). A test of " + f"fewer pre-periods may agree: see power_by_pre_periods." + ) + + # ============================================================================= # Results Classes # ============================================================================= @@ -370,8 +460,11 @@ class PreTrendsPowerResults(Diagnostic): # Provenance for downstream tier classification. Populated at fit time # from `_extract_pre_period_params`. ``"full_pre_period_vcov"`` when # off-diagonal pre-period covariances were used; ``"diag_fallback"`` - # when only per-period SEs were available; ``"unknown"`` for legacy - # serialized results pre-PR-B (backwards-compat default). See + # when only per-period SEs were available; ``"placebo_draws"`` when the + # input was a placebo event study from ``diagnose_design`` (planned + # power for a design that has not been run; the covariance is the sample + # covariance of the coefficients across placebo draws); ``"unknown"`` for + # legacy serialized results pre-PR-B (backwards-compat default). See # ``diagnostic_report._infer_cov_source`` for consumer-side use. covariance_source: str = "unknown" @@ -591,6 +684,7 @@ def power_at(self, M: float) -> float: """ from scipy import stats + _validate_violation_magnitude(M) n_pre = self.n_pre_periods # Prefer the persisted fitted weights (populated for all violation @@ -1086,6 +1180,8 @@ def _extract_pre_period_params( - ``"diag_fallback"`` when only the per-period standard errors were available (bootstrap / replicate-weight CS or SA fits). + - ``"placebo_draws"`` when the container is a placebo event + study recorded by ``diagnose_design(..., event_study=True)``. ``DiagnosticReport`` consumes this label downstream to decide whether the power-tier should be conservatively @@ -2081,6 +2177,16 @@ def fit( ``DMLDiDResults.aggregate('event_study')``, or ``StackedDiDResults.aggregate('event_study')`` (Stacked containers require ``kappa_pre >= 2``). + A design that has not been run is also accepted: a + ``DesignDiagnosisResults`` from ``diagnose_design(..., + event_study=True)`` that holds one placebo event study, or one + entry of its ``event_study_results``. The result is then planned + pre-trend power (``covariance_source == "placebo_draws"``). It is + reported only when the pre-trend test over the tested pre-periods + rejected, in the placebo draws, at the rate the formula assumes + (``ValueError`` with both rates otherwise; see + :meth:`power_by_pre_periods`), and for ``pretest_form="nis"`` + only. M : float, optional Specific violation magnitude to evaluate. If None, evaluates at a default magnitude based on the data. @@ -2095,6 +2201,12 @@ def fit( PreTrendsPowerResults Power analysis results including power and MDV. """ + if M is not None: + _validate_violation_magnitude(M) + # A design diagnosis is unwrapped to its placebo event study, which is + # also what the result keeps as original_results. + results = _resolve_planned_input(results) + # Extract pre-period parameters (now includes relative_times for # γ-unit MDV under linear violation_type, plus the covariance-source # provenance label for downstream DiagnosticReport / BusinessReport @@ -2113,6 +2225,16 @@ def fit( # convention (skip L2 normalization for linear-with-relative_times). weights = self._get_violation_weights(n_pre, relative_times=relative_times) + # A design that has not been run: report power only if the pre-trend + # test behaves in the placebo draws as the formula assumes. + if _is_placebo_surface(results): + tested = _planned_pre_periods(results, pre_periods) + counted, expected, n_draws, agrees = self._planned_pretest_check( + results, tested, weights, vcov + ) + if not agrees: + raise ValueError(_planned_withheld_message(tested, counted, expected, n_draws)) + # Compute MDV (dispatches on self.pretest_form) mdv = self._compute_mdv(weights, vcov) @@ -2160,7 +2282,7 @@ def power_at( Parameters ---------- results : results object - Event study results. + Event study results, or a design-stage input (see :meth:`fit`). M : float Violation magnitude. pre_periods : list of int, optional @@ -2187,7 +2309,7 @@ def power_curve( Parameters ---------- results : results object - Event study results. + Event study results, or a design-stage input (see :meth:`fit`). M_grid : list of float, optional Specific violation magnitudes to evaluate. If None, creates automatic grid from 0 to 2.5 * MDV. @@ -2201,6 +2323,7 @@ def power_curve( PreTrendsPowerCurve Power curve data with plot method. """ + results = _resolve_planned_input(results) # Extract parameters (6-tuple includes relative_times + covariance # source; the source label is currently unused on the curve path but # the unpack must match the helper's signature). @@ -2208,6 +2331,13 @@ def power_curve( results, pre_periods ) weights = self._get_violation_weights(n_pre, relative_times=relative_times) + if _is_placebo_surface(results): + tested = _planned_pre_periods(results, pre_periods) + counted, expected, n_draws, agrees = self._planned_pretest_check( + results, tested, weights, vcov + ) + if not agrees: + raise ValueError(_planned_withheld_message(tested, counted, expected, n_draws)) # Compute MDV mdv = self._compute_mdv(weights, vcov) @@ -2217,6 +2347,7 @@ def power_curve( max_M = min(2.5 * mdv if np.isfinite(mdv) else 10 * np.max(ses), 100) M_grid = np.linspace(0, max_M, n_points) else: + _validate_violation_magnitude(M_grid) M_grid = np.asarray(M_grid) # Compute power at each M @@ -2233,6 +2364,160 @@ def power_curve( pretest_form=self.pretest_form, ) + def _planned_pretest_check( + self, surface: Any, tested: List[Any], weights: np.ndarray, vcov: np.ndarray + ) -> Tuple[float, float, int, bool]: + """Does the pre-trend test over ``tested`` behave as the formula assumes? + + Compares how often the test rejected in the placebo draws (no + violation is present in any of them) with the rejection probability + the formula gives at a violation of zero. Returns the counted rate, + the assumed rate, the number of draws and the verdict. + + Planned power is available for the NIS form only: that is the test + the placebo record can count, and the one the library's simulation + checked against direct trend injection. + """ + from diff_diff.design import _pretest_size_ok, placebo_pretest_rate + + if self.pretest_form != "nis": + raise ValueError( + "Planned pre-trend power (a design-stage input from " + "diagnose_design) is available for pretest_form='nis' only: the " + "placebo draws record each coefficient against its own standard " + "error, which is the NIS test, and the joint Wald form has not " + "been checked against placebo draws." + ) + counted, n_draws = placebo_pretest_rate(surface, tested, self.alpha) + expected = float(self._compute_power(0.0, weights, vcov)[0]) + return counted, expected, n_draws, _pretest_size_ok(counted, expected, n_draws) + + def power_by_pre_periods(self, results: Any, M: Optional[float] = None) -> pd.DataFrame: + """ + Planned pre-trend power by number of pre-periods tested. + + For a design that has not been run: one row per ``K``, where the test + covers the ``K`` pre-period coefficients closest to treatment. Each + row is :meth:`fit` on those ``K`` coefficients. + + A row describes the same planned data with fewer coefficients tested. + It is not a design with fewer periods of data. + + The power formula assumes that each coefficient's own test rejects at + its nominal level when nothing is wrong. Every row is checked against + the placebo draws: ``placebo_rejection_rate`` is how often the test + over that row's coefficients rejected in the draws (none of which has + a violation), and ``power_no_violation`` is the rate the formula + assumes. Where the two disagree by more than Monte Carlo error the + row's ``mdv``, ``max_abs_pre_violation`` and ``power`` are NaN, and + one warning lists the rows concerned. + + Parameters + ---------- + results : DesignDiagnosisResults or EventStudyResults + A design diagnosis run with ``event_study=True`` that holds one + placebo event study, or one entry of its ``event_study_results``. + A fitted model is refused: choosing how many pre-periods to test + after seeing the estimated event study is a choice made on the + outcome. ``fit(results, pre_periods=...)`` remains available for + a fitted model. + M : float, optional + Violation magnitude at which to report ``power``. ``None`` leaves + that column NaN. + + Returns + ------- + pd.DataFrame + Columns ``n_pre_periods``, ``pre_periods`` (the event times + tested), ``mdv``, ``max_abs_pre_violation``, + ``power_no_violation`` (the probability, under the formula, that + the test rejects when there is no violation: above ``alpha`` and + growing with ``K``, because the test rejects when any single + coefficient is significant), ``placebo_rejection_rate`` (the same + rate counted in the placebo draws), and ``power`` at ``M``. + + Raises + ------ + TypeError + If ``results`` is not a design-stage input. + ValueError + If ``violation_type="custom"`` (custom weights are positional for + one fixed set of pre-periods and have no defined subset) or + ``pretest_form="wald"`` (planned power is available for the NIS + form only). + """ + results = _resolve_planned_input(results) + if not _is_placebo_surface(results): + raise TypeError( + "power_by_pre_periods plans a design that has not been run: pass " + "a DesignDiagnosisResults from diagnose_design(..., " + "event_study=True) or one entry of its event_study_results. For " + "a fitted model use fit(results, pre_periods=...)." + ) + if self.violation_type == "custom": + raise ValueError( + "power_by_pre_periods does not support violation_type='custom': " + "custom weights are positional for one fixed set of pre-periods. " + "Call fit(results, pre_periods=...) with weights for that set." + ) + if M is not None: + _validate_violation_magnitude(M) + labels = _planned_pre_periods(results, None) + if not labels: + raise ValueError("No pre-treatment periods found in event study.") + rows: List[Dict[str, Any]] = [] + withheld: List[int] = [] + # The extraction repeats its interpretation warnings on every call; + # issue each distinct one once for the whole table. + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + for k in range(1, len(labels) + 1): + tested = labels[-k:] + _, _, vcov, n_pre, relative_times, _ = self._extract_pre_period_params( + results, tested + ) + weights = self._get_violation_weights(n_pre, relative_times=relative_times) + counted, expected, _, agrees = self._planned_pretest_check( + results, tested, weights, vcov + ) + row: Dict[str, Any] = { + "n_pre_periods": n_pre, + "pre_periods": tested, + "mdv": np.nan, + "max_abs_pre_violation": np.nan, + "power_no_violation": expected, + "placebo_rejection_rate": counted, + "power": np.nan, + } + if agrees: + mdv = self._compute_mdv(weights, vcov) + row["mdv"] = mdv + row["max_abs_pre_violation"] = ( + float(mdv * np.max(np.abs(weights))) if np.isfinite(mdv) else mdv + ) + if M is not None: + row["power"] = float(self._compute_power(M, weights, vcov)[0]) + else: + withheld.append(k) + rows.append(row) + seen = set() + for record in caught: + key = (record.category, str(record.message)) + if key not in seen: + seen.add(key) + warnings.warn(str(record.message), record.category, stacklevel=2) + if withheld: + warnings.warn( + f"Planned pre-trend power is not reported for tests of " + f"{withheld} pre-period(s): in the placebo draws those tests " + f"rejected, with no violation, at a rate that differs from the " + f"one the power formula assumes by more than Monte Carlo error " + f"(columns placebo_rejection_rate and power_no_violation).", + UserWarning, + stacklevel=2, + ) + return pd.DataFrame(rows) + def sensitivity_to_honest_did( self, results: Any, @@ -2247,7 +2532,9 @@ def sensitivity_to_honest_did( Parameters ---------- results : results object - Event study results. + Event study results from a fitted model. A design-stage input + (a ``DesignDiagnosisResults`` or one of its placebo event + studies) is refused: this method describes a realized estimate. pre_periods : list of int, optional Explicit list of pre-treatment periods. See fit() for details. @@ -2259,6 +2546,14 @@ def sensitivity_to_honest_did( - honest_M_at_mdv: Corresponding M value for HonestDiD - interpretation: Text explaining the relationship """ + results = _resolve_planned_input(results) + if _is_placebo_surface(results): + raise ValueError( + "sensitivity_to_honest_did describes a realized event study; a " + "placebo event study from diagnose_design has no estimate to " + "compare. Sensitivity planning at the design stage is not " + "implemented." + ) pt_results = self.fit(results, pre_periods=pre_periods) mdv = pt_results.mdv # Level-scale scalar for comparison against the level-scale @@ -2335,7 +2630,10 @@ def compute_pretrends_power( Parameters ---------- results : results object - Event study results (CS / SA), or the unified event-study + Event study results (CS / SA), a design-stage input (a + ``DesignDiagnosisResults`` from ``diagnose_design(..., + event_study=True)`` holding one placebo event study, or one entry of + its ``event_study_results``), or the unified event-study container from ``CallawaySantAnnaResults.aggregate('event_study')``, ``DMLDiDResults.aggregate('event_study')``, or ``StackedDiDResults.aggregate('event_study')`` (Stacked @@ -2403,7 +2701,10 @@ def compute_mdv( Parameters ---------- results : results object - Event study results (CS / SA), or the unified event-study + Event study results (CS / SA), a design-stage input (a + ``DesignDiagnosisResults`` from ``diagnose_design(..., + event_study=True)`` holding one placebo event study, or one entry of + its ``event_study_results``), or the unified event-study container from ``CallawaySantAnnaResults.aggregate('event_study')``, ``DMLDiDResults.aggregate('event_study')``, or ``StackedDiDResults.aggregate('event_study')`` (Stacked diff --git a/diff_diff/results_base.py b/diff_diff/results_base.py index 594f69f2..adde44bc 100644 --- a/diff_diff/results_base.py +++ b/diff_diff/results_base.py @@ -393,7 +393,12 @@ class EventStudyResults(BaseResults): #: The estimand label for the ``att`` column when the producer's #: per-horizon estimand is NOT an ATT - HeterogeneousAdoptionDiD's #: per-horizon "WAS"/"WAS_d_lower" (row M-027; ``_from_had`` relays - #: ``target_parameter``). None means the column is an ATT (every other + #: ``target_parameter``), or ``"placebo"`` on the placebo event study + #: that ``diagnose_design(..., event_study=True)`` records (the column + #: is the mean of placebo coefficients over the draws, and ``se`` their + #: spread: not an estimate of an effect; ``PreTrendsPower`` accepts such + #: a surface for planned pre-trend power, ``HonestDiD`` refuses it). + #: None means the column is an ATT (every other #: producer), keeping their rendering byte-stable. ``summary()`` uses #: it as the column heading and ``to_dict()`` serializes it, so the #: numbers never silently change meaning. Optional provenance appended diff --git a/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst b/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst index 193aaa44..8e1190ca 100644 --- a/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst +++ b/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst @@ -25,6 +25,7 @@ .. autosummary:: + ~DesignDiagnosisResults.event_study ~DesignDiagnosisResults.results ~DesignDiagnosisResults.mde_results ~DesignDiagnosisResults.estimators @@ -51,4 +52,5 @@ ~DesignDiagnosisResults.data_sha256 ~DesignDiagnosisResults.data_columns ~DesignDiagnosisResults.time_periods + ~DesignDiagnosisResults.event_study_results diff --git a/docs/api/_autosummary/diff_diff.PreTrendsPower.rst b/docs/api/_autosummary/diff_diff.PreTrendsPower.rst index b5085f8e..bd253e7c 100644 --- a/docs/api/_autosummary/diff_diff.PreTrendsPower.rst +++ b/docs/api/_autosummary/diff_diff.PreTrendsPower.rst @@ -15,6 +15,7 @@ ~PreTrendsPower.fit ~PreTrendsPower.get_params ~PreTrendsPower.power_at + ~PreTrendsPower.power_by_pre_periods ~PreTrendsPower.power_curve ~PreTrendsPower.sensitivity_to_honest_did ~PreTrendsPower.set_params diff --git a/docs/api/design.rst b/docs/api/design.rst index f165f247..04b613cd 100644 --- a/docs/api/design.rst +++ b/docs/api/design.rst @@ -41,6 +41,35 @@ test inference - size and power - on your panel's own error structure. They do not test parallel trends: a design that passes the size check can still be biased if treatment goes to units on a different trend. +**Planned pre-trend power.** With ``event_study=True`` the diagnosis also keeps, +for each ``CallawaySantAnna`` and ``StackedDiD`` estimator, a placebo event +study: the mean and the covariance, across the no-effect draws, of the +event-study coefficients of each fit +(``DesignDiagnosisResults.event_study_results``). Pass the diagnosis to +:class:`~diff_diff.PreTrendsPower` and it returns, before any outcome exists, +the smallest trend violation the design's pre-trend test would detect with the +target power; :meth:`~diff_diff.PreTrendsPower.power_by_pre_periods` shows how +that changes with the number of pre-periods tested. These numbers come from +Roth's (2022) formula, which assumes that each coefficient's own test rejects +at its nominal level when nothing is wrong. That assumption is checked against +the placebo draws, none of which contains a violation: for the pre-periods +being planned, ``PreTrendsPower`` counts how often the pre-trend test rejected +in the draws and compares the count with the rate the formula assumes. Planned +power is reported only where the two agree within Monte Carlo error. Where +they do not (typically with few treated units or many pre-periods), ``fit`` +raises with both rates and the by-pre-period table leaves the row blank; a +test of fewer pre-periods often still agrees. ``summary()`` shows the +comparison for the test over all pre-periods. Planned power is available for +the default pre-test form (any coefficient individually significant) only. +The surface's ``att`` column is a mean of placebo coefficients, labelled +``estimand="placebo"``, and its ``se`` is the spread of one fit's coefficient, +not inference on an effect; plot it with ``ylabel="Placebo estimate"``. +If you compared several estimators and picked one, its placebo event study +comes from draws that informed the pick. For pre-trend planning the choice did +not see, rerun ``diagnose_design`` with the chosen estimator alone and a new +``seed``, and use that run for pre-trend planning only: the lock is still taken +from the comparison run. + **Design lock.** :meth:`~diff_diff.DesignDiagnosisResults.lock` records one estimator and its configuration as a :class:`~diff_diff.DesignLock`. Comparing several estimators and then quoting the chosen one's power from the same runs diff --git a/docs/api/pretrends.rst b/docs/api/pretrends.rst index ee2e0b8b..c9a9d8ef 100644 --- a/docs/api/pretrends.rst +++ b/docs/api/pretrends.rst @@ -17,11 +17,24 @@ violations of parallel trends. This module provides tools to assess: Key insights from Roth (2022): -- Pre-trends tests are joint tests that pre-period coefficients equal zero +- The usual pre-trends check looks for any individually significant pre-period + coefficient (the default ``pretest_form="nis"``); a joint Wald test is the + alternative (``pretest_form="wald"``) - Standard pre-trends tests often have low power against linear trends - A "passed" pre-trends test may simply reflect lack of statistical power - MDV provides the minimum violation the test could have detected +**Before the study has run.** ``PreTrendsPower`` also accepts a design that +has not been run: a :class:`~diff_diff.DesignDiagnosisResults` from +``diagnose_design(..., event_study=True)``, or one entry of its +``event_study_results``. The result is then planned pre-trend power +(``covariance_source == "placebo_draws"``), and +:meth:`~diff_diff.PreTrendsPower.power_by_pre_periods` tabulates it by the +number of pre-periods tested. Planned power is reported for a set of +pre-periods only when the pre-trend test over that set rejected, in the +placebo draws, at the rate the formula assumes; it is available for +``pretest_form="nis"`` only. See :doc:`design` for the details. + PreTrendsPower -------------- @@ -40,6 +53,7 @@ Main class for pre-trends power analysis. ~PreTrendsPower.fit ~PreTrendsPower.power_curve + ~PreTrendsPower.power_by_pre_periods ~PreTrendsPower.sensitivity_to_honest_did Example diff --git a/docs/doc-deps.yaml b/docs/doc-deps.yaml index 37661eaf..10d71995 100644 --- a/docs/doc-deps.yaml +++ b/docs/doc-deps.yaml @@ -1350,10 +1350,16 @@ sources: drift_risk: low docs: - path: docs/methodology/REGISTRY.md - section: "Pre-trends" + section: "PreTrendsPower" type: methodology - path: docs/api/pretrends.rst type: api_reference + - path: docs/api/design.rst + type: api_reference + note: "Planned pre-trend power from a design diagnosis; power_by_pre_periods" + - path: docs/tutorials/34_design_diagnosis.ipynb + type: tutorial + note: "Planned pre-trend power section" - path: docs/tutorials/04_parallel_trends.ipynb type: tutorial - path: docs/tutorials/07_pretrends_power.ipynb @@ -1496,6 +1502,9 @@ sources: - path: docs/tutorials/34_design_diagnosis.ipynb type: tutorial note: "diagnose_design, lock, DesignLock.fit, reconcile and the report keyword on one worked panel; drift-locked at tests/test_t34_design_diagnosis_drift.py" + - path: docs/api/pretrends.rst + type: api_reference + note: "Design-stage input: PreTrendsPower on a placebo event study recorded by diagnose_design(event_study=True)" - path: docs/index.rst type: user_guide note: "Diagnostics & Sensitivity table row" diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index a14692e8..d8a75d21 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -6795,6 +6795,7 @@ CRITICAL: δ_pre = β_pre pins pre-treatment violations to observed coefficients - **Note:** Phase 7d: survey variance support. When input results carry `survey_metadata` with `df_survey`, Delta^SD smoothness uses folded non-central t critical values (`scipy.stats.nct`); Delta^RM and naive FLCI paths use `_get_critical_value(alpha, df)` (standard t-distribution). `df_survey=0` → NaN inference. CallawaySantAnnaResults stores `event_study_vcov` (full cross-event-time VCV from IF vectors; on bootstrap fits the covariance of the event-study bootstrap draws, see the CallawaySantAnna bootstrap event-study covariance Note), which HonestDiD uses instead of the diagonal fallback. For replicate-weight designs, the event-study VCV falls back to diagonal (multivariate replicate VCV deferred). - **Note (deviation from R):** When HonestDiD receives bootstrap-fitted CallawaySantAnna results (`n_bootstrap > 0`), it uses the covariance of the event-study bootstrap draws (see the CallawaySantAnna bootstrap event-study covariance Note), whose diagonal is the bootstrap SEs squared, so the analytical VCV is never mixed with bootstrap SEs. R's `honest_did.AGGTEobj` computes the covariance from the influence function matrix instead. On both input routes (native results and the `aggregate('event_study')` container) the stored matrix passes `_validate_vcov_subblock(..., allow_singular=False)` before use, so a singular matrix (fewer PSUs than horizons, analytical or bootstrap) raises `ValueError` rather than returning bounds; previously only the container route checked. Where no bootstrap covariance is stored (`n_bootstrap` at or below the number of event times, or a non-finite draw), HonestDiD falls back to `diag(se^2)` from the bootstrap SEs with a UserWarning; increase `n_bootstrap` or use analytical SEs (`n_bootstrap=0`) for the full covariance structure. - **Note (deviation from R):** When CallawaySantAnna results are passed to HonestDiD, `base_period != "universal"` emits a warning but does not error. R's `honest_did::honest_did.AGGTEobj` requires universal base period. Our implementation warns because the varying-base pre-treatment coefficients use consecutive comparisons (not a common reference), which changes the parallel-trends restriction interpretation. +- **Note (placebo event studies are refused):** an `EventStudyResults` with `estimand="placebo"` (recorded by `diagnose_design(..., event_study=True)`) raises `ValueError`. Its coefficients are means over placebo draws, not estimates of an effect, so bounds on them have no meaning. Sensitivity planning at the design stage is not implemented. - **Note (common-reference guard — gapped universal grids):** CallawaySantAnna `base_period="universal"` fits record `reference_event_times` — the distinct per-cohort positional-base event times (also carried on the `EventStudyResults` container). On a gapped time grid the positional bases land at different event times, and a cohort's base can OVERLAP another cohort's estimated horizon, where the aggregated row is a real estimate and NO reference-only row marks the anchor — `is_reference` cannot see it. When the field carries more than one entry, HonestDiD raises on BOTH input routes (native results and container) rather than returning bounds over coefficients normalized against different bases: Rambachan-Roth's `δ₀ = 0` normalization is defined around one common reference. PreTrendsPower applies the same guard (its hypothesized violation `δ` is likewise defined relative to one reference). SunAbraham fits record the field too - the distinct per-cohort omitted relative periods, more than one when a cohort cannot be normalized at `e = -1 - anticipation` (SunAbraham per-cohort reference Note) - and the native SunAbraham route of PreTrendsPower applies the guard; HonestDiD has no SunAbraham route. Varying-base fits carry `reference_event_times=None` (no constant per-cohort reference exists) and are covered by the varying-base warnings instead. Universal-base inputs WITHOUT the field are never failed open: the native route re-derives the bases from the materialized reference cells (covers pre-3.9 pickles), and a provenance-less universal container (hand-built; producer-built containers always record the field) warns fail-safe that the common reference cannot be verified. Container admission covers CS- and Stacked-sourced containers (row M-024): StackedDiD threads `base_period="universal"` and a singleton `reference_event_times` by construction (one omitted reference per fit), needs `kappa_pre >= 2` for estimated pre-periods, and HonestDiD additionally requires the full retained event-study covariance (pre+post sub-block) non-singular — see the StackedDiD section's container-admission Note for the df_survey and withheld-inference semantics. **Reference implementation(s):** @@ -6882,6 +6883,9 @@ Violation types: The diag-fallback path is therefore reserved for cases where the analytical VCV is genuinely unavailable (bootstrap SA fits, bootstrap CS fits with `n_bootstrap` at or below the number of event times, replicate-weight survey fits, a calendar container without `vcov`). In those cases dropping off-diagonals is documented as a non-paper approximation — not provably conservative, since the direction of the discrepancy with the full-Σ_22 calc depends on the sign and magnitude of the dropped correlations. See `docs/methodology/papers/roth-2022-review.md` for the full derivation. +- **Note (non-finite violation magnitude):** `fit`, `power_at`, `power_curve`, `power_by_pre_periods` and `PreTrendsPowerResults.power_at` raise `ValueError` for a violation magnitude `M` that is NaN or infinite. A NaN makes every comparison in the NIS acceptance region false, which was previously reported as a rejection probability of one (and as `alpha` by the Wald form). +- **Note (design-stage input):** `fit`, `power_at`, `power_curve`, `compute_pretrends_power` and `compute_mdv` also accept a design that has not been run: a `DesignDiagnosisResults` from `diagnose_design(..., event_study=True)` that holds exactly one placebo event study, or one entry of its `event_study_results`. The surface takes the container route unchanged (reference anchoring, `pre_periods`, the common-reference guard, the varying-base warning) and the result carries `covariance_source="placebo_draws"`. Using a placebo covariance in Roth's formula is a library extension. Planned power is reported for a set of pre-periods only when the pre-trend test over that set rejected, in the placebo draws, at the rate the formula assumes, and for `pretest_form="nis"` only; what the extension rests on, that check, and the measured agreement with direct trend injection are in `## DesignDiagnosis` (`Note (placebo covariance as the planned covariance)`, `Note (pre-test check)`). A planned result is refused by `sensitivity_to_honest_did`, by `HonestDiD`, and as `precomputed["pretrends_power"]` in the reports, each of which describes a fitted model. +- **Note (`power_by_pre_periods`):** for a design-stage input only, one row per `K`: the test over the `K` pre-period coefficients nearest to treatment. `power_no_violation` is the rejection probability the formula gives at `M = 0`, above `alpha` and growing with `K` (with independent coefficients, `1 - (1 - alpha)^K`); `placebo_rejection_rate` is the same rate counted in the placebo draws. A row whose two rates disagree (the pre-test check) has NaN `mdv`, `max_abs_pre_violation` and `power`. A row is the same planned data with fewer coefficients tested, not a design with fewer periods of data. A fitted model is refused (`TypeError`): choosing how many pre-periods to test after seeing the estimated event study is a choice made on the outcome; `fit(results, pre_periods=...)` is unchanged for fitted models. `violation_type="custom"` is refused because custom weights are positional for one fixed set of pre-periods. - **Backwards-compat addendum (`power_at()` for `violation_type='custom'`):** `PreTrendsPowerResults` now persists `violation_weights` on fresh fits (PR-B Step 5), so `power_at(M)` works for all four violation types including custom. Old serialized results from before PR-B's field addition have `violation_weights=None`; for those legacy results, `power_at(M)` falls back to weight reconstruction from `violation_type + n_pre_periods`, but for `violation_type='custom'` the custom weights cannot be reconstructed and `power_at(M)` raises `NotImplementedError` with a "refit with current library version" message. Fresh fits do not hit this guard. **Reference implementation(s):** @@ -6899,6 +6903,7 @@ Violation types: - [x] R `pretrends` parity at commit `122731d082` (PR-C, 2026-05-19; 4 fixtures × NIS power + γ_p MDV at `atol=1e-4`) - [x] Power curve plotting over violation magnitudes (preserved from pre-PR-B) - [x] Integrates with HonestDiD for combined sensitivity analysis (preserved from pre-PR-B) +- [x] Design-stage input: planned power from a placebo event study equals the hand computation on its covariance; the pre-test check on the tested set, in both directions; `power_by_pre_periods` with blank rows; refusals (Wald form, a surface without its record, fitted models, reports, `HonestDiD`): `tests/test_design_event_study.py::TestPlannedPower`, `TestPowerByPrePeriods`, `TestConsumers` --- @@ -7080,6 +7085,28 @@ with data: data_sha256 fingerprint of the rows in the locked periods - The treatment columns are arguments and are not taken from the lock: `first_treat` for the estimators fitted with a first-treatment-period column, `treatment` and `post` for `DifferenceInDifferences` and `TwoWayFixedEffects`. The lock's own `first_treat` field is the column that truncated the diagnosed panel. - `reconcile` returns `declared=True` and keeps the `results` it was given (`None` when none was passed). +*Placebo event study* (`event_study=True`; library choice, no paper source): +``` +recorded for CallawaySantAnna and StackedDiD candidates (not vcov_type="jackknife") +draws the scored no-effect replicates of the diagnosis +per draw results.aggregate("event_study"): coefficients b_r, reported SEs s_r +surface att = mean_r b_r + vcov = sample covariance of the b_r (ddof = 1) + se = sqrt(diag(vcov)) +per-draw record |b_rk / s_rk| for every pre-period coefficient k, kept on the surface +pre-test check for a set S of pre-periods (PreTrendsPower, the set it plans): + counted = share of draws with |b_rk / s_rk| > z_{1-alpha/2} for some k in S + assumed = that probability for b_S ~ N(0, vcov_S) with + thresholds z * sqrt(diag(vcov_S)) + agree = |counted - assumed| <= 1.96 * sqrt(assumed (1 - assumed) / R) +``` +- The surface is an `EventStudyResults` in `DesignDiagnosisResults.event_study_results[label]`, with `estimand="placebo"`, `anticipation=0`, no counts (`n` NaN, `n_kind=None`) and the provenance of the draws it averages (`source`, `base_period`, `reference_event_times`, `event_time_convention`). +- Draws are averaged only if they have the same layout: the same reference rows, the same rows with a finite coefficient and a finite positive standard error, and the same provenance. The most frequent layout is used (ties: more rows, then a fixed order); the other draws are excluded and counted. +- No surface is recorded, and one labelled warning gives the reason, when: more than 10% of the scored no-effect replicates were excluded; fewer than `2k + 1` draws remain for `k` estimated rows; the layout has no estimated row before event time 0; or the covariance is not finite or is numerically rank-deficient (smallest eigenvalue at or below `1e-10` times the largest). +- The pre-test check is made by `PreTrendsPower`, for the pre-periods it is asked to plan, from the per-draw record: planned power is reported for a set only when the check agrees (see `Note (pre-test check)`). A surface that has lost its record (rebuilt or copied field by field) cannot be checked and is refused. +- `summary()` lists, for every recorded surface, the draws used and excluded, the range of the ratio of the mean reported standard error to the placebo spread over the pre-period rows, and the counted and assumed rejection rates of the test over all pre-periods with their verdict. A diagnosis warns when that verdict is a disagreement. +- Only the no-effect cell of a `diagnose_design` call is captured: the other effect cells, the MDE search and the lock rerun fit without capturing. The cells of the diagnosis are identical with the keyword on and off. `DesignLock` is unchanged. + *Standard errors / inference:* none of its own. Each replicate uses the fitted candidate's own p-value and confidence interval; `alpha` must equal the candidate's own level. *Edge cases:* @@ -7128,6 +7155,22 @@ with data: data_sha256 fingerprint of the rows in the locked periods - **Note (lock file):** `sha256` is the SHA-256 of the lock's canonical JSON (sorted keys, no whitespace, NaN not allowed). It detects accidental edits and is not a signature. `DESIGN_LOCK_SCHEMA_VERSION` is `"1.0"`; a lock with a different major version is refused on load. - **Note (lockable configurations):** a lock must be able to rebuild the estimator exactly, so a parameter or `fit()` keyword that is not a JSON scalar, list or string-keyed mapping, or that is a non-finite number (for example `epv_threshold=inf`, or a callable `conley_metric`), is refused by `lock`. +- **Note (placebo covariance as the planned covariance):** Roth (2022) computes pre-test power from the covariance of the pre-period coefficients and calibrates it to the covariance of an estimated event study. Taking that covariance from placebo draws of a design that has not been run is a library extension with no paper source. It rests on the premise of the whole diagnosis: the spread of a candidate's estimates over placebo assignments on this panel stands in for its sampling distribution. With `resample_units=False` the spread is over assignments on the fixed panel only, and the same caveat as for the size check applies (see `Note (fixed versus resampled outcomes)`). +- **Note (surface columns):** on a placebo event study `se` is the spread of one fit's coefficient across the draws, which is what a single fit's standard error should equal. `t_stat`, `p_value` and the interval are computed from `att` and `se` with a normal reference so that the fields are mutually consistent; they compare the mean of the draws with the spread of one draw and are not inference on an effect. Error bars in a plot of the surface show that spread. +- **Note (layout rule and minimum draws):** a draw of a staggered design in which a cohort received no treated unit has other event times, and on a calendar with gaps another normalization base, than the draws with every cohort. Its provenance is part of its layout, so it can never label coefficients it did not produce. The 10% exclusion bound is the module's existing bound on lost replicates. `2k + 1` draws is the library's minimum for the sample covariance of `k` coefficients, a policy choice: full rank needs at least `k + 1` draws, and the floor asks for about twice that so that the estimate is not at the edge of singularity. The eigenvalue-based rank gate is a separate check; it catches a small panel with `resample_units=False` whose replicates contain few distinct assignments (four units with two treated have six), where every variance is positive and the matrix is singular. Every pre-period block `PreTrendsPower` can select is a principal sub-matrix of the gated matrix and is therefore not singular either. +- **Note (pre-test check):** Roth's formula assumes that each coefficient's own test rejects at its nominal level when nothing is wrong. That fails when reported standard errors are too small, too large or too noisy, as with few treated units, and the excess compounds over the coefficients a test covers. No placebo draw contains a violation, so the share of draws in which a pre-trend test rejects is a direct estimate of its no-violation rejection rate on this panel. For the pre-periods it plans, `PreTrendsPower` therefore counts how often the test it models by default (any tested coefficient individually significant at its `alpha`, normal critical value, each draw's own reported standard errors) rejected in the draws, and compares the count with the rate its formula gives at a violation of zero. Planned power is reported only when the two agree within 1.96 Monte Carlo standard errors of a rate estimated from the draws used, in both directions: a pre-test that rejects more often than assumed has power that is not meaningful, one that rejects less often has less power than planned. `fit`, `power_at` and `power_curve` raise `ValueError` with both rates otherwise; `power_by_pre_periods` leaves the row's planned numbers NaN and warns once. The check is made on the tested set, so a test of the pre-periods nearest to treatment can be planned when a test of all of them cannot. This mirrors the minimum detectable effect, which is not reported for a candidate that fails the size check; the rule has no paper source. Planned power is available for `pretest_form="nis"` only: the record holds each coefficient against its own standard error, and the joint Wald form has not been checked against placebo draws. Measured on simulated panels (`benchmarks/python/pretrend_planning_check.py`, results in `benchmarks/data/pretrend_planning_check.json`): twelve Gaussian AR(1) panels of 12 periods (40 and 200 units, a quarter treated, AR coefficient 0, 0.5 and 0.8, common and staggered adoption), `CallawaySantAnna(base_period="universal")` on all and `StackedDiD` on the common-adoption ones, 500 diagnosis replicates, tests of 2, 4 and all testable pre-periods (48 cells), and for each cell a direct check on 1,000 fresh draws in which a linear trend of the planned size is added to the placebo-treated units and the pre-test is applied with each fit's own standard errors: + + | Pre-test check | Cells | Counted minus assumed (diagnosis draws) | Power at the planned MDV, fresh draws (target 80%) | No-violation rejection, fresh draws: observed minus planned | Cells flagged | + |---|---|---|---|---|---| + | agrees | 28 (22 of the 24 at 200 units, 6 of the 24 at 40 units) | -1.9pp to +2.4pp | 73% to 84%, mean 79% | -0.4pp to +5.2pp | 0 | + | disagrees | 20 (18 at 40 units, 2 at 200 units) | +2.9pp to +21.6pp | 78% to 90%, mean 83% | +2.3pp to +21.5pp | 15 | + + A cell is flagged when the observed power at the planned MDV is more than 5pp plus two Monte Carlo standard errors from 80%, or the observed no-violation rate is more than 3pp plus two standard errors from the planned one. Every flagged cell is one the check withholds; of the five withheld cells that are not flagged, two are at 200 units, where the check is the stricter of the two rules. On the 40-unit `CallawaySantAnna` panels (10 treated units) each coefficient's own test rejected 7% to 9% of the time against a nominal 5%. The evidence is one family of simulated designs; a verdict near the threshold can differ between seeds, as for the size check. +- **Note (Monte Carlo error of the planned MDV):** the planned MDV inherits the sampling error of the placebo covariance. In the same simulation its standard deviation over 20 diagnosis seeds was 4% to 5% of its mean at 200 replicates, 3% to 4% at 500 and 2% at 1,000. +- **Note (placebo event study and the choice of estimator):** a surface is computed on the draws that were used to compare the candidates, so the planned MDV of a candidate picked from a comparison is measured on draws that informed the pick, and the lock carries no event-study content that a rerun could replace. In the simulation (two staggered points, `CallawaySantAnna` with never-treated and with not-yet-treated controls, the candidate with the higher power at an injected effect picked, 50 repetitions, planned MDV computed without the pre-test check) the picked candidate's planned MDV differed from its value in a rerun alone on a new seed by -1.7% (SE 0.7) at 40 units and +1.4% (SE 0.6) at 200: small and of no consistent sign. For planned pre-trend power the choice did not see, rerun `diagnose_design` with the chosen candidate alone and a new seed, and use that run for pre-trend planning only. The lock is still taken from the comparison diagnosis: a lock made from a single-candidate run records no comparison and no rerun. +- **Note (which candidates record a placebo event study):** `CallawaySantAnna` and `StackedDiD`, the two candidates whose `aggregate("event_study")` container `PreTrendsPower` admits. The other candidates get a warning and no surface (`SunAbraham` is admitted by `PreTrendsPower` only as a fitted results object; `TwoWayFixedEffects` has an event study only as a different fit). A candidate with `vcov_type="jackknife"` records none either: the report's pre-trend check for such a fit is Bonferroni over per-row `t(H-1)` p-values, which is not the test the formula models, and `DiagnosticReport` skips pre-trends power for it. `estimator_kwargs={"event_study": ...}` is unrelated: it remains a `fit()` keyword of a `TwoWayFixedEffects` candidate. +- **Note (what planned pre-trend power is power against):** a shift of the pre-period coefficients by `M` times the violation weights. How a trend in the treated units' outcomes maps to such a shift depends on the comparison group: with never-treated controls a linear trend of slope `gamma` relative to the reference period shifts the coefficient at event time `e` by `gamma` times its distance from the reference, while not-yet-treated controls that share the trend make the shift smaller. + **Reference implementation(s):** - None to match. The source papers run their placebo procedures on their own US state-level data with their own code, and none distributes a placebo generator (BDM: only block-bootstrap code is offered, "available upon request"; Mizushima-Powell name the Stata estimation commands they call but reference no replication code; Coglianese-Fang name no software). R `DeclareDesign` implements Blair et al.'s diagnosis on simulated data, not placebo assignment on a user's panel. There is no R parity target. - Validation is therefore internal: exact enumeration of all assignments on a six-unit panel, exact recovery of an injected effect, shared placebo draws across candidates, and the papers' qualitative findings reproduced on simulated panels (serially correlated outcomes make unclustered standard errors over-reject while unit-clustered ones are near nominal; very few treated units make asymptotic inference over-reject). The papers' own tables are not reproduced. @@ -7150,6 +7193,9 @@ with data: data_sha256 fingerprint of the rows in the locked periods - [x] The reports state the reconciliation and refuse one not made for the reported results: `tests/test_design_reconciliation_report.py` - [x] Lock rerun of a correctly sized candidate is near nominal on serially correlated data: `tests/test_methodology_design.py::TestLockRerun` - [x] The simulation numbers quoted in `Note (lock rerun)`: `TestLockRerunEvidence` (reads `benchmarks/data/design_lock_rerun.json`) +- [x] The placebo event study equals the mean and sample covariance of a by-hand loop over the same draws (both base periods, staggered timing, `StackedDiD`); only the no-effect cell is captured and no cell of the diagnosis changes: `tests/test_design_event_study.py::TestSurface` +- [x] Layout, exclusion, minimum-draw and rank rules, the per-draw record and the counted and assumed rejection rates, including provenance taken from the retained draws on a gapped calendar: `TestReduction`, `TestNotRecorded` +- [x] The simulation numbers quoted in `Note (pre-test check)`, `Note (Monte Carlo error of the planned MDV)` and `Note (placebo event study and the choice of estimator)`: `TestPlanningEvidence` (reads `benchmarks/data/pretrend_planning_check.json`) --- diff --git a/docs/methodology/REPORTING.md b/docs/methodology/REPORTING.md index b944011b..f1d0fbe1 100644 --- a/docs/methodology/REPORTING.md +++ b/docs/methodology/REPORTING.md @@ -609,6 +609,13 @@ what is reconciled. statistic; otherwise it falls back to Bonferroni over the per-row p-values (a documented conservative downgrade, not a defect). +- **Note:** Planned pre-trends power is refused. A + `PreTrendsPowerResults` computed from a placebo event study of + `diagnose_design` (`covariance_source == "placebo_draws"`) describes + a design that had not been run, not the fit being reported, so + `DiagnosticReport` and `BusinessReport` raise `ValueError` when it is + passed as `precomputed["pretrends_power"]` (on every `BusinessReport` + path, including `diagnostics=` and `auto_diagnostics=False`). - **Note:** Cluster-jackknife parallel-trends policy (same deviation by omission as `hc2_bm`). When the source fit's `vcov_type` is `"jackknife"` (`CallawaySantAnna`), the PT check does NOT run the diff --git a/docs/tutorials/34_design_diagnosis.ipynb b/docs/tutorials/34_design_diagnosis.ipynb index 4097af09..fe4a39d9 100644 --- a/docs/tutorials/34_design_diagnosis.ipynb +++ b/docs/tutorials/34_design_diagnosis.ipynb @@ -21,6 +21,8 @@ " your own untreated history, and reports each one's size and power.\n", "- `DesignDiagnosisResults.lock` records the estimator you choose as a\n", " `DesignLock`, a small JSON file.\n", + "- `PreTrendsPower` on the diagnosis says how large a diverging trend the\n", + " pre-trend check of the planned design would catch.\n", "- `DesignLock.fit` fits the locked analysis once the study has run and checks it\n", " against the lock.\n", "- `BusinessReport(..., design_reconciliation=...)` states the result of that\n", @@ -140,6 +142,7 @@ " CallawaySantAnna,\n", " DesignLock,\n", " ImputationDiD,\n", + " PreTrendsPower,\n", " TwoWayFixedEffects,\n", " diagnose_design,\n", ")\n", @@ -343,7 +346,7 @@ "The size check allows for Monte Carlo noise: with 200 replicates a correctly\n", "sized test can easily show 6% or 7%, so the threshold is the nominal level plus\n", "1.96 Monte Carlo standard errors, **8.0%** here. `cs` passes at 7.0%, which is\n", - "closer to the threshold than `twfe` or `imp`. Section 9 comes back to what that\n", + "closer to the threshold than `twfe` or `imp`. Section 10 comes back to what that\n", "does and does not tell you.\n", "\n", "**What the size check does not cover.** Placebo treatment is assigned at random,\n", @@ -466,9 +469,145 @@ "that you wrote it before you saw the outcomes. That evidence has to come from\n", "outside: commit the file to version control, attach it to a pre-analysis plan,\n", "or send it to a colleague before the rollout starts. The timestamp of that act\n", - "is what shows the design was fixed in advance.\n", + "is what shows the design was fixed in advance." + ] + }, + { + "cell_type": "markdown", + "id": "e2f7f490", + "metadata": {}, + "source": [ + "## 5. Plan the pre-trend check\n", "\n", - "## 5. Six months later\n", + "After the rollout you will look at the event study and ask whether the treated\n", + "and comparison stores were on the same path *before* treatment. A check that\n", + "finds nothing is only reassuring if it could have found something. For a fitted\n", + "event study `PreTrendsPower` answers that (tutorial `07_pretrends_power`). With\n", + "`event_study=True`, `diagnose_design` lets you ask it now, before any outcome\n", + "exists: it keeps the event study of every placebo fit, and `PreTrendsPower`\n", + "reads the spread of those coefficients.\n", + "\n", + "Two choices in the next cell:\n", + "\n", + "- **One estimator, a new seed.** `cs` was picked from a comparison, so its\n", + " numbers in that run owe something to luck. For the pre-trend plan, rerun the\n", + " chosen estimator alone with new draws. The lock still comes from the\n", + " comparison run above.\n", + "- **`base_period=\"universal\"`.** A pre-trend check compares every earlier month\n", + " with the month just before treatment, and that is what this option estimates.\n", + " With the default, the pre-period coefficients are month-to-month changes\n", + " instead. The post-period estimates are the same either way." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "6c278aaf", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " n_pre_periods mdv power_no_violation placebo_rejection_rate\n", + " 1 0.616 0.050 0.056\n", + " 2 0.357 0.084 0.092\n", + " 3 NaN 0.111 0.152\n", + " 4 NaN 0.125 0.176\n", + " 5 NaN 0.139 0.196\n", + " 6 NaN 0.155 0.208\n", + " 7 NaN 0.165 0.216\n", + " 8 NaN 0.177 0.230\n", + "\n", + "Warning: [cs] a pre-trend test over all 17 pre-periods (any coefficient individually\n", + "significant at 0.05) rejected 29.6% of the 500 no-effect replicates, against 25.0%\n", + "assumed by the pre-trend power formula. PreTrendsPower repeats this comparison for the\n", + "pre-periods it plans and reports planned power only where the two agree; a test of fewer\n", + "pre-periods may still agree (see PreTrendsPower.power_by_pre_periods).\n", + "\n", + "Warning: Planned pre-trend power is not reported for tests of [3, 4, 5, 6, 7, 8, 9, 10,\n", + "11, 12, 13, 14, 15, 16, 17] pre-period(s): in the placebo draws those tests rejected,\n", + "with no violation, at a rate that differs from the one the power formula assumes by more\n", + "than Monte Carlo error (columns placebo_rejection_rate and power_no_violation).\n" + ] + } + ], + "source": [ + "import textwrap\n", + "import warnings\n", + "\n", + "with warnings.catch_warnings(record=True) as caught: # collect the warnings to print them below\n", + " warnings.simplefilter(\"always\")\n", + " plan = diagnose_design(\n", + " history,\n", + " outcome=\"sales\",\n", + " unit=\"store\",\n", + " time=\"month\",\n", + " estimators={\"cs\": CallawaySantAnna(base_period=\"universal\")},\n", + " cohort_periods=[19],\n", + " n_treated=N_TREATED,\n", + " n_simulations=500,\n", + " seed=SEED + 2, # new draws: not the ones that informed the choice\n", + " event_study=True, # keep each placebo fit's event study\n", + " progress=False,\n", + " )\n", + " by_pre_periods = PreTrendsPower().power_by_pre_periods(plan)\n", + "\n", + "columns = [\"n_pre_periods\", \"mdv\", \"power_no_violation\", \"placebo_rejection_rate\"]\n", + "print(by_pre_periods[columns].head(8).round(3).to_string(index=False))\n", + "for warning in caught:\n", + " print()\n", + " print(textwrap.fill(\"Warning: \" + str(warning.message), width=88))" + ] + }, + { + "cell_type": "markdown", + "id": "9efc1f18", + "metadata": {}, + "source": [ + "**Read the table row by row.** Each row is a pre-trend check over the months\n", + "closest to the rollout: the last one, the last two, and so on.\n", + "\n", + "- `power_no_violation` is how often the power formula says that check raises a\n", + " false alarm, that is, rejects although nothing is wrong. It grows with the\n", + " number of months because the check fires when any single coefficient is\n", + " significant: **8.4%** for two months.\n", + "- `placebo_rejection_rate` is the same rate counted in the 500 placebo draws,\n", + " none of which contains a violation: **9.2%** for two months.\n", + "- `mdv` is the smallest divergence the check would catch 80% of the time, in\n", + " sales-index points per month: **0.357** when two months are tested. A smaller\n", + " divergence is caught less than 80% of the time, and less often the smaller it\n", + " is.\n", + "\n", + "**Blank rows are deliberate.** The formula behind `mdv` assumes that each\n", + "coefficient's own test rejects 5% of the time when nothing is wrong. The placebo\n", + "draws show whether that holds on your panel. For checks over three or more\n", + "months it does not: the three-month check rejected **15.2%** of the time in the\n", + "draws against **11.1%** assumed. A planned number for such a check would describe\n", + "a better-behaved test than the one you would run, so none is given. That is what\n", + "the two warnings printed under the table say: one for the check over all 17 pre-period months, one\n", + "listing the rows left blank.\n", + "\n", + "The comparison allows for Monte Carlo noise, so a row near the line can come out\n", + "differently with another seed, and more replicates make it stricter. With 2,000\n", + "replicates every row of this table is blank: with 25 treated stores each\n", + "coefficient's own test rejects about 6% of the time, not 5%, and with enough\n", + "draws that shows even for a single month. On a panel this size, read the\n", + "pre-trend check with that in mind.\n", + "\n", + "**A pre-trend check that does not reject is not evidence that parallel trends\n", + "holds.** This plan tells you how large a divergence it could miss. Tutorial\n", + "`07_pretrends_power` covers the same question for a fitted event study, and\n", + "tutorial `05_honest_did` shows how the conclusion changes if parallel trends is\n", + "violated by a given amount." + ] + }, + { + "cell_type": "markdown", + "id": "a865fea9", + "metadata": {}, + "source": [ + "## 6. Six months later\n", "\n", "The rollout happened. The analysis panel is the 24 months of history followed by\n", "six new months, with the layout live in 25 stores from month 25. We simulate a\n", @@ -485,7 +624,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 7, "id": "43ea0a53", "metadata": {}, "outputs": [ @@ -517,7 +656,7 @@ "id": "749b9d81", "metadata": {}, "source": [ - "## 6. Fit the locked analysis\n", + "## 7. Fit the locked analysis\n", "\n", "`lock.fit` builds the locked estimator, fits it with the locked outcome, unit\n", "and time columns, and checks the result against the lock on the same data. You\n", @@ -527,7 +666,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 8, "id": "f31cf052", "metadata": {}, "outputs": [ @@ -577,7 +716,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 9, "id": "3682d50b", "metadata": {}, "outputs": [ @@ -613,7 +752,7 @@ "interpret, and to explain to others, when the power calculation was done on your\n", "own data before the study and is on file.\n", "\n", - "## 7. Report it\n", + "## 8. Report it\n", "\n", "Pass the reconciliation to `BusinessReport` (or `DiagnosticReport`) as\n", "`design_reconciliation=`. The report then says, next to the estimate, how the\n", @@ -622,7 +761,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 10, "id": "fd29e446", "metadata": {}, "outputs": [ @@ -647,7 +786,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 11, "id": "3a65d1cd", "metadata": {}, "outputs": [ @@ -688,7 +827,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 12, "id": "c2708cca", "metadata": {}, "outputs": [ @@ -707,7 +846,7 @@ " 'not_checked': []}" ] }, - "execution_count": 11, + "execution_count": 12, "metadata": {}, "output_type": "execute_result" } @@ -721,7 +860,7 @@ "id": "a16ee6a3", "metadata": {}, "source": [ - "## 8. When the analysis is not the planned one\n", + "## 9. When the analysis is not the planned one\n", "\n", "**A different realized design.** Suppose you had been asked for a readout after\n", "four months instead of six. The estimator is still the locked one, but the study\n", @@ -731,7 +870,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 13, "id": "86b06596", "metadata": {}, "outputs": [ @@ -784,7 +923,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 14, "id": "ebd02086", "metadata": {}, "outputs": [ @@ -824,7 +963,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 15, "id": "a6971b09", "metadata": {}, "outputs": [ @@ -876,7 +1015,7 @@ "id": "3dba6529", "metadata": {}, "source": [ - "## 9. What this does and does not give you\n", + "## 10. What this does and does not give you\n", "\n", "**The rerun removes one source of optimism, not all of it.** Choosing the best\n", "candidate overstates its power for two reasons: luck in the placebo draws, and\n", @@ -917,6 +1056,7 @@ "| Diagnose | `diagnose_design(history, ...)` | Size, power and MDE of each candidate on your own untreated panel |\n", "| Lock | `result.lock(label, data=history)` | A `DesignLock`: the chosen estimator, its configuration and a rerun of its diagnosis |\n", "| Register | `lock.to_json()` | A file to commit or send before the study starts |\n", + "| Plan the pre-trend check | `PreTrendsPower().power_by_pre_periods(diagnose_design(..., event_study=True))` | How large a diverging trend the planned pre-trend check would catch, by number of months tested |\n", "| Analyse | `lock.fit(analysis, first_treat=...)` | The estimate (`.results`) and its status against the lock (`match` / `deviates`) |\n", "| Report | `BusinessReport(check.results, design_reconciliation=check)` | The estimate with the reconciliation stated next to it |\n", "\n", diff --git a/tests/test_design_event_study.py b/tests/test_design_event_study.py new file mode 100644 index 00000000..94f100b0 --- /dev/null +++ b/tests/test_design_event_study.py @@ -0,0 +1,1119 @@ +"""Placebo event studies in ``diagnose_design`` and planned pre-trend power. + +``diagnose_design(..., event_study=True)`` records, per candidate, the mean and +the covariance across the no-effect placebo draws of its event-study +coefficients. ``PreTrendsPower`` reads that record to plan pre-trend power for +a design that has not been run. + +Numerical note: the default NIS pre-test integrates a multivariate normal with +a randomized routine, so two calls agree only to about 1e-5. Exact checks are +made on the Wald form and on deterministic inputs; NIS values are compared at +``NIS_ATOL``. +""" + +import pickle +import warnings + +import numpy as np +import pandas as pd +import pytest + +from diff_diff import ( + BusinessReport, + CallawaySantAnna, + DiagnosticReport, + HonestDiD, + ImputationDiD, + PreTrendsPower, + StackedDiD, + TwoWayFixedEffects, + compute_mdv, + compute_pretrends_power, + diagnose_design, +) +from diff_diff import design as design_module +from diff_diff.results_base import EventStudyResults +from diff_diff.utils import safe_inference + +NIS_ATOL = 1e-3 + + +def _panel(n_units=40, periods=range(1, 9), seed=0, rho=0.5): + """An untreated panel with unit effects, a common trend and AR(1) errors.""" + rng = np.random.default_rng(seed) + periods = list(periods) + rows = [] + for i in range(n_units): + unit_effect = rng.normal() + error = rng.normal() + for t in periods: + error = rho * error + rng.normal() + rows.append((i, t, unit_effect + 0.1 * t + error)) + return pd.DataFrame(rows, columns=["id", "t", "y"]) + + +def _diagnose(panel, estimators, cohorts=(6,), n_simulations=40, seed=1, quiet=True, **kwargs): + kwargs.setdefault("event_study", True) + if "n_treated" not in kwargs: + kwargs.setdefault("treatment_fraction", 0.25) + call = dict( + outcome="y", + unit="id", + time="t", + estimators=estimators, + cohort_periods=list(cohorts), + n_simulations=n_simulations, + seed=seed, + progress=False, + **kwargs, + ) + if not quiet: + return diagnose_design(panel, **call) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return diagnose_design(panel, **call) + + +def _messages(recorded): + return [str(w.message) for w in recorded] + + +@pytest.fixture(scope="module") +def panel(): + return _panel() + + +@pytest.fixture(scope="module") +def cs_diagnosis(panel): + return _diagnose(panel, [CallawaySantAnna(base_period="universal")]) + + +@pytest.fixture(scope="module") +def cs_surface(cs_diagnosis): + return cs_diagnosis.event_study_results["CallawaySantAnna"] + + +def _independent_surface(n_pre=4, se=0.5, inflate=(), n_draws=4000, seed=0): + """A hand-built placebo surface with independent pre-period coefficients. + + Its per-draw record holds standard normal ratios, so the pre-trend test + over any ``K`` of them rejects at ``1 - 0.95^K`` as the formula assumes. + Columns listed in ``inflate`` (positions among the pre-periods, earliest + first) get ratios 1.5 times too large: tests that include them reject + more often than assumed. + """ + event_time = np.arange(-n_pre - 1, 2) + is_reference = event_time == -1 + k = int((~is_reference).sum()) + ses = np.where(is_reference, np.nan, se) + surface = EventStudyResults( + event_time=event_time, + att=np.zeros(len(event_time)), + se=ses, + t_stat=np.where(is_reference, np.nan, 0.0), + p_value=np.where(is_reference, np.nan, 1.0), + conf_int_lower=np.where(is_reference, np.nan, -1.96 * se), + conf_int_upper=np.where(is_reference, np.nan, 1.96 * se), + is_reference=is_reference, + n=np.full(len(event_time), np.nan), + vcov=np.eye(k) * se**2, + vcov_index=event_time[~is_reference], + source="CallawaySantAnnaResults", + base_period="universal", + anticipation=0, + reference_event_times=(-1,), + estimand=design_module.PLACEBO_ESTIMAND, + ) + ratios = np.abs(np.random.default_rng(seed).normal(size=(n_draws, n_pre))) + for column in inflate: + ratios[:, column] *= 1.5 + labels = event_time[event_time < -1].tolist() + setattr(surface, design_module._PRETEST_RECORD, {"labels": labels, "abs_t": ratios}) + return surface + + +# --------------------------------------------------------------------------- +# The recorded surface +# --------------------------------------------------------------------------- + + +class TestSurface: + """The surface is the mean and sample covariance of the per-draw event studies.""" + + @pytest.mark.parametrize( + "estimator, cohorts", + [ + (CallawaySantAnna(base_period="universal"), (6,)), + (CallawaySantAnna(), (6,)), + (CallawaySantAnna(base_period="universal"), (5, 7)), + (StackedDiD(kappa_pre=3, kappa_post=1), (6,)), + ], + ids=["cs-universal", "cs-varying", "cs-staggered", "stacked"], + ) + def test_equals_hand_loop(self, panel, estimator, cohorts): + n_simulations, seed = 40, 7 + diagnosis = _diagnose(panel, [estimator], cohorts, n_simulations, seed) + label = type(estimator).__name__ + surface = diagnosis.event_study_results[label] + assert diagnosis._event_study_checks[label]["n_excluded"] == 0 + + generator = design_module._make_placebo_generator( + panel, "y", "id", "t", 10, list(cohorts), True + ) + fit_kwargs = design_module._fit_kwargs(estimator, "y", "id", "t", {}) + draws, reported, first = [], [], None + for replicate_seed in design_module._replicate_seeds(seed, n_simulations): + frame = generator(treatment_effect=0.0, seed=replicate_seed) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fitted = design_module._clone(estimator).fit(frame, **fit_kwargs) + one = fitted.aggregate("event_study") + first = one if first is None else first + np.testing.assert_array_equal(one.event_time, first.event_time) + draws.append(one.att[~one.is_reference]) + reported.append(one.se[~one.is_reference]) + draws = np.vstack(draws) + + np.testing.assert_array_equal(surface.event_time, first.event_time) + np.testing.assert_array_equal(surface.is_reference, first.is_reference) + estimated = ~surface.is_reference + np.testing.assert_allclose(surface.att[estimated], draws.mean(axis=0), rtol=1e-12) + expected_vcov = np.atleast_2d(np.cov(draws, rowvar=False, ddof=1)) + np.testing.assert_allclose(surface.vcov, expected_vcov, rtol=1e-12, atol=1e-14) + np.testing.assert_allclose( + surface.se[estimated], np.sqrt(np.diag(expected_vcov)), rtol=1e-12 + ) + np.testing.assert_array_equal(surface.vcov_index, first.event_time[~first.is_reference]) + assert surface.source == first.source + assert surface.base_period == first.base_period + assert surface.event_time_convention == first.event_time_convention + expected_refs = ( + None + if first.reference_event_times is None + else tuple(int(v) for v in first.reference_event_times) + ) + assert surface.reference_event_times == expected_refs + assert surface.estimand == "placebo" + assert surface.anticipation == 0 + assert surface.n_kind is None + assert np.all(np.isnan(surface.n)) + assert surface.alpha == diagnosis.alpha + + # The calibration record: mean reported SE over the placebo spread. + pre = first.event_time[~first.is_reference] < 0 + expected_ratio = ( + np.vstack(reported).mean(axis=0)[pre] / np.sqrt(np.diag(expected_vcov))[pre] + ) + ratios = diagnosis._event_study_checks[label]["se_ratio"] + np.testing.assert_allclose(list(ratios.values()), expected_ratio, rtol=1e-12) + assert list(ratios) == first.event_time[~first.is_reference][pre].tolist() + + # The pre-trend test counted in the draws, with each draw's own SEs. + reported = np.vstack(reported) + rejected = np.any(np.abs(draws[:, pre] / reported[:, pre]) > 1.959963984540054, axis=1) + checks = diagnosis._event_study_checks[label] + assert checks["pretest_rejection_rate"] == pytest.approx(rejected.mean(), abs=1e-12) + pre_labels = first.event_time[~first.is_reference][pre].tolist() + record = getattr(surface, design_module._PRETEST_RECORD) + assert record["labels"] == pre_labels + np.testing.assert_allclose( + record["abs_t"], np.abs(draws[:, pre] / reported[:, pre]), rtol=1e-12 + ) + expected_rate = design_module._formula_pretest_rate(expected_vcov[np.ix_(pre, pre)], 0.05) + assert checks["pretest_expected_rate"] == pytest.approx(expected_rate, abs=NIS_ATOL) + assert checks["pretest_agrees"] is design_module._pretest_size_ok( + checks["pretest_rejection_rate"], checks["pretest_expected_rate"], n_simulations + ) + assert (checks["n_pre"], checks["n_post"]) == (int(pre.sum()), int((~pre).sum())) + + def test_inference_columns_follow_from_mean_and_spread(self, cs_surface): + for i in range(len(cs_surface.event_time)): + if cs_surface.is_reference[i]: + assert cs_surface.att[i] == 0.0 + assert np.isnan(cs_surface.se[i]) and np.isnan(cs_surface.p_value[i]) + continue + t_stat, p_value, conf_int = safe_inference( + float(cs_surface.att[i]), float(cs_surface.se[i]), alpha=cs_surface.alpha + ) + assert cs_surface.t_stat[i] == pytest.approx(t_stat) + assert cs_surface.p_value[i] == pytest.approx(p_value) + assert cs_surface.conf_int_lower[i] == pytest.approx(conf_int[0]) + assert cs_surface.conf_int_upper[i] == pytest.approx(conf_int[1]) + + def test_summary_labels_the_column_placebo(self, cs_surface): + text = cs_surface.summary() + assert "estimand: placebo" in text + assert "placebo" in text.splitlines()[4] + assert set(cs_surface.to_dataframe()["estimand"]) == {"placebo"} + + def test_keyword_does_not_change_any_cell(self, panel): + estimators = [CallawaySantAnna(base_period="universal"), StackedDiD(kappa_pre=3)] + off = _diagnose(panel, estimators, seed=11, event_study=False, effect_sizes=[0.5]) + on = _diagnose(panel, estimators, seed=11, effect_sizes=[0.5]) + pd.testing.assert_frame_equal(off.to_dataframe(), on.to_dataframe()) + assert off.event_study is False and off.event_study_results == {} + assert on.event_study is True and set(on.event_study_results) == { + "CallawaySantAnna", + "StackedDiD", + } + assert "Placebo event studies" not in off.summary() + assert "Placebo event studies" in on.summary() + assert off.to_dict()["event_study"] is False + assert on.to_dict()["event_study"] is True + stripped = {k: v for k, v in on.to_dict().items() if k != "event_study"} + assert set(stripped) == set(off.to_dict()) - {"event_study"} + + def test_only_the_no_effect_cell_is_captured(self, panel): + estimator = CallawaySantAnna(base_period="universal") + plain = _diagnose(panel, [estimator]) + searched = _diagnose(panel, [estimator], effect_sizes=[0.4, 0.8], power=0.8) + label = "CallawaySantAnna" + assert searched.mde_results, "the MDE search must have run for this check to bind" + checks = searched._event_study_checks[label] + assert checks["n_draws"] == searched.results[label][0].n_simulations + reference = plain._event_study_checks[label] + for key in ("n_draws", "n_excluded", "se_ratio", "pretest_rejection_rate"): + assert checks[key] == reference[key], key + np.testing.assert_array_equal( + searched.event_study_results[label].vcov, plain.event_study_results[label].vcov + ) + np.testing.assert_array_equal( + searched.event_study_results[label].att, plain.event_study_results[label].att + ) + + def test_summary_block(self, cs_diagnosis): + text = cs_diagnosis.summary() + assert "Placebo event studies (no-effect runs)" in text + row = [line for line in text.splitlines() if line.startswith("CallawaySantAnna")][-1] + checks = cs_diagnosis._event_study_checks["CallawaySantAnna"] + verdict = "yes" if checks["pretest_agrees"] else "NO" + assert str(checks["n_draws"]) in row and row.rstrip().endswith(verdict) + assert f"{checks['pretest_rejection_rate']:.1%}" in row + assert f"{checks['pretest_expected_rate']:.1%}" in row + + +# --------------------------------------------------------------------------- +# Reduction rules +# --------------------------------------------------------------------------- + + +def _record(event_times, references, values, ses=None, refs=(-1,), base="universal"): + rows = tuple((int(e), bool(r)) for e, r in zip(event_times, references)) + provenance = ("CallawaySantAnnaResults", base, refs, "e0_first_treated") + values = np.asarray(values, dtype=float) + ses = np.ones_like(values) if ses is None else np.asarray(ses, dtype=float) + return (rows, provenance), values, ses + + +class TestReduction: + """``_placebo_event_study``: which draws are averaged and when nothing is reported.""" + + def _draws(self, n, k=3, seed=0): + return np.random.default_rng(seed).normal(size=(n, k)) + + def test_provenance_comes_from_the_retained_draws(self): + """A draw with another layout never lends its provenance, even when first.""" + odd = _record([-2, -1, 0], [False, True, False], [0.1, 0.2], refs=(-1,)) + main = [ + _record([-3, -2, -1, 0], [False, False, True, False], row, refs=(-2, -1)) + for row in self._draws(30) + ] + surface, checks, reason = design_module._placebo_event_study( + CallawaySantAnna(), [odd] + main, 0.05 + ) + assert reason is None + assert surface.reference_event_times == (-2, -1) + assert surface.event_time.tolist() == [-3, -2, -1, 0] + assert checks["n_draws"] == 30 and checks["n_excluded"] == 1 + + def test_failed_aggregations_count_as_excluded(self): + main = [_record([-2, -1, 0], [False, True, False], row) for row in self._draws(30, k=2)] + surface, checks, _ = design_module._placebo_event_study( + CallawaySantAnna(), main + [None, None], 0.05 + ) + assert surface is not None and checks["n_excluded"] == 2 + + @pytest.mark.parametrize("records", [[], [None, None, None]], ids=["empty", "all-failed"]) + def test_nothing_captured(self, records): + surface, checks, reason = design_module._placebo_event_study( + CallawaySantAnna(), records, 0.05 + ) + assert surface is None and checks is None + assert "no no-effect replicate produced an event study" in reason + + def test_more_than_ten_percent_excluded(self): + main = [_record([-2, -1, 0], [False, True, False], row) for row in self._draws(30, k=2)] + other = [_record([-1, 0], [True, False], [0.1]) for _ in range(5)] + surface, _, reason = design_module._placebo_event_study( + CallawaySantAnna(), main + other, 0.05 + ) + assert surface is None and "5 of 35" in reason + + def test_tied_layouts_are_not_reported(self): + a = [_record([-2, -1, 0], [False, True, False], row) for row in self._draws(10, k=2)] + b = [_record([-3, -1, 0], [False, True, False], row) for row in self._draws(10, k=2)] + first = design_module._placebo_event_study(CallawaySantAnna(), a + b, 0.05) + second = design_module._placebo_event_study(CallawaySantAnna(), b + a, 0.05) + assert first[0] is None and second[0] is None + assert first[2] == second[2] + + def test_too_few_draws(self): + records = [ + _record([-3, -2, -1, 0], [False, False, True, False], row) for row in self._draws(6) + ] + surface, _, reason = design_module._placebo_event_study(CallawaySantAnna(), records, 0.05) + assert surface is None + assert "6 replicates are too few" in reason and "at least 7" in reason + + def test_no_pre_period(self): + records = [_record([-1, 0, 1], [True, False, False], row) for row in self._draws(30, k=2)] + for estimator, hint in ((StackedDiD(), True), (CallawaySantAnna(), False)): + surface, _, reason = design_module._placebo_event_study(estimator, records, 0.05) + assert surface is None and "no estimated pre-treatment period" in reason + assert ("kappa_pre" in reason) is hint + + def test_rank_deficient_covariance(self): + """Few distinct draws: positive variances, rank below the number of rows.""" + distinct = self._draws(3, k=5) + distinct = np.vstack([distinct, -distinct]) + rows = distinct[np.random.default_rng(1).integers(0, 6, size=100)] + assert np.all(rows.var(axis=0) > 0) + assert np.linalg.matrix_rank(np.cov(rows, rowvar=False)) < 5 + records = [ + _record([-4, -3, -2, -1, 0, 1], [False, False, False, True, False, False], row) + for row in rows + ] + surface, _, reason = design_module._placebo_event_study(CallawaySantAnna(), records, 0.05) + assert surface is None and "rank-deficient" in reason + + def test_pretest_record_and_rates(self): + """Counted rate = share of draws with any |coefficient / own SE| above z.""" + rng = np.random.default_rng(3) + values = rng.normal(size=(200, 3)) + records = [ + _record([-3, -2, -1, 0], [False, False, True, False], v, ses=np.ones(3)) for v in values + ] + surface, checks, reason = design_module._placebo_event_study( + CallawaySantAnna(), records, 0.05 + ) + assert surface is not None and reason is None + z = 1.959963984540054 + assert checks["pretest_rejection_rate"] == pytest.approx( + np.mean(np.any(np.abs(values[:, :2]) > z, axis=1)), abs=1e-12 + ) + assert checks["pretest_expected_rate"] == pytest.approx( + design_module._formula_pretest_rate(surface.vcov[:2, :2], 0.05), abs=NIS_ATOL + ) + # The same count for a subset, and at another level. + counted, n_draws = design_module.placebo_pretest_rate(surface, [-2], 0.10) + assert n_draws == 200 + assert counted == pytest.approx(np.mean(np.abs(values[:, 1]) > 1.6448536269514722)) + with pytest.raises(ValueError, match="not in this placebo event study"): + design_module.placebo_pretest_rate(surface, [-9], 0.05) + + @pytest.mark.parametrize("scale, direction", [(0.6, "more"), (1.8, "less")]) + def test_full_set_verdict_in_both_directions(self, scale, direction): + """Reported SEs too small (test over-rejects) or too large (under-rejects).""" + values = np.random.default_rng(4).normal(size=(400, 3)) + records = [ + _record([-3, -2, -1, 0], [False, False, True, False], v, ses=np.full(3, scale)) + for v in values + ] + surface, checks, reason = design_module._placebo_event_study( + CallawaySantAnna(), records, 0.05 + ) + assert surface is not None and reason is None + assert checks["pretest_agrees"] is False + gap = checks["pretest_rejection_rate"] - checks["pretest_expected_rate"] + assert (gap > 0) is (direction == "more") + + def test_formula_pretest_rate(self): + """Independent coefficients: 1 - 0.95^K; correlated ones reject less often.""" + for k in (1, 3, 6): + rate = design_module._formula_pretest_rate(np.eye(k) * 0.3, 0.05) + assert rate == pytest.approx(1.0 - 0.95**k, abs=NIS_ATOL) + correlated = np.full((4, 4), 0.9) + 0.1 * np.eye(4) + assert design_module._formula_pretest_rate(correlated, 0.05) < 1.0 - 0.95**4 - 0.03 + + def test_pretest_check_tolerance(self): + """Agreement within 1.96 Monte Carlo standard errors at the expected rate.""" + tolerance = 1.96 * np.sqrt(0.2 * 0.8 / 500) + assert design_module._pretest_size_ok(0.2 + 0.99 * tolerance, 0.2, 500) + assert not design_module._pretest_size_ok(0.2 + 1.01 * tolerance, 0.2, 500) + assert design_module._pretest_size_ok(0.2 - 0.99 * tolerance, 0.2, 500) + assert not design_module._pretest_size_ok(0.2 - 1.01 * tolerance, 0.2, 500) + assert not design_module._pretest_size_ok(float("nan"), 0.2, 500) + assert not design_module._pretest_size_ok(0.2, 0.2, 0) + + +class TestNotRecorded: + """End-to-end: the cases in which a candidate gets no surface, and says why.""" + + def _run(self, panel, estimators, **kwargs): + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always") + diagnosis = _diagnose(panel, estimators, quiet=False, **kwargs) + return diagnosis, _messages(recorded) + + def test_non_bool_keyword(self, panel): + with pytest.raises(ValueError, match="event_study must be True or False"): + _diagnose(panel, [CallawaySantAnna()], event_study="yes") + + def test_unsupported_class(self, panel): + diagnosis, messages = self._run( + panel, [ImputationDiD(), CallawaySantAnna(base_period="universal")] + ) + assert list(diagnosis.event_study_results) == ["CallawaySantAnna"] + assert any( + "[ImputationDiD] no placebo event study is recorded" in m + and "not an input PreTrendsPower accepts" in m + for m in messages + ) + + def test_jackknife_candidate(self): + diagnosis, messages = self._run( + _panel(20), [CallawaySantAnna(vcov_type="jackknife")], n_simulations=6 + ) + assert diagnosis.event_study_results == {} + assert any("cluster-jackknife" in m and "Bonferroni" in m for m in messages) + + def test_stacked_without_pre_window(self, panel): + diagnosis, messages = self._run(panel, [StackedDiD()]) + assert diagnosis.event_study_results == {} + assert any("kappa_pre" in m for m in messages) + + def test_too_few_replicates(self, panel): + diagnosis, messages = self._run( + panel, [CallawaySantAnna(base_period="universal")], n_simulations=8 + ) + assert diagnosis.event_study_results == {} + assert any("too few for the covariance" in m for m in messages) + + def test_rank_deficient_on_a_small_fixed_panel(self): + """Four units, two treated, no resampling: six distinct placebo assignments.""" + diagnosis, messages = self._run( + _panel(4), + [CallawaySantAnna(base_period="universal")], + n_simulations=100, + n_treated=2, + resample_units=False, + ) + assert diagnosis.event_study_results == {} + assert any("rank-deficient" in m and "resample_units=False" in m for m in messages) + + def test_rare_cohort_excludes_too_many_draws(self, panel): + """Three treated units over two cohorts: a quarter of the draws lose a cohort.""" + diagnosis, messages = self._run( + panel, + [CallawaySantAnna(base_period="universal")], + cohorts=(5, 7), + n_simulations=60, + n_treated=3, + ) + assert diagnosis.event_study_results == {} + assert any("different event-study layout" in m for m in messages) + + def test_gapped_grid_keeps_its_own_provenance(self): + """A universal-base design on a gapped grid: the surface records both bases. + + The first scored draw loses a cohort (a single base). The surface is + built from the draws with both cohorts, records their two bases, and + ``PreTrendsPower`` refuses it with its common-reference guard. + """ + gapped = _panel(40, periods=[1, 2, 3, 4, 6]) + seed = 33 + generator = design_module._make_placebo_generator(gapped, "y", "id", "t", 6, [3, 6], True) + first = generator(treatment_effect=0.0, seed=design_module._replicate_seeds(seed, 1)[0]) + cohorts_in_first = first.loc[first["_placebo_first_treat"] > 0, "_placebo_first_treat"] + assert cohorts_in_first.nunique() == 1, "precondition: the first draw loses a cohort" + + diagnosis, _ = self._run( + gapped, + [CallawaySantAnna(base_period="universal")], + cohorts=(3, 6), + n_simulations=60, + seed=seed, + n_treated=6, + ) + surface = diagnosis.event_study_results["CallawaySantAnna"] + assert diagnosis._event_study_checks["CallawaySantAnna"]["n_excluded"] >= 1 + assert surface.reference_event_times == (-2, -1) + with pytest.raises(ValueError, match="one common reference period"): + PreTrendsPower().fit(surface) + + def test_full_pretest_that_over_rejects_warns(self): + """Four treated units of forty: the test over all pre-periods rejects too often.""" + diagnosis, messages = self._run( + _panel(40), + [CallawaySantAnna(base_period="universal")], + n_simulations=200, + seed=3, + n_treated=4, + ) + checks = diagnosis._event_study_checks["CallawaySantAnna"] + assert "CallawaySantAnna" in diagnosis.event_study_results + assert checks["pretest_agrees"] is False + assert checks["pretest_rejection_rate"] > checks["pretest_expected_rate"] + assert any( + "a pre-trend test over all 4 pre-periods" in m + and f"{checks['pretest_rejection_rate']:.1%}" in m + and f"{checks['pretest_expected_rate']:.1%}" in m + for m in messages + ) + row = [ + line for line in diagnosis.summary().splitlines() if line.startswith("CallawaySantAnna") + ][-1] + assert row.rstrip().endswith("NO") + with pytest.raises(ValueError, match="Planned pre-trend power is not reported"): + PreTrendsPower().fit(diagnosis) + + def test_size_not_controlled_warns_at_diagnosis(self, panel, monkeypatch): + monkeypatch.setattr(design_module, "_size_controlled", lambda *args: False) + diagnosis, messages = self._run(panel, [CallawaySantAnna(base_period="universal")]) + assert "CallawaySantAnna" in diagnosis.event_study_results + assert any("did not pass the size check" in m for m in messages) + + def test_twfe_fit_keyword_of_the_same_name_still_works(self, panel): + """``estimator_kwargs={"event_study": False}`` stays a TWFE fit keyword.""" + for flag in (False, True): + diagnosis = _diagnose( + panel, + [TwoWayFixedEffects()], + event_study=flag, + estimator_kwargs={"event_study": False}, + ) + assert diagnosis.results["TwoWayFixedEffects"][0].n_simulations == 40 + assert diagnosis.event_study_results == {} + + +# --------------------------------------------------------------------------- +# PreTrendsPower on a planned design +# --------------------------------------------------------------------------- + + +class TestPlannedPower: + """``PreTrendsPower`` on a diagnosis or one of its placebo event studies (NIS form).""" + + def test_diagnosis_and_surface_give_the_same_result(self, cs_diagnosis, cs_surface): + planner = PreTrendsPower() + from_diagnosis = planner.fit(cs_diagnosis) + from_surface = planner.fit(cs_surface) + assert from_diagnosis.mdv == pytest.approx(from_surface.mdv, rel=5e-3) + assert from_diagnosis.covariance_source == "placebo_draws" + assert from_diagnosis.original_results is cs_surface + assert from_diagnosis.n_pre_periods == 4 + np.testing.assert_array_equal(from_diagnosis.vcov, from_surface.vcov) + + def test_equals_hand_computation(self, cs_surface): + pre = [-5, -4, -3, -2] + index = cs_surface.vcov_index.tolist() + rows = [index.index(label) for label in pre] + block = cs_surface.vcov[np.ix_(rows, rows)] + weights = np.abs(np.asarray(pre, dtype=float) - (-1.0)) + + planner = PreTrendsPower() + fitted = planner.fit(cs_surface) + np.testing.assert_array_equal(fitted.violation_weights, weights) + np.testing.assert_allclose(fitted.vcov, block, rtol=1e-12) + assert fitted.mdv == pytest.approx(planner._compute_mdv_nis(weights, block), rel=5e-3) + assert fitted.power == pytest.approx(0.80, abs=NIS_ATOL) + assert fitted.pretest_form == "nis" + + @pytest.mark.parametrize( + "kwargs", + [ + {"violation_type": "linear"}, + {"violation_type": "constant"}, + {"violation_type": "last_period"}, + {"violation_type": "custom", "violation_weights": np.array([4.0, 3.0, 2.0, 1.0])}, + ], + ids=["linear", "constant", "last_period", "custom"], + ) + def test_violation_types(self, cs_diagnosis, kwargs): + fitted = PreTrendsPower(**kwargs).fit(cs_diagnosis) + assert np.isfinite(fitted.mdv) and fitted.mdv > 0 + assert fitted.covariance_source == "placebo_draws" + + def test_other_entry_points_accept_the_diagnosis(self, cs_diagnosis, cs_surface): + planner = PreTrendsPower() + reference = planner.fit(cs_surface) + assert compute_mdv(cs_diagnosis) == pytest.approx(reference.mdv, rel=5e-3) + at_m = compute_pretrends_power(cs_diagnosis, M=0.3) + assert at_m.power == pytest.approx(planner.fit(cs_surface, M=0.3).power, abs=NIS_ATOL) + assert planner.power_at(cs_diagnosis, 0.3) == pytest.approx(at_m.power, abs=NIS_ATOL) + curve = planner.power_curve(cs_diagnosis, M_grid=[0.0, 0.2, 0.4]) + expected = planner.power_curve(cs_surface, M_grid=[0.0, 0.2, 0.4]) + np.testing.assert_allclose(curve.powers, expected.powers, atol=NIS_ATOL) + assert curve.mdv == pytest.approx(reference.mdv, rel=5e-3) + + def test_pre_period_subset(self, cs_diagnosis): + planner = PreTrendsPower() + subset = planner.fit(cs_diagnosis, pre_periods=[-3, -2]) + assert subset.n_pre_periods == 2 + np.testing.assert_array_equal(subset.violation_weights, [2.0, 1.0]) + with pytest.raises(ValueError, match="not eligible"): + planner.fit(cs_diagnosis, pre_periods=[-9]) + + def test_wald_form_is_refused_for_a_planned_input(self, cs_diagnosis, cs_surface): + wald = PreTrendsPower(pretest_form="wald") + for planned in (cs_diagnosis, cs_surface): + with pytest.raises(ValueError, match="pretest_form='nis' only"): + wald.fit(planned) + with pytest.raises(ValueError, match="pretest_form='nis' only"): + wald.power_curve(cs_diagnosis) + with pytest.raises(ValueError, match="pretest_form='nis' only"): + wald.power_by_pre_periods(cs_diagnosis) + + def test_check_is_made_on_the_tested_set(self): + """Power is reported for a set that agrees and refused for one that does not.""" + surface = _independent_surface(n_pre=4, inflate=(0, 1)) + planner = PreTrendsPower() + near = planner.fit(surface, pre_periods=[-3, -2]) + assert np.isfinite(near.mdv) + for call in ( + lambda: planner.fit(surface), + lambda: planner.fit(surface, pre_periods=[-5, -2]), + lambda: planner.power_at(surface, 0.3), + lambda: planner.power_curve(surface, M_grid=[0.1]), + ): + with pytest.raises(ValueError, match="Planned pre-trend power is not reported") as info: + call() + assert "more often than assumed" in str(info.value) + + def test_test_that_rejects_too_rarely_is_refused_too(self): + surface = _independent_surface(n_pre=3) + record = getattr(surface, design_module._PRETEST_RECORD) + record["abs_t"] = record["abs_t"] * 0.6 + with pytest.raises(ValueError, match="less often than assumed"): + PreTrendsPower().fit(surface) + + def test_surface_without_its_record_is_refused(self, cs_surface): + """A copy rebuilt field by field cannot be checked, so nothing is planned from it.""" + import dataclasses + + copied = dataclasses.replace(cs_surface) + assert copied.estimand == "placebo" + with pytest.raises(ValueError, match="carries no per-draw record"): + PreTrendsPower().fit(copied) + + def test_check_uses_the_planners_alpha(self): + surface = _independent_surface(n_pre=3) + planner = PreTrendsPower(alpha=0.10) + counted, expected, n_draws, agrees = planner._planned_pretest_check( + surface, [-4, -3, -2], np.array([3.0, 2.0, 1.0]), surface.vcov[:3, :3] + ) + assert expected == pytest.approx(1.0 - 0.90**3, abs=NIS_ATOL) + assert counted == pytest.approx(1.0 - 0.90**3, abs=0.03) + assert n_draws == 4000 and agrees + + def test_diagnosis_without_the_keyword(self, panel): + diagnosis = _diagnose(panel, [CallawaySantAnna()], event_study=False) + with pytest.raises(ValueError, match="event_study=True"): + PreTrendsPower().fit(diagnosis) + + def test_diagnosis_with_no_surface(self, panel): + diagnosis = _diagnose(panel, [ImputationDiD()]) + with pytest.raises(ValueError, match="recorded no placebo event study"): + PreTrendsPower().fit(diagnosis) + + def test_diagnosis_with_several_surfaces(self, panel): + diagnosis = _diagnose( + panel, {"a": CallawaySantAnna(base_period="universal"), "b": StackedDiD(kappa_pre=3)} + ) + with pytest.raises(ValueError, match=r"event_study_results\[label\]"): + PreTrendsPower().fit(diagnosis) + assert np.isfinite(PreTrendsPower().fit(diagnosis.event_study_results["b"]).mdv) + + def test_varying_base_warns_on_a_planned_surface(self, panel): + diagnosis = _diagnose(panel, [CallawaySantAnna()]) + with pytest.warns(UserWarning, match="without a universal"): + PreTrendsPower().fit(diagnosis, pre_periods=[-2, -1]) + + def test_size_warning_once_per_public_call(self, panel): + diagnosis = _diagnose(panel, [CallawaySantAnna(base_period="universal")]) + diagnosis.size_controlled["CallawaySantAnna"] = False + planner = PreTrendsPower() + calls = { + "fit": lambda: planner.fit(diagnosis), + "power_at": lambda: planner.power_at(diagnosis, 0.2), + "power_curve": lambda: planner.power_curve(diagnosis, M_grid=[0.1]), + "power_by_pre_periods": lambda: planner.power_by_pre_periods(diagnosis), + } + for name, call in calls.items(): + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always") + call() + hits = [m for m in _messages(recorded) if "did not pass the size check" in m] + assert len(hits) == 1, name + + +class TestPowerByPrePeriods: + COLUMNS = [ + "n_pre_periods", + "pre_periods", + "mdv", + "max_abs_pre_violation", + "power_no_violation", + "placebo_rejection_rate", + "power", + ] + + def test_rows_equal_fit_calls(self, cs_diagnosis, cs_surface): + planner = PreTrendsPower() + table = planner.power_by_pre_periods(cs_diagnosis, M=0.3) + assert list(table.columns) == self.COLUMNS + assert table["n_pre_periods"].tolist() == [1, 2, 3, 4] + assert table["pre_periods"].tolist() == [[-2], [-3, -2], [-4, -3, -2], [-5, -4, -3, -2]] + assert table["mdv"].notna().all(), "every tested set agrees on this fixture" + for _, row in table.iterrows(): + fitted = planner.fit(cs_surface, M=0.3, pre_periods=row["pre_periods"]) + assert row["mdv"] == pytest.approx(fitted.mdv, rel=5e-3) + assert row["max_abs_pre_violation"] == pytest.approx( + fitted.max_abs_pre_violation, rel=5e-3 + ) + assert row["power"] == pytest.approx(fitted.power, abs=NIS_ATOL) + assert row["power_no_violation"] == pytest.approx(fitted.power_at(0.0), abs=NIS_ATOL) + counted, _ = design_module.placebo_pretest_rate(cs_surface, row["pre_periods"], 0.05) + assert row["placebo_rejection_rate"] == counted + assert np.all(np.isnan(planner.power_by_pre_periods(cs_diagnosis)["power"])) + + def test_no_violation_rate_grows_with_k(self): + """Independent coefficients: the any-significant test rejects at 1 - 0.95^K.""" + table = PreTrendsPower().power_by_pre_periods(_independent_surface(n_pre=4)) + expected = 1.0 - 0.95 ** np.arange(1, 5) + np.testing.assert_allclose(table["power_no_violation"], expected, atol=NIS_ATOL) + np.testing.assert_allclose(table["placebo_rejection_rate"], expected, atol=0.02) + assert np.all(np.diff(table["power_no_violation"]) > 10 * NIS_ATOL) + assert table["mdv"].notna().all() + + def test_rows_that_disagree_are_blank(self): + """Tests reaching the two earliest pre-periods reject too often: no number there.""" + surface = _independent_surface(n_pre=4, inflate=(0, 1)) + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always") + table = PreTrendsPower().power_by_pre_periods(surface, M=0.5) + assert table["mdv"].notna().tolist() == [True, True, False, False] + blank = table.iloc[2:] + assert blank[["mdv", "max_abs_pre_violation", "power"]].isna().all().all() + assert (blank["placebo_rejection_rate"] > blank["power_no_violation"]).all() + assert table.iloc[:2]["power"].notna().all() + hits = [m for m in _messages(recorded) if "is not reported for tests of [3, 4]" in m] + assert len(hits) == 1 + + def test_refuses_a_fitted_model(self, panel): + frame = design_module._make_placebo_generator(panel, "y", "id", "t", 10, [6], True)( + treatment_effect=0.0, seed=1 + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fitted = CallawaySantAnna(base_period="universal").fit( + frame, outcome="y", unit="id", time="t", first_treat="_placebo_first_treat" + ) + for realized in (fitted, fitted.aggregate("event_study")): + with pytest.raises(TypeError, match="has not been run"): + PreTrendsPower().power_by_pre_periods(realized) + + @pytest.mark.parametrize("magnitude", [float("nan"), float("inf")]) + def test_non_finite_magnitude_is_refused(self, cs_diagnosis, cs_surface, magnitude): + """A NaN magnitude must not be reported as a rejection probability of one.""" + planner = PreTrendsPower() + for planned in (cs_diagnosis, cs_surface): + with pytest.raises(ValueError, match="must be finite"): + planner.power_by_pre_periods(planned, M=magnitude) + with pytest.raises(ValueError, match="must be finite"): + planner.fit(planned, M=magnitude) + with pytest.raises(ValueError, match="must be finite"): + planner.power_at(planned, magnitude) + with pytest.raises(ValueError, match="must be finite"): + planner.power_curve(planned, M_grid=[0.1, magnitude]) + with pytest.raises(ValueError, match="must be finite"): + planner.fit(cs_surface).power_at(magnitude) + + def test_refuses_custom_weights(self, cs_diagnosis): + planner = PreTrendsPower(violation_type="custom", violation_weights=np.ones(4)) + with pytest.raises(ValueError, match="violation_type='custom'"): + planner.power_by_pre_periods(cs_diagnosis) + + def test_repeated_warning_is_issued_once(self, panel): + diagnosis = _diagnose(panel, [CallawaySantAnna()]) + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always") + table = PreTrendsPower().power_by_pre_periods(diagnosis) + assert len(table) > 1 + hits = [m for m in _messages(recorded) if "without a universal" in m] + assert len(hits) == 1 + + +# --------------------------------------------------------------------------- +# Consumers that must not read a placebo surface as an estimate +# --------------------------------------------------------------------------- + + +@pytest.fixture(scope="module") +def fitted_cs(panel): + frame = design_module._make_placebo_generator(panel, "y", "id", "t", 10, [6], True)( + treatment_effect=0.5, seed=2 + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return CallawaySantAnna(base_period="universal").fit( + frame, outcome="y", unit="id", time="t", first_treat="_placebo_first_treat" + ) + + +class TestConsumers: + def test_honest_did_refuses(self, cs_surface): + with pytest.raises(ValueError, match="placebo event study from diagnose_design"): + HonestDiD().fit(cs_surface) + with pytest.raises(ValueError, match="placebo event study from diagnose_design"): + HonestDiD().sensitivity_analysis(cs_surface) + + def test_sensitivity_to_honest_did_refuses(self, cs_diagnosis, cs_surface): + for planned in (cs_diagnosis, cs_surface): + with pytest.raises(ValueError, match="describes a realized event study"): + PreTrendsPower().sensitivity_to_honest_did(planned) + + def test_reports_refuse_planned_power(self, cs_diagnosis, fitted_cs): + planned = PreTrendsPower().fit(cs_diagnosis) + precomputed = {"pretrends_power": planned} + with pytest.raises(ValueError, match="DiagnosticReport: precomputed"): + DiagnosticReport(fitted_cs, precomputed=precomputed) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + ready = DiagnosticReport(fitted_cs) + paths = ( + {}, + {"auto_diagnostics": False}, + {"diagnostics": ready}, + ) + for extra in paths: + with pytest.raises(ValueError, match="BusinessReport: precomputed"): + BusinessReport(fitted_cs, precomputed=precomputed, **extra) + + def test_reports_still_accept_fitted_power(self, fitted_cs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + realized = compute_pretrends_power(fitted_cs.aggregate("event_study")) + assert realized.covariance_source != "placebo_draws" + DiagnosticReport(fitted_cs, precomputed={"pretrends_power": realized}) + BusinessReport(fitted_cs, precomputed={"pretrends_power": realized}) + + def test_plot_event_study_accepts(self, cs_surface): + pytest.importorskip("matplotlib") + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + from diff_diff import plot_event_study + + ax = plot_event_study(cs_surface, ylabel="Placebo estimate", show=False) + assert ax is not None + plt.close("all") + + +# --------------------------------------------------------------------------- +# Results contract +# --------------------------------------------------------------------------- + + +class TestResultsContract: + def test_pickle_round_trip(self, cs_diagnosis): + loaded = pickle.loads(pickle.dumps(cs_diagnosis)) + assert loaded.event_study is True + np.testing.assert_array_equal( + loaded.event_study_results["CallawaySantAnna"].vcov, + cs_diagnosis.event_study_results["CallawaySantAnna"].vcov, + ) + assert loaded._event_study_checks == cs_diagnosis._event_study_checks + record = getattr( + loaded.event_study_results["CallawaySantAnna"], design_module._PRETEST_RECORD + ) + original = getattr( + cs_diagnosis.event_study_results["CallawaySantAnna"], design_module._PRETEST_RECORD + ) + np.testing.assert_array_equal(record["abs_t"], original["abs_t"]) + planner = PreTrendsPower() + assert planner.fit(loaded).mdv == pytest.approx(planner.fit(cs_diagnosis).mdv, rel=5e-3) + + def test_pickle_from_before_the_fields_existed(self, panel): + """A state without the three new attributes loads with their defaults.""" + diagnosis = _diagnose(panel, [CallawaySantAnna()], event_study=False) + state = dict(diagnosis.__dict__) + for name in ("event_study", "event_study_results", "_event_study_checks"): + del state[name] + old = object.__new__(type(diagnosis)) + old.__dict__.update(state) + loaded = pickle.loads(pickle.dumps(old)) + assert loaded.event_study is False + assert loaded.event_study_results == {} + assert loaded._event_study_checks == {} + assert loaded.summary() == diagnosis.summary() + assert loaded.to_dict()["event_study"] is False + assert isinstance(loaded == diagnosis, bool) + assert loaded.lock(progress=False).to_json() == diagnosis.lock(progress=False).to_json() + + def test_equality_does_not_raise_with_surfaces(self, panel): + """Surfaces hold arrays; ``==`` must still return a bool.""" + estimator = [CallawaySantAnna(base_period="universal")] + first = _diagnose(panel, estimator, seed=3) + second = _diagnose(panel, estimator, seed=3) + assert first.event_study_results and second.event_study_results + assert isinstance(first == second, bool) + assert first == first + + def test_lock_is_unchanged_by_the_keyword(self, panel): + estimators = { + "cs": CallawaySantAnna(base_period="universal"), + "st": StackedDiD(kappa_pre=3), + } + locks = [] + for flag in (False, True): + diagnosis = _diagnose(panel, estimators, seed=9, event_study=flag) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + locks.append(diagnosis.lock("cs", data=panel, progress=False).to_json()) + assert locks[0] == locks[1] + + +# --------------------------------------------------------------------------- +# Simulation evidence +# --------------------------------------------------------------------------- + + +@pytest.fixture(scope="module") +def planning_evidence(): + import json + from pathlib import Path + + path = Path(__file__).resolve().parents[1] / "benchmarks/data/pretrend_planning_check.json" + if not path.exists(): + pytest.skip("benchmarks/data/pretrend_planning_check.json is not available") + return json.loads(path.read_text()) + + +class TestPlanningEvidence: + """The numbers the REGISTRY ``## DesignDiagnosis`` placebo event-study Notes quote.""" + + @staticmethod + def _cells(evidence, passed): + return [ + (point, run, cell) + for point in evidence["design_points"] + for run in point["runs"] + for cell in run["cells"] + if cell["check_passed"] is passed + ] + + def test_grid(self, planning_evidence): + meta = planning_evidence["meta"] + assert (meta["n_diagnosis"], meta["n_direct"], meta["n_cells"]) == (500, 1000, 48) + assert len(planning_evidence["design_points"]) == 12 + assert (meta["n_cells_check_passed"], meta["n_cells_check_failed"]) == (28, 20) + + def test_which_cells_pass_the_pretest_check(self, planning_evidence): + def by_units(passed): + units = [point["n_units"] for point, _, _ in self._cells(planning_evidence, passed)] + return units.count(40), units.count(200) + + assert by_units(True) == (6, 22) + assert by_units(False) == (18, 2) + + def test_formula_holds_where_the_check_agrees(self, planning_evidence): + cells = [cell for _, _, cell in self._cells(planning_evidence, True)] + assert not any(cell["flag_power"] or cell["flag_no_violation"] for cell in cells) + powers = [cell["direct_power_at_mdv"] for cell in cells] + assert 0.725 <= min(powers) and max(powers) <= 0.845 + assert np.mean(powers) == pytest.approx(0.79, abs=0.005) + gaps = [cell["direct_no_violation"] - cell["planned_no_violation"] for cell in cells] + assert -0.0045 <= min(gaps) and max(gaps) <= 0.0525 + counted = [cell["placebo_rejection_rate"] - cell["planned_no_violation"] for cell in cells] + assert -0.0195 <= min(counted) and max(counted) <= 0.0245 + + def test_formula_fails_where_the_check_disagrees(self, planning_evidence): + cells = [cell for _, _, cell in self._cells(planning_evidence, False)] + flagged = [cell for cell in cells if cell["flag_power"] or cell["flag_no_violation"]] + assert len(flagged) == 15 + unflagged_units = [ + point["n_units"] + for point, _, cell in self._cells(planning_evidence, False) + if not (cell["flag_power"] or cell["flag_no_violation"]) + ] + assert sorted(unflagged_units) == [40, 40, 40, 200, 200] + powers = [cell["direct_power_at_mdv"] for cell in cells] + assert 0.775 <= min(powers) and max(powers) <= 0.905 + assert np.mean(powers) == pytest.approx(0.83, abs=0.005) + gaps = [cell["direct_no_violation"] - cell["planned_no_violation"] for cell in cells] + assert 0.0225 <= min(gaps) and max(gaps) <= 0.2155 + counted = [cell["placebo_rejection_rate"] - cell["planned_no_violation"] for cell in cells] + assert 0.0285 <= min(counted) and max(counted) <= 0.2165 + + def test_monte_carlo_spread_of_the_planned_mdv(self, planning_evidence): + spread = { + (row["n_units"], row["n_simulations"]): row["relative_spread"] + for row in planning_evidence["stability"] + } + assert all(0.04 <= spread[(n, 200)] <= 0.05 for n in (40, 200)) + assert all(0.03 <= spread[(n, 500)] <= 0.04 for n in (40, 200)) + assert all(0.02 <= spread[(n, 1000)] <= 0.025 for n in (40, 200)) + + def test_selection_effect_is_small(self, planning_evidence): + rows = {row["n_units"]: row for row in planning_evidence["selection"]} + assert all(row["measurable"] and not row["flag"] for row in rows.values()) + assert rows[40]["relative_difference_mean"] == pytest.approx(-0.017, abs=6e-4) + assert rows[40]["relative_difference_se"] == pytest.approx(0.007, abs=6e-4) + assert rows[200]["relative_difference_mean"] == pytest.approx(0.014, abs=6e-4) + assert rows[200]["relative_difference_se"] == pytest.approx(0.006, abs=6e-4) + + +@pytest.fixture(scope="module") +def planning_benchmark(): + """The benchmark script as a module (skipped where benchmarks/ is not checked out).""" + import importlib.util + from pathlib import Path + + path = Path(__file__).resolve().parents[1] / "benchmarks/python/pretrend_planning_check.py" + if not path.exists(): + pytest.skip("benchmarks/python/pretrend_planning_check.py is not available") + spec = importlib.util.spec_from_file_location("pretrend_planning_check", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class TestBenchmarkScoring: + """The benchmark scores every tested set of a run on the same fresh draws.""" + + @staticmethod + def _surface(event_time, ratios): + event_time = np.asarray(event_time) + is_reference = event_time == -1 + ratios = np.asarray(ratios, dtype=float) + return EventStudyResults( + event_time=event_time, + att=np.where(is_reference, 0.0, ratios), + se=np.where(is_reference, np.nan, 1.0), + t_stat=np.where(is_reference, np.nan, ratios), + p_value=np.where(is_reference, np.nan, np.where(np.abs(ratios) > 1.96, 0.01, 0.5)), + conf_int_lower=np.where(is_reference, np.nan, ratios - 1.96), + conf_int_upper=np.where(is_reference, np.nan, ratios + 1.96), + is_reference=is_reference, + n=np.full(len(event_time), np.nan), + ) + + def test_a_draw_missing_a_planned_period_is_not_scored_at_all(self, planning_benchmark): + """It rejects on the nearest set but lacks the earliest period: no partial count.""" + required = [-4, -3, -2] + tested_sets = [[-2], [-3, -2], [-4, -3, -2]] + short = self._surface([-3, -2, -1, 0], [0.1, 5.0, 0.0, 0.0]) + assert planning_benchmark.score_event_study(short, required, tested_sets, 1.96) is None + full = self._surface([-4, -3, -2, -1, 0], [3.0, 0.1, 0.2, 0.0, 0.0]) + assert planning_benchmark.score_event_study(full, required, tested_sets, 1.96) == [ + (False, False), + (False, False), + (True, True), + ] + + def test_a_draw_with_a_non_finite_ratio_is_not_scored(self, planning_benchmark): + surface = self._surface([-4, -3, -2, -1, 0], [np.nan, 0.1, 5.0, 0.0, 0.0]) + assert planning_benchmark.score_event_study(surface, [-4, -3, -2], [[-2]], 1.96) is None diff --git a/tests/test_pretrends.py b/tests/test_pretrends.py index bda1f096..db1dd6fc 100644 --- a/tests/test_pretrends.py +++ b/tests/test_pretrends.py @@ -214,6 +214,28 @@ def test_custom_weights(self): class TestPowerComputation: """Tests for power computation.""" + @pytest.mark.parametrize("pretest_form", ["nis", "wald"]) + @pytest.mark.parametrize("magnitude", [float("nan"), float("inf")]) + def test_non_finite_magnitude_is_refused( + self, mock_event_study_results, pretest_form, magnitude + ): + """A NaN ``M`` was reported as power 1.0 (NIS) or alpha (Wald).""" + pt = PreTrendsPower(pretest_form=pretest_form) + with pytest.raises(ValueError, match="must be finite"): + pt.fit(mock_event_study_results, M=magnitude) + with pytest.raises(ValueError, match="must be finite"): + pt.power_at(mock_event_study_results, magnitude) + with pytest.raises(ValueError, match="must be finite"): + pt.power_curve(mock_event_study_results, M_grid=[0.5, magnitude]) + fitted = pt.fit(mock_event_study_results, M=0.5) + with pytest.raises(ValueError, match="must be finite"): + fitted.power_at(magnitude) + with pytest.raises(ValueError, match="must be finite"): + compute_pretrends_power( + mock_event_study_results, M=magnitude, pretest_form=pretest_form + ) + assert 0.0 <= fitted.power_at(0.5) <= 1.0 + def test_power_at_zero_equals_alpha(self): """Test that power at M=0 equals alpha (size of test). diff --git a/tests/test_t34_design_diagnosis_drift.py b/tests/test_t34_design_diagnosis_drift.py index 6ff5ef79..8b96ddbc 100644 --- a/tests/test_t34_design_diagnosis_drift.py +++ b/tests/test_t34_design_diagnosis_drift.py @@ -34,6 +34,7 @@ BusinessReport, CallawaySantAnna, ImputationDiD, + PreTrendsPower, TwoWayFixedEffects, diagnose_design, ) @@ -225,6 +226,10 @@ def test_quotes_in_rendered_surface(): "all 28 checks that were run", "warning | design_deviation", "By-hand ATT 0.393 vs locked ATT 0.393", + # Section 5: the planned pre-trend check (500 replicates, seed 36). + " 2 0.357 0.084 0.092", + " 3 NaN 0.111 0.152", + "rejected 29.6% of the 500 no-effect replicates, against 25.0%", ], surface="output", ) @@ -239,6 +244,11 @@ def test_quotes_in_rendered_surface(): "**55.5%**", # cs power at 0.5, rerun "**28 checks**", "**0.393**", + "**8.4%**", # formula's false-alarm rate, two pre-period months + "**9.2%**", # the same rate counted in the placebo draws + "**0.357**", # planned MDV, two pre-period months + "**15.2%**", # counted, three months + "**11.1%**", # assumed, three months ], surface="markdown", ) @@ -276,6 +286,11 @@ def test_notebook_design_matches(): "np.random.default_rng(SEED + 1).choice(N_STORES, size=N_TREATED, replace=False)", 'lock.fit(analysis, first_treat="first_treat")', 'CallawaySantAnna(control_group="not_yet_treated")', + 'estimators={"cs": CallawaySantAnna(base_period="universal")}', + "n_simulations=500", + "seed=SEED + 2,", + "event_study=True,", + "PreTrendsPower().power_by_pre_periods(plan)", ): assert fragment in src, f"notebook no longer contains: {fragment}" @@ -343,3 +358,47 @@ def test_lock_rerun(diagnosis, history): assert abs(null["rejection_rate"] - 0.065) < 0.02 assert abs(at_half["rejection_rate"] - 0.555) < 0.05 assert abs(lock.mde - 0.66) < 0.05 + + +def pretrend_plan(history, n_simulations): + """Section 5's run: the chosen estimator alone, new seed, universal base.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + plan = diagnose_design( + history, + estimators={"cs": CallawaySantAnna(base_period="universal")}, + cohort_periods=[PLACEBO_ADOPTION], + n_treated=N_TREATED, + n_simulations=n_simulations, + seed=SEED + 2, + event_study=True, + progress=False, + **COLUMNS, + ) + return plan, PreTrendsPower().power_by_pre_periods(plan) + + +@pytest.mark.slow +def test_pretrend_plan(history): + """Section 5: two rows are planned, the checks over three or more months are not.""" + plan, table = pretrend_plan(history, 500) + assert len(table) == 17 + assert table["mdv"].notna().tolist() == [True, True] + [False] * 15 + two, three = table.iloc[1], table.iloc[2] + assert two["mdv"] == pytest.approx(0.357, abs=2e-3) + assert two["power_no_violation"] == pytest.approx(0.084, abs=1e-3) + assert two["placebo_rejection_rate"] == pytest.approx(0.092, abs=1e-12) + assert three["power_no_violation"] == pytest.approx(0.111, abs=1e-3) + assert three["placebo_rejection_rate"] == pytest.approx(0.152, abs=1e-12) + checks = plan._event_study_checks["cs"] + assert checks["pretest_rejection_rate"] == pytest.approx(0.296, abs=1e-12) + assert checks["pretest_expected_rate"] == pytest.approx(0.250, abs=1e-3) + assert checks["pretest_agrees"] is False + + +@pytest.mark.slow +def test_pretrend_plan_with_more_replicates(history): + """Section 5: with 2,000 replicates every row is blank; one coefficient rejects ~6%.""" + _, table = pretrend_plan(history, 2000) + assert table["mdv"].isna().all() + assert 0.055 <= table.iloc[0]["placebo_rejection_rate"] <= 0.07