diff --git a/TODO.md b/TODO.md index 227b57102..27433dbe1 100644 --- a/TODO.md +++ b/TODO.md @@ -47,7 +47,7 @@ Related tracking surfaces: | `absorbed_fe_rank` N>=3 general rank: the helper keeps `sum(levels-1)` for 3+ absorbed dims, exact for independent connected dims but an over-count for duplicated/nested triples (measured `a(5),b(4),c==b(4)`: true 7 vs formula 10) and for disconnected N-way graphs. Two-way is component-exact. Deriving general N-way FE rank is a hypergraph problem; do it with a reference (fixest's `fixef.rm`/reghdfe df_a) rather than a guess. See `docs/methodology/variance-conventions.md` D3. | `diff_diff/utils.py` | #variance-inventory | Mid | Low | | `SyntheticControl` conformal (CWZ 2021) AR / innovation-permutation path (Lemmas 5-7) for time-series proxies — the residual-permutation shortcut is only valid for time-permutation-invariant proxies (SC/Lasso/DiD); an AR proxy needs innovation permutation. | `diff_diff/conformal.py`, `diff_diff/synthetic_control_results.py` | CWZ-2021 | Heavy | Low | | Re-run the R-dependent benchmark refresh so `docs/benchmarks.rst`'s TWFE "SE Rel Diff 0.1%" cell reflects the 3.9 K_reference convergence (expected 0.1% -> 0.0%; the table is generated, never hand-edited — the movement is noted in the CHANGELOG entry). | `docs/benchmarks.rst`, `benchmarks/R/` | #variance-inventory | Quick | Low | -| `SunAbraham`: a cohort not observed at its own reference relative period (`e = -1 - anticipation`) makes that cohort's block collinear, so QR drops an unnamed column (`dropping 1 of 12 columns (column 9)`) and `overall_att` comes back **NaN**. Found by auditing the sibling estimator while fixing the ETWFE analogue (#724); PRE-EXISTING, not introduced there. Lower severity than #724 — that returned a silently WRONG finite number, this returns NaN with a rank warning — but the event-study surface still looks complete, so a user may not notice the loss. SA already omits its reference explicitly and tracks `_reference_observed`, so the fix is per-cohort support for that flag rather than the ETWFE-style redesign. | `diff_diff/sun_abraham.py` | #724-audit | Mid | Low | +| `SunAbraham`: a cohort not observed at its own reference relative period (`e = -1 - anticipation`) makes that cohort's block collinear, so QR drops an unnamed column (`dropping 1 of 12 columns (column 9)`) and `overall_att` comes back **NaN**. Reproduces on the bundled `load_divorce_laws()` panel (cohort 1968 is treated from the first panel year), where `SunAbraham().fit(...)` returns `att = NaN` after "dropping 1 of 261 columns (column 10)". Found by auditing the sibling estimator while fixing the ETWFE analogue (#724); PRE-EXISTING, not introduced there. Lower severity than #724 — that returned a silently WRONG finite number, this returns NaN with a rank warning — but the event-study surface still looks complete, so a user may not notice the loss. SA already omits its reference explicitly and tracks `_reference_observed`, so the fix is per-cohort support for that flag rather than the ETWFE-style redesign. | `diff_diff/sun_abraham.py` | #724-audit | Mid | Low | | Define `N_g` (W2025 Eqs. 7.4/7.6) for UNBALANCED panels where comparison-support filtering removes every observation of some units in an estimated cohort, then replace the fail-closed guard with the defined behavior. `_n_g_per_cohort` is read off the final sample, so those units vanish from the cohort-share weights; measured on a cohort supplied with 100 units of which 90 appear only at a dropped period, `aggregate(weights="cohort_share")` moves 1.8078 -> 3.8157. The paper assumes a balanced panel and does not say whether `N_g` counts the supplied cohort or the surviving units, and the two disagree materially, so `aggregate` currently raises naming the cohorts and counts ([M-125]); `weights="cell"` is unaffected and balanced panels never trip it. Settle the estimand (likely: count the supplied cohort, since ATT(g,t) is a cohort-level quantity, but that weights units with no retained observation) and gate with a test computing Eq. 7.4 by hand on unequal cohort sizes. | `diff_diff/wooldridge_results.py`, `diff_diff/wooldridge.py` | #729-followup | Mid | Medium | | `WooldridgeDiD` + `survey_design=` does not support DOMAIN ESTIMATION, so BOTH row-deleting paths are currently REFUSED (`NotImplementedError`, all three methods) rather than performed: unidentified-cohort exclusion ([M-123]) and comparison-support period filtering ([M-125]). One fix unblocks both. Implementing it properly means zero-padding the excluded rows' weights while retaining strata/PSU/FPC, per REGISTRY *Subpopulation Analysis (Phase 6)* / Lumley (2004) 3.4, so TSL variance and `df_survey = n_PSU - n_strata` use the full design (naive deletion measured 22 -> 14 on a two-stratum panel). `SurveyDesign.subpopulation()` already implements the contract and SpilloverDiD Wave E.3 is the in-repo precedent; the blocker is that the weighted within-transform rejects zero-weight units, shared machinery behind 7 estimators. Landing it would turn both refusals back into supported fits. Gate with a `SurveyDesign.subpopulation()` parity test on ATT, TSL SE and survey df where the excluded cohort exhausts a PSU. | `diff_diff/wooldridge.py`, `diff_diff/utils.py` | #724-codex-R4/R5 | Heavy | Medium | | `WooldridgeDiD` REFUSES a fit whose only treatment cells fall inside the anticipation window, discarding estimates it successfully computed. `_require_estimable_overall_att` ([M-124]) raises when no cell has `t >= g`, because the overall ATT averages only `t >= g` (W2025 excludes anticipation leads) while cells from `t >= g - anticipation` are ESTIMATED. For a cohort never observed at or after its own treatment date, those anticipation-window ATT(g, t) are real, identified estimates and are thrown away with the fit. **The refusal is a stopgap for the missing estimand semantics, not the intended end state.** Real fix: decide what such a fit should return — most likely the per-cell ATT(g, t) plus an overall that is explicitly undefined with a stated reason (not a bare NaN, per the no-silent-NaN convention) — then relax the guard to that. Needs a REGISTRY note defining the estimand and an `aggregate()` story for the anticipation-only case. | `diff_diff/wooldridge.py` | #724-codex-R2 | Mid | Medium | @@ -67,6 +67,13 @@ Related tracking surfaces: | DurationDiD alternative finite-sample PH estimators (the repaired cumulative-increment slope of Equation 3.5 and the average-hazard slope of Equation 3.6) as an opt-in beside the shipped mean-of-ratios coefficient; they coincide under exact PH and differ under sampling noise (review table, lines 306-311) | `duration_did.py` | #822 | Mid | Low | | `DiagnosticReport` / `BusinessReport` admission of `DurationDiDResults`: both reject it by type today (their batteries are keyed to mean-outcome parallel-trends diagnostics); admission needs a hazard-restriction check family (the Algorithm 2 pretest, the invalid-curve statuses, per-family bootstrap failure counts) and a narrative for per-date absorption ATTs | `diagnostic_report.py`, `business_report.py` | #822 | Mid | Low | | `SyntheticControl` at an exact-fit tie (treated predictors inside the donors' convex hull): `W` and `V` are not identified, and the inner solve reports the active set's vertex (REGISTRY §SyntheticControl). A stated selection rule (Abadie-L'Hour 2021 penalty, or the minimum-norm `W`) is a methodology choice; note that any strictly convex tie-break makes `W(V)` continuous, and the nested search then moves `V` toward a corner where a predictor's weight is negligible (Tutorial 25 under a 1e-10 relative ridge: `V` = (0.017, 2e-12, 0.983)). | `synthetic_control.py`, `utils.py` | #838 | Mid | Low | +| `plot_event_study` rejects the unified `EVENT_STUDY_SCHEMA` frame that every `to_dataframe(level="event_study")` returns (`ValueError: DataFrame must have 'period' column`; the DataFrame branch accepts only `period`/`effect`/`se`). Accepting it needs two decisions first: which level the stored `conf_int_*` are drawn at when the frame carries no `alpha` to compare with the caller's, and how multiple `is_reference` rows map onto the container route's row-aligned marking. Plot the container (`results.aggregate('event_study')`) in the meantime. | `visualization/_event_study.py` | 4.0 tutorial review | Mid | Low | +| `WooldridgeDiDResults.to_dataframe(level="group" / "calendar" / "simple")` names its interval columns `conf_int_lo` / `conf_int_hi`, while its own `level="event_study"` frame and every other results class use `conf_int_lower` / `conf_int_upper`. A public column rename, so it needs a deprecation-ledger row and a transition release. | `wooldridge_results.py` | 4.0 tutorial review | Mid | Low | +| `ChangesInChanges.fit(time=)` takes the 0/1 post indicator, while the 2x2 estimators take that indicator as `post=` and reserve `time=` for the calendar column (the 4.0 TWFE split). Tutorial 27 shows the two side by side. Resolving it is a keyword rename with a ledger row. | `changes_in_changes.py` | 4.0 tutorial review | Mid | Low | +| TROP convergence defaults: on the tutorial-10 panels the default `max_iter=100` leaves most per-observation fits unconverged (the aggregated warning fires on essentially every fit), and the warning text reads "... fits did not converge did not converge in 100 iterations" because the callers pass a method name that already ends in "did not converge" to `warn_if_not_converged`. Fix the wording at the three call sites; separately assess whether the default iteration cap or tolerance should change (needs a convergence study on the paper's designs, not just the tutorial). | `trop.py`, `trop_local.py`, `trop_global.py`, `utils.py` | 4.0 tutorial review | Mid | Low | +| `ImputationDiDResults.pretrend_test()` emits pandas' `Pandas4Warning` ("The inplace keyword in DataFrame.drop is deprecated", PDEP-8) on pandas 3.1: three `drop(..., inplace=True)` calls in the lead-regression path. Rebind instead of dropping in place, and grep the package for the remaining `inplace=True` uses in the same pass. | `imputation_aggregation.py` | 4.0 tutorial review | Quick | Low | +| Conley bandwidth diagnostic: when `conley_cutoff_km` covers the whole treated set (one treated spatial cluster inside the bandwidth), the spatial-HAC meat collapses and the SE falls far below HC1 on data with no spatial correlation (tutorial 23's panel: HC1 0.117; Conley 0.117 at 0.5 km, 0.090 at 25 km, 0.062 at 100 km). This is the usual large-bandwidth HAC degeneracy, not a variance bug, but nothing warns. Candidate: a `UserWarning` when the share of treated-treated pairs inside the cutoff exceeds a threshold; the threshold needs a small simulation to choose. | `conley.py`, `spillover.py` | 4.0 tutorial review | Mid | Low | +| No public idiom for a static staggered TWFE with a time-varying covariate (`Y ~ D_it + X_it` with unit and calendar fixed effects): `TwoWayFixedEffects.fit` is 2x2-shaped in static mode and `decompose()` takes no covariates, so tutorial 33's "include the bad control" benchmark builds it from `within_transform` plus `solve_ols`. Either document that route as the supported one or add a staggered static mode. | `twfe.py`, `docs/tutorials/33_bad_controls.ipynb` | 4.0 tutorial review | Mid | Low | ### Performance diff --git a/changelog.d/20261125-plot-event-study-wooldridge.md b/changelog.d/20261125-plot-event-study-wooldridge.md new file mode 100644 index 000000000..0a9776d5e --- /dev/null +++ b/changelog.d/20261125-plot-event-study-wooldridge.md @@ -0,0 +1,15 @@ +### Fixed +- **`plot_event_study` accepts `WooldridgeDiDResults`**: passing a Wooldridge + ETWFE result (the object `results.aggregate("event_study")` returns) raised + `KeyError: 'effect'`. The result is now converted to the unified event-study + container at entry, so its stored intervals are drawn as-is, the + stored-`alpha` mismatch warning applies, and a `weights="cohort_share"` + aggregation (NaN intervals by design) draws no error bars. A fit on which + `aggregate("event_study")` has not been called raises a `ValueError` naming + that call. On every container input, a row whose stored interval is NaN now + also stays without an interval under an explicit `reference_period=` + (previously the normalization path recomputed one from the SE, which would + have redrawn inference that a producer had disabled). A contract test now pins the one event-study idiom the tutorials + teach (`es = results.aggregate("event_study")` where the class has + `aggregate`, else the result; `plot_event_study(es)`) on all thirteen + estimators that produce an event study. diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index 3b26b3c12..9e6f08915 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -2544,7 +2544,8 @@ All plotting functions return a matplotlib `Figure` object. from diff_diff import plot_event_study plot_event_study( - results, # EventStudyResults (TWFE event-study surface), CS, SA, BJS, TwoStageDiD, StackedDiD, or DataFrame + results, # EventStudyResults (TWFE event-study surface), CS, SA, BJS, TwoStageDiD, StackedDiD, + # WooldridgeDiD (after results.aggregate('event_study')), or DataFrame effects=None, # Manual dict of effects (alternative to results) se=None, # Manual dict of SEs periods=None, diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index 7bec7f93b..c5bcbeffe 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -17,6 +17,7 @@ from diff_diff.staggered import CallawaySantAnnaResults from diff_diff.sun_abraham import SunAbrahamResults from diff_diff.two_stage import TwoStageDiDResults + from diff_diff.wooldridge_results import WooldridgeDiDResults # Type alias for results that can be plotted PlottableResults = Union[ @@ -26,6 +27,7 @@ "TwoStageDiDResults", "StackedDiDResults", "ChaisemartinDHaultfoeuilleResults", + "WooldridgeDiDResults", "EventStudyResults", pd.DataFrame, ] @@ -72,8 +74,12 @@ def plot_event_study( Results object from CallawaySantAnna, a unified :class:`~diff_diff.results_base.EventStudyResults` container (from any producer's ``aggregate('event_study')`` or - ``build_event_study_surface``), or a DataFrame with columns - 'period', 'effect', 'se' (and optionally 'conf_int_lower', + ``build_event_study_surface``), a + :class:`~diff_diff.WooldridgeDiDResults` on which + ``aggregate('event_study')`` has been called (it is converted to + the unified container, so its stored intervals are drawn as-is; + an un-aggregated fit raises ``ValueError``), or a DataFrame with + columns 'period', 'effect', 'se' (and optionally 'conf_int_lower', 'conf_int_upper'). If None, must provide effects and se directly. effects : dict, optional Dictionary mapping periods to effect estimates. Used if results is None. @@ -191,10 +197,27 @@ def plot_event_study( # Track if reference_period was explicitly provided by user reference_period_explicit = reference_period is not None + # WooldridgeDiDResults stores its event-study dict keyed ``att`` (not + # ``effect``) and returns ITSELF from ``aggregate("event_study")``, so + # convert it to the unified container here - BEFORE extraction and the + # stored-alpha guard - and let it take the EventStudyResults route end + # to end (stored intervals preserved, including the NaN intervals of a + # ``weights="cohort_share"`` aggregation, so no misleading error bars + # are recomputed from its conditional-on-shares SE). An un-aggregated + # fit raises the surface builder's ValueError naming the call to make. + if results is not None: + from diff_diff.wooldridge_results import WooldridgeDiDResults as _WooldridgeResults + + if isinstance(results, _WooldridgeResults): + from diff_diff.results_base import build_event_study_surface + + results = build_event_study_surface(results) + # Extract data from results if provided ci_lower_override = None ci_upper_override = None reference_marks: Optional[Set[Any]] = None + undefined_inference: Set[Any] = set() if results is not None: ( effects, @@ -210,6 +233,18 @@ def plot_event_study( pw_upper_override, reference_marks, ) = _extract_plot_data(results, periods, pre_periods, post_periods, reference_period) + # Rows whose STORED inference is undefined (a NaN stored pointwise + # interval on a route that carries one - the container route). Their + # inference was disabled by the producer (e.g. WooldridgeDiD + # ``weights="cohort_share"``, whose conditional-on-shares SE stays + # finite while t/p/CI fail closed to NaN), so no interval may be + # reconstructed for them from the SE on any later path. + if pw_lower_override is not None and pw_upper_override is not None: + undefined_inference = { + p + for p, lo in pw_lower_override.items() + if not (np.isfinite(lo) and np.isfinite(pw_upper_override.get(p, np.nan))) + } # If reference was inferred from results, it was NOT explicitly provided if reference_inferred: reference_period_explicit = False @@ -248,7 +283,14 @@ def plot_event_study( effects = {p: e - ref_effect for p, e in effects.items()} # Set reference SE to NaN (it's now a constraint, not an estimate) # This follows fixest convention where the omitted category has no SE/CI - se = {p: (np.nan if p == reference_period else s) for p, s in se.items()} + # Rows with undefined STORED inference get a NaN SE too: the + # overrides are discarded just below and the intervals recomputed + # from the SE, which must not revive inference the producer + # disabled (their normalized point estimates still plot). + se = { + p: (np.nan if (p == reference_period or p in undefined_inference) else s) + for p, s in se.items() + } # REGISTRY (Event Study Plotting): after explicit normalization, # CIs are RECOMPUTED from the normalized effects and original # SEs, and the reference CI becomes (NaN, NaN). Any simultaneous @@ -1018,7 +1060,8 @@ def _extract_plot_data( f"Cannot extract plot data from {type(results).__name__}. " "Expected CallawaySantAnnaResults, " "SunAbrahamResults, ImputationDiDResults, " - "ChaisemartinDHaultfoeuilleResults, EventStudyResults, or DataFrame. " + "ChaisemartinDHaultfoeuilleResults, WooldridgeDiDResults, " + "EventStudyResults, or DataFrame. " "For a result that stores no event-study surface (DMLDiD, " "EfficientDiD, every CallawaySantAnna fit since 4.0, and ANALYTICAL " "ImputationDiD / TwoStageDiD / ContinuousDiD fits), plot the " diff --git a/docs/api/visualization.rst b/docs/api/visualization.rst index 2b03605a0..f5876969f 100644 --- a/docs/api/visualization.rst +++ b/docs/api/visualization.rst @@ -29,6 +29,22 @@ Example ax = plot_event_study(results) ax.figure.savefig('event_study.png', dpi=300, bbox_inches='tight') +For an estimator with post-fit aggregation, plot the event-study container: + +.. code-block:: python + + from diff_diff import CallawaySantAnna, WooldridgeDiD, plot_event_study + + cs = CallawaySantAnna().fit(data, outcome='y', unit='unit_id', + time='period', first_treat='first_treat') + plot_event_study(cs.aggregate('event_study')) + + # WooldridgeDiD.aggregate() returns the results object itself, which + # plot_event_study accepts once the event study has been aggregated + etwfe = WooldridgeDiD().fit(data, outcome='y', unit='unit_id', + time='period', first_treat='first_treat') + plot_event_study(etwfe.aggregate('event_study')) + plot_group_effects ------------------ diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 114b54d98..aeb8cc41e 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7149,6 +7149,20 @@ should be a deliberate user choice. normalization is accepted only when the chosen period is one of the marked rows (a no-op shift); any other period raises `ValueError`, because each anchor is a constraint under its own cohort base and no single shift represents them faithfully +- **Note (WooldridgeDiD route):** a `WooldridgeDiDResults` passed to `plot_event_study` is + converted to the unified `EventStudyResults` container at entry + (`build_event_study_surface`) and takes the container route end to end: its stored + intervals are drawn as-is (the stored-alpha mismatch warning applies), and the NaN + intervals of a `weights="cohort_share"` aggregation draw no error bars - nothing is + recomputed from the conditional-on-shares SE. A Wooldridge event-study surface has no + reference row, so no marker is hollowed. The no-recomputation guarantee also holds under + an explicit `reference_period=` (which discards the stored-interval overrides and + recomputes pointwise from the SE): on every container-route input, a row whose STORED + pointwise interval is NaN gets a NaN SE before that recomputation, so its normalized point + estimate plots with no interval. Inference a producer disabled (cohort-share weights, an + undefined design df) is never revived by normalizing. A fit on which `aggregate('event_study')` has + not been called raises the surface builder's `ValueError` (previously the raw result + raised `KeyError: 'effect'`, because its native dict is keyed `att`). - **Note (zero-SE pointwise gate, `plot_group_effects` twin):** the pointwise `effect +/- z*SE` reconstruction NaN-gates zero/negative-SE rows on every path that reaches it - a zero-SE row has all-NaN stored inference (`safe_inference`), and a finite diff --git a/tests/test_doc_snippets.py b/tests/test_doc_snippets.py index 45a32cf4e..e7ecaeb63 100644 --- a/tests/test_doc_snippets.py +++ b/tests/test_doc_snippets.py @@ -418,9 +418,9 @@ def _restore_datasets_module(): _CONTEXT_DEPENDENT_SNIPPETS = { "api_bacon:block1", "api_bacon:block2", - "api_visualization:block2", "api_visualization:block3", - "api_visualization:block9", + "api_visualization:block4", + "api_visualization:block10", "python_comparison:block5", "quickstart:block3", "quickstart:block9", diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 9bc2c518b..b3824cbb7 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -854,3 +854,350 @@ def test_pt_post_anticipation_reference_shifts(self): extracted = _extract_plot_data(es, None, None, None, None) assert extracted[5] == -2 # reference_period slot assert extracted[6] is True # inferred, not caller-supplied + + +def _plotted_points(ax): + """Point estimates drawn by plot_event_study: [(x, y, is_hollow)] in x order.""" + pts = [] + for line in ax.lines: + ydata = np.asarray(line.get_ydata(), dtype=float) + if ydata.size != 1 or line.get_marker() in (None, "None", ""): + continue + hollow = line.get_markerfacecolor() in ("white", "w") + pts.append((float(np.asarray(line.get_xdata())[0]), float(ydata[0]), hollow)) + return sorted(pts) + + +def _plotted_intervals(ax): + """Vertical error-bar segments drawn by plot_event_study: {x: (lower, upper)}.""" + out = {} + for coll in ax.collections: + if not hasattr(coll, "get_segments"): + continue + for seg in coll.get_segments(): + seg = np.asarray(seg, dtype=float) + if seg.shape == (2, 2) and seg[0, 0] == seg[1, 0]: + out[float(seg[0, 0])] = (float(seg[:, 1].min()), float(seg[:, 1].max())) + return out + + +class TestPlotEventStudyWooldridge: + """plot_event_study accepts a WooldridgeDiDResults by converting it to the + unified container, so it takes the EventStudyResults route end to end.""" + + @staticmethod + def _fit(**kwargs): + from diff_diff import WooldridgeDiD + from diff_diff.prep_dgp import generate_staggered_data as _gen + + data = _gen(n_units=120, n_periods=8, seed=1) + return WooldridgeDiD(**kwargs).fit( + data, outcome="outcome", unit="unit", time="period", first_treat="first_treat" + ) + + def test_plots_the_stored_surface(self): + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + res = self._fit() + res.aggregate("event_study") + frame = res.to_dataframe(level="event_study") + # A Wooldridge event-study surface carries no reference row. + assert not frame["is_reference"].any() + + ax = plot_event_study(res, show=False) + + points = _plotted_points(ax) + assert len(points) == len(frame) + np.testing.assert_allclose([p[1] for p in points], frame["att"].to_numpy(), rtol=1e-12) + assert not any(p[2] for p in points) # nothing drawn as a reference marker + intervals = _plotted_intervals(ax) + assert len(intervals) == len(frame) + for x, (_, row) in enumerate(frame.iterrows()): + lo, hi = intervals[float(x)] + np.testing.assert_allclose( + [lo, hi], [row["conf_int_lower"], row["conf_int_upper"]], rtol=1e-10 + ) + assert [t.get_text() for t in ax.get_xticklabels()] == [ + str(e) for e in frame["event_time"].tolist() + ] + plt.close() + + def test_matches_the_container_route(self): + """The raw result and build_event_study_surface(result) plot identically.""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + from diff_diff.results_base import build_event_study_surface + + res = self._fit() + res.aggregate("event_study") + ax_raw = plot_event_study(res, show=False) + pts_raw, ci_raw = _plotted_points(ax_raw), _plotted_intervals(ax_raw) + plt.close() + ax_cont = plot_event_study(build_event_study_surface(res), show=False) + assert _plotted_points(ax_cont) == pts_raw + assert _plotted_intervals(ax_cont) == ci_raw + plt.close() + + def test_unaggregated_fit_raises(self): + pytest.importorskip("matplotlib") + + res = self._fit() + assert res.event_study_effects is None + with pytest.raises(ValueError, match=r"aggregate\('event_study'\)"): + plot_event_study(res, show=False) + + def test_stored_alpha_mismatch_warns(self): + """Stored intervals are at the fit's level; a different plot alpha warns.""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + res = self._fit(alpha=0.10) + res.aggregate("event_study") + with pytest.warns(UserWarning, match="does not apply to an EventStudyResults container"): + plot_event_study(res, show=False) # default alpha=0.05 + plt.close() + + def test_cohort_share_draws_no_error_bars(self): + """The fail-closed cohort-share inference (NaN intervals) is preserved: + no interval is recomputed from the conditional-on-shares SE.""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + res = self._fit() + with pytest.warns(UserWarning, match="conditional-on-shares"): + res.aggregate("event_study", weights="cohort_share") + frame = res.to_dataframe(level="event_study") + assert np.isfinite(frame["se"]).all() + assert frame["conf_int_lower"].isna().all() + + ax = plot_event_study(res, show=False) + assert len(_plotted_points(ax)) == len(frame) + assert _plotted_intervals(ax) == {} + plt.close() + + @pytest.mark.parametrize("use_cband", [True, False]) + def test_cohort_share_stays_undefined_under_explicit_reference(self, use_cband): + """Explicit reference_period= discards the stored intervals and recomputes + from the SE; that recomputation must not revive the inference the + cohort-share aggregation disabled (finite SE, NaN t/p/CI).""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + res = self._fit() + with pytest.warns(UserWarning, match="conditional-on-shares"): + res.aggregate("event_study", weights="cohort_share") + frame = res.to_dataframe(level="event_study") + + ax = plot_event_study(res, reference_period=0, use_cband=use_cband, show=False) + points = _plotted_points(ax) + # the normalized point estimates still plot ... + np.testing.assert_allclose( + [p[1] for p in points], (frame["att"] - frame["att"].iloc[0]).to_numpy(), atol=1e-12 + ) + # ... with no interval on any row + assert _plotted_intervals(ax) == {} + plt.close() + + @pytest.mark.parametrize("use_cband", [True, False]) + def test_cohort_share_explicit_reference_plotly_draws_no_band(self, use_cband): + pytest.importorskip("plotly") + + res = self._fit() + with pytest.warns(UserWarning, match="conditional-on-shares"): + res.aggregate("event_study", weights="cohort_share") + for kwargs in ({}, {"reference_period": 0}): + fig = plot_event_study(res, backend="plotly", use_cband=use_cband, show=False, **kwargs) + assert not [t for t in fig.data if getattr(t, "fill", None) == "toself"] + # positive control: the same call on defined (cell-weighted) inference bands + res.aggregate("event_study") + fig = plot_event_study( + res, backend="plotly", reference_period=0, use_cband=use_cband, show=False + ) + assert [t for t in fig.data if getattr(t, "fill", None) == "toself"] + + @pytest.mark.parametrize("use_cband", [True, False]) + def test_cell_weighted_explicit_reference_keeps_intervals(self, use_cband): + """The undefined-inference mask is row-level: a cell-weighted surface + (defined inference) still gets recomputed intervals on every + non-reference row after explicit normalization.""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + from scipy import stats + + res = self._fit() + res.aggregate("event_study") + frame = res.to_dataframe(level="event_study") + ref = frame["event_time"].tolist().index(0) + + ax = plot_event_study(res, reference_period=0, use_cband=use_cband, show=False) + intervals = _plotted_intervals(ax) + assert sorted(intervals) == [float(i) for i in range(len(frame)) if i != ref] + z = stats.norm.ppf(0.975) + shifted = frame["att"] - frame["att"].iloc[ref] + for x, (lo, hi) in intervals.items(): + i = int(x) + np.testing.assert_allclose( + [lo, hi], + [ + shifted.iloc[i] - z * frame["se"].iloc[i], + shifted.iloc[i] + z * frame["se"].iloc[i], + ], + rtol=1e-10, + ) + plt.close() + + +def _idiom_fit(name): + """A small analytical fit for each event-study producer the tutorials plot.""" + import warnings + + import diff_diff as dd + from diff_diff import prep_dgp + + stag = prep_dgp.generate_staggered_data(n_units=120, n_periods=8, seed=1) + kw = dict(outcome="outcome", unit="unit", time="period", first_treat="first_treat") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + if name == "CallawaySantAnna": + return dd.CallawaySantAnna().fit(stag, **kw) + if name == "SunAbraham": + return dd.SunAbraham().fit(stag, **kw) + if name == "ImputationDiD": + return dd.ImputationDiD().fit(stag, **kw) + if name == "TwoStageDiD": + return dd.TwoStageDiD().fit(stag, **kw) + if name == "StackedDiD": + return dd.StackedDiD(kappa_pre=2, kappa_post=2).fit(stag, **kw) + if name == "EfficientDiD": + return dd.EfficientDiD().fit(stag, **kw) + if name == "WooldridgeDiD": + return dd.WooldridgeDiD().fit(stag, **kw) + if name == "LWDiD": + return dd.LWDiD().fit(stag, treatment="treated", **kw) + if name == "DMLDiD": + cov = stag.copy() + unit_x = np.random.default_rng(0).normal(size=cov["unit"].nunique()) + cov["x1"] = unit_x[cov["unit"].astype("category").cat.codes.to_numpy()] + return dd.DMLDiD(outcome_learner="linear", n_folds=2, seed=1).fit( + cov, covariates=["x1"], **kw + ) + if name == "ChaisemartinDHaultfoeuille": + rev = prep_dgp.generate_reversible_did_data( + n_groups=40, n_periods=6, pattern="single_switch", seed=1 + ) + return dd.ChaisemartinDHaultfoeuille(twfe_diagnostic=False).fit( + rev, outcome="outcome", unit="group", time="period", treatment="treatment", L_max=2 + ) + if name == "ContinuousDiD": + cont = prep_dgp.generate_continuous_did_data( + n_units=150, n_periods=6, cohort_periods=[3, 5], never_treated_frac=0.3, seed=1 + ) + return dd.ContinuousDiD(seed=1).fit(cont, dose="dose", **kw) + if name == "HeterogeneousAdoptionDiD": + had = prep_dgp.generate_continuous_did_data( + n_units=60, + n_periods=8, + cohort_periods=[5], + never_treated_frac=0.0, + dose_distribution="uniform", + dose_params={"low": 5.0, "high": 50.0}, + seed=1, + ) + had.loc[had["period"] < had["first_treat"], "dose"] = 0.0 + return dd.HeterogeneousAdoptionDiD(design="auto").fit(had, dose="dose", **kw) + if name == "TwoWayFixedEffects": + return dd.TwoWayFixedEffects().fit( + generate_multi_period_data(), + outcome="outcome", + treatment="treated", + time="period", + event_study=True, + spec="pooled", + post_periods=[2, 3], + reference_period=1, + ) + raise AssertionError(name) + + +_IDIOM_PRODUCERS = [ + "CallawaySantAnna", + "SunAbraham", + "ImputationDiD", + "TwoStageDiD", + "StackedDiD", + "EfficientDiD", + "WooldridgeDiD", + "LWDiD", + "DMLDiD", + "ChaisemartinDHaultfoeuille", + "ContinuousDiD", + "HeterogeneousAdoptionDiD", + "TwoWayFixedEffects", +] + + +class TestEventStudyIdiomContract: + """The one event-study idiom the tutorials teach (CONTRIBUTING.md, "Tutorial + conventions") works on every producer they plot: + + es = results.aggregate("event_study") if hasattr(results, "aggregate") else results + plot_event_study(es) + table = es.to_dataframe() if isinstance(es, EventStudyResults) \\ + else results.to_dataframe(level="event_study") + + A producer that stops satisfying it must be fixed in the plotter (convert to + the container at the top of plot_event_study), not excepted in the docs. + """ + + @pytest.mark.parametrize("name", _IDIOM_PRODUCERS) + def test_surface_plot_and_table(self, name): + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + from diff_diff.results_base import EVENT_STUDY_SCHEMA, EventStudyResults + + results = _idiom_fit(name) + es = results.aggregate("event_study") if hasattr(results, "aggregate") else results + table = ( + es.to_dataframe() + if isinstance(es, EventStudyResults) + else results.to_dataframe(level="event_study") + ) + assert list(table.columns[: len(EVENT_STUDY_SCHEMA)]) == list(EVENT_STUDY_SCHEMA) + assert len(table) > 0 + + ax = plot_event_study(es, show=False) + points = _plotted_points(ax) + # Every estimated row is drawn. A reference row is drawn (hollow) when the + # surface materializes it; a producer whose baseline is omitted from its + # native dict (SunAbraham's raw-result route) plots the estimated rows only. + if len(points) != len(table): + table = table[~table["is_reference"].astype(bool)] + assert len(points) == len(table) + estimates = table["att"].to_numpy(dtype=float) + plotted = np.array([p[1] for p in points]) + finite = np.isfinite(estimates) + assert finite.any() + np.testing.assert_allclose(plotted[finite], estimates[finite], rtol=1e-12, atol=1e-12) + plt.close() + + def test_container_route_classes(self): + """Pin which producers take which route, so the convention text stays true: + only SunAbraham and the TWFE event-study result lack aggregate(), and only + Wooldridge's aggregate() returns the result itself.""" + from diff_diff.results_base import EventStudyResults + + no_aggregate, self_returning = [], [] + for name in _IDIOM_PRODUCERS: + results = _idiom_fit(name) + if not hasattr(results, "aggregate"): + no_aggregate.append(name) + continue + es = results.aggregate("event_study") + if not isinstance(es, EventStudyResults): + assert es is results + self_returning.append(name) + assert no_aggregate == ["SunAbraham", "TwoWayFixedEffects"] + assert self_returning == ["WooldridgeDiD"]