diff --git a/TODO.md b/TODO.md index 8d3eafe04..180d9b4cf 100644 --- a/TODO.md +++ b/TODO.md @@ -57,7 +57,9 @@ Related tracking surfaces: | 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` + `survey_design=` REFUSES (`NotImplementedError`) a panel holding a cohort with no pre-treatment observation, where the unweighted fit excludes the cohort with a warning: dropping its rows under a survey design is naive subsetting, not domain estimation (strata, PSU counts and the design df change). Implement the design-based version - keep the rows and give the excluded cohort no contribution to the other cohorts' estimates or scores - together with the same gap in `WooldridgeDiD` (its domain-estimation row below); one mechanism serves both. | `diff_diff/sun_abraham.py`, `diff_diff/wooldridge.py` | SunAbraham reference PR | Heavy | Low | | `SunAbraham` + `survey_design=` fails with an array shape mismatch (`operands could not be broadcast together with shapes (720,) (712,)`) when the frame holds a unit whose `first_treat` is negative or missing: the survey arrays are sized to `data`, while `df_reg` drops those rows under `control_group="never_treated"`. Loud, not silent, and pre-existing. Either filter the survey arrays with the same mask or reject such rows up front with a clear message; decide what a negative `first_treat` means first (today it is silently neither treated nor a control). | `diff_diff/sun_abraham.py` | SunAbraham reference PR | Quick | Low | -| `StackedDiD` + `survey_design=` does not retain the full survey design. The design is re-resolved on the stacked rows, so the PSUs and strata of every unit outside the stack leave the Taylor-linearized meat and `df_survey` with no warning (balanced panel, 120 single-unit PSUs in 3 strata, one cohort trimmed by IC1 under `control_group="never_treated"`: 90 PSUs in the fit, `df_survey` 87 where the full design gives 117). For the same reason two cases are REFUSED (`NotImplementedError`) under a survey design where the unweighted fit proceeds with a warning: a unit not observed across its event window, and an adoption event left without complete units. Implement domain estimation - keep the full design and give out-of-stack PSUs zero scores (REGISTRY *Subpopulation Analysis*) - then lift both refusals. | `diff_diff/stacked_did.py`, `diff_diff/survey.py` | StackedDiD complete-window PR | Mid | Medium | +| `plot_event_study` on the plotly backend filters rows without an interval out of the band polygon and fills across their position, so an estimate whose inference is undefined (or whose SE is zero) appears inside a shaded band when its neighbours have intervals; matplotlib draws no bar there. Break the band at such rows (one polygon per run, a visible bar for a one-row run) and continue it only across a real normalization constraint. Doing that needs reference provenance on the raw-results route, which today styles event time `-1` as the reference when the producer marks none (an estimated placebo under `base_period="varying"`) and casts a declared `reference_period` with `int()` (a reference at `-0.5`, as `SunAbraham` can declare, lands on event time 0), plus exact handling of horizon labels of mixed numeric types: the plotting DataFrame coerces mixed int/float labels to `float64`, and `==` between an integer reference and a float horizon is lossy beyond 2**53, so two distinct horizons can share a position (and one can be masked as the reference under explicit normalization). Keep native labels through rendering and position rows by index. | `diff_diff/visualization/_event_study.py` | StackedDiD anticipation PR | Mid | Medium | +| Zero survey degrees of freedom (`df_survey = n_PSU - n_strata = 0` under Taylor linearization) is not handled one way. `StackedDiD` returns NaN inference with a warning, and `safe_inference` returns NaN for any `df <= 0`. `SunAbraham` clamps the df to 1 for its overall and event-study aggregates (`max(survey_metadata.df_survey, 1)`), which then get t(1) inference, while its cell-level inference goes through `LinearRegression.get_inference`, which warns and falls back to the normal distribution for a non-positive df (measured: six units in six strata, `lonely_psu="adjust"`). Decide the rule for a variance-unidentified design (NaN) and apply it in `SunAbraham` and in `get_inference`'s survey branch. | `diff_diff/sun_abraham.py`, `diff_diff/linalg.py` | StackedDiD anticipation PR | Mid | Medium | +| `StackedDiD` + `survey_design=` does not retain the full survey design. The design is re-resolved on the stacked rows, so the PSUs and strata of every unit outside the stack leave the Taylor-linearized meat and `df_survey` with no warning (balanced panel, 120 single-unit PSUs in 3 strata, one cohort trimmed by IC1 under `control_group="never_treated"`: 90 PSUs in the fit, `df_survey` 87 where the full design gives 117). For the same reason three cases are REFUSED (`NotImplementedError`) under a survey design where the unweighted fit proceeds: a unit not observed across its event window, an adoption event left without complete units, and (with `anticipation > 0`) a later cohort that the anticipation-adjusted clean-control cutoff leaves out of every sub-experiment. Implement domain estimation - keep the full design and give out-of-stack PSUs zero scores (REGISTRY *Subpopulation Analysis*) - then lift the three refusals. | `diff_diff/stacked_did.py`, `diff_diff/survey.py` | StackedDiD complete-window PR | Mid | Medium | | 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 | diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md new file mode 100644 index 000000000..482f41825 --- /dev/null +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -0,0 +1,84 @@ +### Fixed +- **`StackedDiD` with `anticipation > 0` no longer uses a later adopter as a + control while that unit is already responding.** The clean-control cutoff + ignored `anticipation`, so under `control_group="not_yet_treated"` (the + default) a cohort adopting at `a + kappa_post + 1` up to + `a + kappa_post + anticipation` stayed in event `a`'s control pool through + periods in which it had started to respond, and the estimate was biased + with no warning. On a noiseless balanced panel (periods 0-8, equal-sized + cohorts adopting at 3 and 6 plus never-treated units, an effect of 2 + starting one period before adoption, `kappa_pre = kappa_post = 2`, + `anticipation = 1`) the fit returned 1.5 at event time 2 and an overall ATT + of 1.875; both are now 2 exactly. The cutoff is now + `A_s > a + kappa_post + anticipation`, and + `A_s > a + kappa_post + kappa_pre + anticipation` under + `control_group="strict"`. A strict fit used a responding control only when + `anticipation > kappa_pre`, but its control set changes more widely: the + new cutoff also drops later cohorts adopting up to `anticipation` periods + past the old one, so that their own window, which now starts + `anticipation` periods earlier, stays disjoint from this one. The inclusion check uses the + same rule, so an adoption event whose only later cohort falls inside the + cutoff is now trimmed. Estimates change only for fits with + `anticipation > 0` that had a later cohort between the old and the new + cutoff; `anticipation=0` and `control_group="never_treated"` are unchanged. + Under `survey_design=`, a fit in which the `anticipation` term leaves a + later cohort out of every sub-experiment now raises `NotImplementedError`: + the design is re-resolved on the stacked rows, so that cohort's PSUs or + strata can leave the variance and its degrees of freedom (on a stratified + census the fit would have reported SE 0.136 with 9 df where the full design + gives SE 0 with 15 df). + Each fit records the rule on the new + `StackedDiDResults.control_cutoff_includes_anticipation` (`True`; `None` on + a result saved by an earlier version). For a `"not_yet_treated"` or + `"strict"` result with `anticipation > 0`, `BusinessReport` and + `DiagnosticReport` state the adjusted cutoff when the result records it; when + it does not, they show the earlier cutoff, label it unverified and say to + rerun the fit. Results with `anticipation=0` or never-treated controls get + no such caveat. Separately, the `BusinessReport` assumption text now gives + the event window with its `anticipation` term whenever `anticipation > 0`. + +- **`StackedDiD` + `survey_design=` without a `psu` column no longer uses + `(unit, sub-experiment)` pairs as survey PSUs under + `cluster="unit_subexp"` (Taylor-linearized variance; replicate-weight + designs are unaffected).** Each original unit is the PSU, as it already was + under the default `cluster="unit"`; a `UserWarning` says that + `"unit_subexp"` does not apply to the survey variance. The pairs duplicated + sampled units and their count moved with the stack: on a stratified panel + with a finite-population correction the fit reported SE 0 with 21 survey + degrees of freedom where the sampled units give SE 0.07906 with 15. + Standard errors change for survey fits that combined `cluster="unit_subexp"` + with a design that names no `psu`; fits with an explicit `psu` or the + default cluster are unchanged. +- **`StackedDiD` + `survey_design=` with zero survey degrees of freedom now + returns NaN inference.** When `n_PSU - n_strata = 0` under Taylor + linearization (for example one PSU per stratum with `lonely_psu="adjust"`) + the df was clamped to 1 and the fit reported t(1) p-values and confidence + intervals. Estimates and standard errors are still reported; t-statistics, + p-values and intervals are NaN, overall and per event time, with a + `UserWarning`. +- **`StackedDiD` + `survey_design=` without a `psu` column validates its + implicit unit PSUs like explicit ones.** A stratum with a single unit now + warns that it is excluded from variance estimation under + `lonely_psu="remove"`, and a finite-population size below a stratum's unit + count raises `ValueError`; both checks were skipped before. The count is + that of the supplied sample, not of the units that reach the stack. +- **`plot_event_study(results)` no longer rebuilds intervals for rows whose + stored inference is undefined.** A results object passed directly has its + intervals recomputed from the standard error; a row with a finite standard + error and a stored interval with a missing or NaN endpoint (inference + failed closed, for example a + survey design with zero degrees of freedom) now gets none, as the + `aggregate("event_study")` container already did. This holds for dCDH + results (effects and placebos) too. On the matplotlib backend the row is a + point with no error bar. The Plotly backend still fills its band across + the position of such a row when the rows on both sides have intervals. +- `BusinessReport` no longer describes a Taylor-linearized fit with zero + survey degrees of freedom as "replicate-weight" inference whose interval + "remains at the fit's native level". The same applies to a replicate + design that records no degrees of freedom and stored no interval. When the fit stored no interval it + names the variance method and says that none is available; when the fit + did store one (an estimator that falls back to a reference distribution at + zero df) it describes that interval. +- `StackedDiD.fit()` on a panel with no rows raises a `ValueError` that says + so. It raised "cannot convert float NaN to integer", or an `IndexError` + when the survey design named a finite-population column. diff --git a/diff_diff/_reporting_helpers.py b/diff_diff/_reporting_helpers.py index 5e609875c..c87df6ff0 100644 --- a/diff_diff/_reporting_helpers.py +++ b/diff_diff/_reporting_helpers.py @@ -24,7 +24,7 @@ from __future__ import annotations -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, Tuple from diff_diff.results_base import Diagnostic @@ -180,6 +180,46 @@ def is_staggered_ddd(results: Any) -> bool: return results_design(results) == "staggered" +def stacked_control_cutoff_wording(results: Any) -> Tuple[str, str]: + """Wording for a StackedDiD result's clean-control cutoff. + + Returns ``(shift, caveat)``: ``shift`` is appended to the cutoff formula + and ``caveat`` to the sentence that states it. + + Under ``anticipation > 0`` a later adopter responds from + ``A_s - anticipation``, and fits select later-adopter controls with + ``+ anticipation`` in the cutoff. A fit records that on + ``control_cutoff_includes_anticipation``. A result without the record + (saved by diff-diff 4.1.0 or earlier, whose cutoff ignored + ``anticipation``, or built by hand) is described with the cutoff those + versions used and a caveat that the rule is unverified, so that a report + never asserts a comparison set the fit may not have used. + + Both strings are empty when ``anticipation == 0`` (the rule never + changed) and for never-treated controls (no cutoff applies). + """ + if (getattr(results, "anticipation", 0) or 0) <= 0: + return "", "" + if getattr(results, "control_group", None) == "never_treated": + return "", "" + if getattr(results, "control_cutoff_includes_anticipation", None) is True: + return ( + " + anticipation", + " A later adopter responds from ``A_s - anticipation``, which is " + "why the cutoff includes it.", + ) + return ( + "", + " This result does not record which cutoff built its stack, so the " + "rule shown is unverified: it is the one diff-diff 4.1.0 and earlier " + "used, which ignores ``anticipation``. If the result was fitted with " + "one of those versions, a later adopter may be a control while it is " + "already responding (from ``A_s - anticipation``) and the fit should " + "be rerun; later versions add ``+ anticipation`` to the cutoff and " + "record that on the result.", + ) + + def describe_target_parameter(results: Any) -> Dict[str, Any]: """Return the target-parameter block for a fitted result. @@ -427,19 +467,20 @@ def describe_target_parameter(results: Any) -> Dict[str, Any]: # clean_control fallback (a getattr default would silently # misreport the comparison group after the 4.0 removal). clean_control = getattr(results, "control_group", None) + shift, cutoff_caveat = stacked_control_cutoff_wording(results) if clean_control == "never_treated": control_clause = "Controls are the never-treated units (``A_s = infinity``)." elif clean_control == "strict": control_clause = ( "Controls for each sub-experiment ``a`` are units strictly " "untreated across the full pre/post event window " - "(``A_s > a + kappa_post + kappa_pre``)." + f"(``A_s > a + kappa_post + kappa_pre{shift}``).{cutoff_caveat}" ) else: # "not_yet_treated" or unknown -> default rule control_clause = ( "Controls for each sub-experiment ``a`` are units not yet " "treated through the event's post-window " - "(``A_s > a + kappa_post``)." + f"(``A_s > a + kappa_post{shift}``).{cutoff_caveat}" ) # Each scheme aggregates the sub-experiment ATTs with its own cohort # share (Wing et al. 2024, Table 1); a getattr default keeps results diff --git a/diff_diff/business_report.py b/diff_diff/business_report.py index aea83b7b4..628ded880 100644 --- a/diff_diff/business_report.py +++ b/diff_diff/business_report.py @@ -58,6 +58,7 @@ is_staggered_ddd, render_design_reconciliation, results_design, + stacked_control_cutoff_wording, ) from diff_diff.diagnostic_report import DiagnosticReport, DiagnosticReportResults from diff_diff.results_base import Diagnostic, _coverage_level, _coverage_pct @@ -746,12 +747,38 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An "df_survey", getattr(getattr(r, "survey_metadata", None), "df_survey", None), ) + # Whether the fit stored an interval and a p-value, from the + # extracted headline (``ci`` / ``p``), and whether its + # variance comes from replicate weights. + _replicate = ( + getattr(getattr(r, "survey_metadata", None), "replicate_method", None) + is not None + ) + _ci_available = ( + ci is not None + and len(ci) == 2 + and all(b is not None and np.isfinite(b) for b in ci) + ) + _zero_df = isinstance(df_survey, (int, float)) and df_survey == 0 + # A rank-one replicate design stores ``df_survey = None``. + _unrecorded_replicate_df = df_survey is None and _replicate if isinstance(df_survey, (int, float)) and df_survey > 0: inference_label = "finite-df survey" - elif isinstance(df_survey, (int, float)) and df_survey == 0: - # Rank-deficient replicate design: the fit deliberately - # left inference undefined. Preserve (NaN bounds remain NaN). - inference_label = "undefined-df (replicate-weight)" + elif (_zero_df or _unrecorded_replicate_df) and not _ci_available: + # The fit deliberately left inference undefined: a + # rank-deficient replicate design, or a Taylor-linearized + # design with n_PSU - n_strata = 0. Preserve (NaN bounds + # remain NaN) and name the variance method that applies. + inference_label = ( + "undefined-df (replicate-weight)" + if _replicate + else "undefined-df (Taylor-linearized survey)" + ) + elif _zero_df or _unrecorded_replicate_df: + # The fit stored an interval although its design df is + # zero or unrecorded (an estimator that falls back to a + # reference distribution). Describe what the fit stored. + inference_label = "zero-df survey (fallback reference distribution)" else: # Ordinary analytical fit with a finite but unexposed # ``df`` (``DifferenceInDifferences`` / most staggered @@ -761,14 +788,29 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An display_alpha = float(result_alpha) alpha_was_honored = False - alpha_override_caveat = ( - f"Requested alpha ({phrasing_alpha:.2f}) was not honored " - f"for the confidence interval because this fit uses " - f"{inference_label} inference; the displayed CI remains " - f"at the fit's native level " - f"({_coverage_pct(result_alpha)}%). The " - f"significance phrasing still uses the requested alpha." + # Interval availability comes from the stored bounds and + # significance availability from the stored p-value, separately. + _p_stored = p is not None and bool(np.isfinite(p)) + _significance_clause = ( + "The significance phrasing still uses the requested alpha." + if _p_stored + else "The fit stored no p-value, so significance is not assessed." ) + if inference_label.startswith("undefined-df"): + alpha_override_caveat = ( + f"Requested alpha ({phrasing_alpha:.2f}) cannot produce a " + f"confidence interval: this fit has {inference_label} " + "inference with zero degrees of freedom, so no confidence " + "interval is available at any level. " + _significance_clause + ) + else: + alpha_override_caveat = ( + f"Requested alpha ({phrasing_alpha:.2f}) was not honored " + f"for the confidence interval because this fit uses " + f"{inference_label} inference; the displayed CI remains " + f"at the fit's native level " + f"({_coverage_pct(result_alpha)}%). " + _significance_clause + ) unit = self._context.outcome_unit unit_kind = _UNIT_KINDS.get(unit.lower() if unit else "", "unknown") @@ -1543,6 +1585,12 @@ def _describe_assumption(estimator_name: str, results: Any = None) -> Dict[str, # adoption event. REGISTRY.md §StackedDiD (identification / # clean-control rules). control_group = getattr(results, "control_group", None) + # Same cutoff wording as the target-parameter description: under + # anticipation the cutoff and the window both move by `anticipation`. + shift, cutoff_caveat = stacked_control_cutoff_wording(results) + # The window has always widened under anticipation; only the cutoff + # rule depends on which version fitted the result. + anticipating = (getattr(results, "anticipation", 0) or 0) > 0 if control_group == "never_treated": control_clause = ( "controls are restricted to units that are never treated " @@ -1551,17 +1599,22 @@ def _describe_assumption(estimator_name: str, results: Any = None) -> Dict[str, elif control_group == "strict": control_clause = ( "controls for event ``a`` are units satisfying the strict " - "rule ``A_s > a + kappa_post + kappa_pre`` (strictly " + f"rule ``A_s > a + kappa_post + kappa_pre{shift}`` (strictly " "untreated across the full pre- and post-event window)" ) else: - # Default: "not_yet_treated" — A_s > a + kappa_post. + # Default: "not_yet_treated" - A_s > a + kappa_post (+ anticipation). control_clause = ( "controls for event ``a`` are units satisfying ``A_s > a + " - "kappa_post`` (not yet treated through the end of the " + f"kappa_post{shift}`` (not yet treated through the end of the " "event's post-window, so future-treated units can serve " "as controls for earlier events)" ) + window = ( + "``[-kappa_pre - anticipation, +kappa_post]``" + if anticipating + else "``[-kappa_pre, +kappa_post]``" + ) block = { "parallel_trends_variant": "stacked_sub_experiment", "no_anticipation": True, @@ -1570,9 +1623,12 @@ def _describe_assumption(estimator_name: str, results: Any = None) -> Dict[str, "Hollingsworth 2024): within each stacked sub-experiment " "parallel trends holds between the treated cohort and the " "corresponding clean-control set over the event window " - "``[-kappa_pre, +kappa_post]``; " + + window + + "; " + control_clause - + ". Sub-experiments are restricted by IC1 (the event " + + "." + + cutoff_caveat + + " Sub-experiments are restricted by IC1 (the event " "window fits within the available time range) and IC2 " "(at least one clean control exists). The aggregate ATT is " "a weighted sum over sub-experiments, so the common-trends " diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index ae7a98cca..293f820a0 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -1028,6 +1028,8 @@ StackedDiD( **Complete event windows:** a unit enters a sub-experiment only if it is observed at every event time of the window `[-kappa_pre - anticipation, kappa_post]` (the regression contrasts event-time cell means, which needs the same units in every cell; Wing et al. 2024, Section 5.1). On a panel with missing observations the units that are not are excluded from that sub-experiment with a `UserWarning` giving the counts, and the estimand is the trimmed aggregate ATT over the units observed across their whole window. An adoption event left without a complete treated unit or clean control (including one whose window contains a period no unit observes) is dropped with a warning and listed in `results.trimmed_groups`; if none is left `fit()` raises `ValueError`. Under `survey_design=` both the unit-level exclusion and a dropped event raise `NotImplementedError`. `time` must be integer-valued (consecutive integers) with at most one row per unit and period, and `first_treat` an integer period: duplicates, a missing or fractional `time` and a fractional `first_treat` raise `ValueError`. +**Clean controls under anticipation:** with `anticipation=k` a later adopter is a clean control for event `a` only if it starts responding after the window closes: `A_s > a + kappa_post + k` (`"not_yet_treated"`), `A_s > a + kappa_post + kappa_pre + k` (`"strict"`). With the default `anticipation=0` these are the paper's rules. Under `survey_design=`, a fit in which that shift leaves a later cohort out of every sub-experiment raises `NotImplementedError` (its PSUs or strata can drop out of the design). + **fit() parameters:** ```python diff --git a/diff_diff/stacked_did.py b/diff_diff/stacked_did.py index 9603e16b8..bb64d6ef1 100644 --- a/diff_diff/stacked_did.py +++ b/diff_diff/stacked_did.py @@ -18,6 +18,7 @@ """ import copy +import dataclasses import warnings from typing import Any, Dict, List, Optional, Tuple @@ -181,13 +182,23 @@ class StackedDiD(BaseEstimator): unit masses. control_group : str, default="not_yet_treated" How to define clean controls per Appendix A of the paper: - - "not_yet_treated": Units with A_s > a + kappa_post - - "strict": Units with A_s > a + kappa_post + kappa_pre + - "not_yet_treated": Units with A_s > a + kappa_post + anticipation + - "strict": Units with A_s > a + kappa_post + kappa_pre + anticipation - "never_treated": Only units with A_s = infinity + + ``anticipation`` enters because a later adopter responds from + ``A_s - anticipation``; with the default ``anticipation=0`` these are + the paper's rules. cluster : str, default="unit" Clustering level for standard errors: - "unit": Cluster on original unit identifier - "unit_subexp": Cluster on (unit, sub_experiment) pairs + + Under ``survey_design=`` with Taylor-linearized variance the survey + PSU governs: the design's ``psu`` when it names one, otherwise each + original unit. ``"unit_subexp"`` pairs are never used as survey PSUs. + Replicate-weight designs take their variance from the replicate + weights and use no PSU. alpha : float, default=0.05 Significance level for confidence intervals. anticipation : int, default=0 @@ -196,6 +207,7 @@ class StackedDiD(BaseEstimator): - Reference period shifts from e=-1 to e=-1-anticipation - Post-treatment includes anticipation periods (e >= -anticipation) - Event window expands by anticipation pre-periods + - Clean-control cutoffs for later adopters move out by anticipation Consistent with ImputationDiD, TwoStageDiD, SunAbraham. rank_deficient_action : str, default="warn" Action when design matrix is rank-deficient: @@ -486,8 +498,8 @@ def fit( Raises ------ ValueError - If required columns are missing or data validation fails: a - missing or non-integer ``time``, a duplicated ``(unit, time)`` + If required columns are missing or data validation fails: an + empty panel, a missing or non-integer ``time``, a duplicated ``(unit, time)`` row, a non-integer ``first_treat``, or no adoption event with both a treated unit and a clean control observed at every event time of the window. Also under ``weighting="population"`` when a @@ -498,7 +510,10 @@ def fit( Under ``survey_design=`` when a treated or clean-control unit is not observed at every event time of its sub-experiment window, or an adoption event would be dropped for lack of complete units - (removing them would drop their PSUs from the design). + (removing them would drop their PSUs from the design). Also under + ``survey_design=`` with ``anticipation > 0`` when the + anticipation-adjusted clean-control cutoff leaves a later cohort + out of every sub-experiment, for the same reason. Warns ----- @@ -523,6 +538,14 @@ def fit( missing = [c for c in required_cols if c not in data.columns] if missing: raise ValueError(f"Missing columns: {missing}") + if len(data) == 0: + # Before the survey design is resolved: an empty frame has no + # rows to read a design from (an FPC column would index an empty + # array). + raise ValueError( + "StackedDiD.fit() received an empty panel (0 rows): there is " + "nothing to estimate." + ) if self.weighting == "population" and population is None: raise ValueError("population column must be specified when weighting='population'") @@ -572,8 +595,22 @@ def fit( _validate_unit_constant_survey, ) + # A Taylor-linearized design that names no PSU samples UNITS: the unit + # column is declared as the PSU here, before anything is trimmed, so + # the design is validated against the FULL supplied sample (an FPC + # below a stratum's unit count raises, as it does for an explicit + # ``psu``) and the same specification is reused on the stack + # (REGISTRY StackedDiD, survey-PSU Note). + _implicit_unit_psu = ( + isinstance(survey_design, SurveyDesign) + and survey_design.psu is None + and survey_design.replicate_weights is None + ) + _design_for_fit = ( + dataclasses.replace(survey_design, psu=unit) if _implicit_unit_psu else survey_design + ) resolved_survey, survey_weights, survey_weight_type, survey_metadata = ( - _resolve_survey_for_fit(survey_design, data, "analytical") + _resolve_survey_for_fit(_design_for_fit, data, "analytical") ) # Survey columns must be constant within a unit: the regression # contrasts event-time cell means, and a weight that changes over a @@ -659,6 +696,28 @@ def fit( # ---- Trim adoption events (IC1 + IC2) ---- omega_kappa, trimmed = self._trim_adoption_events(omega_A, T_min, T_max, unit_info) + # Under a survey design the anticipation-adjusted clean-control cutoff + # must not take sampled units out of the stack altogether: the design + # is re-resolved on the stacked rows, so their PSUs and strata would + # leave the variance and df_survey (REGISTRY StackedDiD, anticipation + # Note). Refused before any estimate is formed. + if survey_design is not None: + lost = self._units_lost_to_anticipation_cutoff(omega_A, T_min, T_max, unit_info) + if lost: + raise NotImplementedError( + "StackedDiD with survey_design= and " + f"anticipation={self.anticipation}: the clean-control cutoff " + "moves out by the anticipation periods, and that leaves " + f"{sum(lost.values())} unit(s) out of every sub-experiment (" + + ", ".join(f"cohort {int(c)}: {n}" for c, n in lost.items()) + + "). That can take PSUs or strata out of the survey " + "variance and its degrees of freedom, which is not domain " + "estimation, so the fit is refused whenever a sampled unit " + "leaves the stack. Fit without survey_design=, or remove those " + "cohorts from the data yourself and adjust the design " + "accordingly." + ) + # ---- Build stacked dataset ---- # Complete-window rule (REGISTRY StackedDiD Note): a unit enters a # sub-experiment only if it has a row at EVERY integer event time of @@ -1180,7 +1239,6 @@ def _refit_stacked(w_r): survey_metadata = compute_survey_metadata(resolved_stacked, raw_w_stacked) elif resolved_survey is not None: from diff_diff.survey import ( - _inject_cluster_as_psu, _resolve_effective_cluster, compute_survey_metadata, compute_survey_vcov, @@ -1192,7 +1250,31 @@ def _refit_stacked(w_r): # to unit level via ``subset_to_units_by_row_idx``: control units are # duplicated across sub-experiments, so the design must be resolved # at the stacked granularity, not one row per original unit.) - resolved_stacked = survey_design.resolve(stacked_df) + # + # A design without an explicit PSU samples UNITS: each original + # unit is its own PSU, whatever ``cluster`` says. The stacked + # (unit, sub-experiment) pairs are not sampling units - a unit that + # serves in several sub-experiments is still one draw, and the pair + # count moves with the stack. The unit column is therefore declared + # as the PSU BEFORE resolving, so that the implicit PSUs pass + # through the same singleton-stratum and FPC validation as an + # explicit ``survey_design.psu`` (REGISTRY StackedDiD, survey-PSU + # Note). + if _implicit_unit_psu: + if self.cluster == "unit_subexp": + warnings.warn( + "StackedDiD with survey_design= and no survey_design.psu " + "uses each unit as its own PSU for the survey variance; " + "cluster='unit_subexp' does not apply there, because a " + "unit that appears in several sub-experiments is one " + "sampled unit. Name the sampling unit in " + "survey_design.psu to choose a different PSU.", + UserWarning, + stacklevel=2, + ) + resolved_stacked = _design_for_fit.resolve(stacked_df) + else: + resolved_stacked = survey_design.resolve(stacked_df) # Create a copy with composed weights (normalized to sum=n_stacked) resolved_composed = copy.copy(resolved_stacked) @@ -1201,11 +1283,9 @@ def _refit_stacked(w_r): # Original-scale residuals for TSL variance resid_orig = Y - X @ coef - # Inject cluster as PSU when survey design has no explicit PSU - resolved_composed = _inject_cluster_as_psu(resolved_composed, cluster_ids) - - # Resolve effective cluster (PSU overrides user-specified cluster) - _resolve_effective_cluster(resolved_composed, cluster_ids, self.cluster) + if not _implicit_unit_psu: + # Explicit PSU overrides the user-specified cluster. + _resolve_effective_cluster(resolved_composed, cluster_ids, self.cluster) # Compute TSL variance vcov = compute_survey_vcov(X, resid_orig, resolved_composed) @@ -1217,6 +1297,15 @@ def _refit_stacked(w_r): else np.ones(n_stacked, dtype=np.float64) ) survey_metadata = compute_survey_metadata(resolved_composed, raw_w_stacked) + if survey_metadata.df_survey is not None and survey_metadata.df_survey <= 0: + warnings.warn( + "StackedDiD: the survey design has zero degrees of freedom " + "(n_PSU - n_strata = 0), so its variance is not identified " + "for inference. Estimates and standard errors are reported; " + "t-statistics, p-values and confidence intervals are NaN.", + UserWarning, + stacklevel=2, + ) # ---- Extract event study effects ---- # 3.9 (row M-024): the surface is ALWAYS materialized - the @@ -1242,8 +1331,10 @@ def _refit_stacked(w_r): idx = interaction_indices[h] effect = float(coef[idx]) se = float(np.sqrt(max(vcov[idx, idx], 0.0))) + # The design's own df (n_PSU - n_strata), unclamped: at 0 the + # variance is not identified and safe_inference returns NaN. _survey_df = ( - max(survey_metadata.df_survey, 1) + survey_metadata.df_survey if survey_metadata is not None and survey_metadata.df_survey is not None else (0 if _uses_replicate_sd else None) ) @@ -1335,7 +1426,7 @@ def _refit_stacked(w_r): overall_se = np.nan _survey_df_overall = ( - max(survey_metadata.df_survey, 1) + survey_metadata.df_survey if survey_metadata is not None and survey_metadata.df_survey is not None else (0 if _uses_replicate_sd else None) ) @@ -1415,6 +1506,7 @@ def _refit_stacked(w_r): event_study_df=es_df_used, df_convention=self.df_convention, inference_df=_overall_df_used, + control_cutoff_includes_anticipation=True, ) self.is_fitted_ = True @@ -1561,9 +1653,7 @@ def _trim_adoption_events( # a - kappa_pre >= T_min AND a + kappa_post <= T_max # (matches R reference: focalAdoptionTime - kappa_pre >= minTime) # With anticipation: shift window start earlier - lower_ok = (a_int - self.kappa_pre - self.anticipation) >= T_min - upper_ok = (a_int + self.kappa_post) <= T_max - ic1 = lower_ok and upper_ok + ic1 = self._window_fits(a_int, T_min, T_max) # IC2: Clean controls exist ic2 = self._check_clean_controls_exist(a_int, unit_info) @@ -1595,15 +1685,72 @@ def _trim_adoption_events( return omega_kappa, trimmed + def _clean_control_mask(self, a: int, ft: np.ndarray) -> np.ndarray: + """Units that are clean controls for adoption event ``a``. + + A later adopter responds from ``A_s - anticipation`` onward, so it is + clean for event ``a`` only if that date falls after the event window + closes at ``a + kappa_post``: ``A_s - anticipation > a + kappa_post``. + ``"strict"`` also keeps the later adopter's own window, which starts at + ``A_s - kappa_pre - anticipation``, disjoint from this one. With + ``anticipation=0`` these are the rules of Wing et al. (2024), + Appendix A. Never-treated units (``A_s = inf``) satisfy both. + """ + return self._control_mask_at(a, ft, self.anticipation) + + def _control_mask_at(self, a: int, ft: np.ndarray, shift: int) -> np.ndarray: + """The clean-control rule with the cutoff moved out by ``shift`` periods + (``shift = anticipation`` is the rule in force; ``shift = 0`` is the + paper's rule, which :meth:`_units_lost_to_anticipation_cutoff` compares + against).""" + if self.control_group == "not_yet_treated": + return ft > a + self.kappa_post + shift + if self.control_group == "strict": + return ft > a + self.kappa_post + self.kappa_pre + shift + return np.isinf(ft) # never_treated + + def _units_lost_to_anticipation_cutoff( + self, adoption_events: List[Any], T_min: int, T_max: int, unit_info: pd.DataFrame + ) -> Dict[Any, int]: + """Units the anticipation term keeps out of EVERY sub-experiment. + + Compares stack membership under the cutoff in force with membership + under the same cutoff without its ``anticipation`` term: the treated + units of every event that passes IC1 and has a clean control, plus + those controls. Returns ``{cohort: number of units}`` for the units in + the second set only (empty when ``anticipation == 0`` or under + never-treated controls). Completeness of the event windows is not + considered; a survey fit refuses incomplete windows separately. + """ + if self.anticipation == 0 or self.control_group == "never_treated": + return {} + ft = unit_info["_first_treat"].values + + def members(shift: int) -> np.ndarray: + inside = np.zeros(len(ft), dtype=bool) + for a in adoption_events: + a_int = int(a) + if not self._window_fits(a_int, T_min, T_max): + continue + controls = self._control_mask_at(a_int, ft, shift) + if not controls.any(): + continue + inside |= controls | (ft == a) + return inside + + lost = members(0) & ~members(self.anticipation) + cohorts, counts = np.unique(ft[lost], return_counts=True) + return {c: int(n) for c, n in zip(cohorts.tolist(), counts.tolist())} + + def _window_fits(self, a: int, T_min: int, T_max: int) -> bool: + """IC1: the event window ``[a - kappa_pre - anticipation, a + kappa_post]`` + lies within the observed periods. (The paper text states a stricter + lower bound, ``T_min + 1``; the co-author's R code uses ``T_min``.)""" + return (a - self.kappa_pre - self.anticipation) >= T_min and (a + self.kappa_post) <= T_max + def _check_clean_controls_exist(self, a: int, unit_info: pd.DataFrame) -> bool: """Check IC2: whether clean control units exist for adoption event a.""" - ft = unit_info["_first_treat"].values - if self.control_group == "not_yet_treated": - return bool(np.any(ft > a + self.kappa_post)) - elif self.control_group == "strict": - return bool(np.any(ft > a + self.kappa_post + self.kappa_pre)) - else: # never_treated - return bool(np.any(np.isinf(ft))) + return bool(np.any(self._clean_control_mask(a, unit_info["_first_treat"].values))) # ========================================================================= # Sub-experiment construction @@ -1663,13 +1810,8 @@ def _build_sub_experiment( treated_mask = ft == a treated_units = set(unit_ids[treated_mask]) - # Clean control units - if self.control_group == "not_yet_treated": - control_mask = ft > a_int + self.kappa_post - elif self.control_group == "strict": - control_mask = ft > a_int + self.kappa_post + self.kappa_pre - else: # never_treated - control_mask = np.isinf(ft) + # Clean control units (same rule as the IC2 check) + control_mask = self._clean_control_mask(a_int, ft) control_units = set(unit_ids[control_mask]) counts = { diff --git a/diff_diff/stacked_did_results.py b/diff_diff/stacked_did_results.py index 9d9f56a3d..f05cbf0a8 100644 --- a/diff_diff/stacked_did_results.py +++ b/diff_diff/stacked_did_results.py @@ -128,6 +128,13 @@ class StackedDiDResults(BaseResults, AggregationMixin): survey/replicate df on survey fits, else the ``df_convention``-resolved analytical fallback. None when the overall inference used normal theory or failed closed. + control_cutoff_includes_anticipation : bool, optional + True when later-adopter controls were selected with the + anticipation-adjusted cutoff (``A_s > a + kappa_post + anticipation``, + plus ``kappa_pre`` under ``"strict"``), which every fit now does. + None when the result does not record it: a result saved by diff-diff + 4.1.0 or earlier, whose cutoff ignored ``anticipation``. Only matters + when ``anticipation > 0``. """ att: float @@ -184,6 +191,12 @@ class StackedDiDResults(BaseResults, AggregationMixin): # Appended LAST (generated __init__ positional indexes are public API). df_convention: Optional[str] = None inference_df: Optional[float] = None + # Clean-control provenance. True when later-adopter controls were selected + # with the anticipation-adjusted cutoff (every fit since that rule landed). + # None on a result that does not record it: one saved by diff-diff 4.1.0 or + # earlier, whose cutoff ignored ``anticipation``, or one built by hand. The + # report descriptions read it to state the rule the fit actually used. + control_cutoff_includes_anticipation: Optional[bool] = None def __setstate__(self, state: Dict[str, Any]) -> None: """Migrate 3.x pickles: the ``clean_control`` -> ``control_group`` diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index c5bcbeffe..9eba3b4b7 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -339,6 +339,13 @@ def plot_event_study( ci_lower = ci_lower_override[period] assert ci_upper_override is not None ci_upper = ci_upper_override[period] + elif period in undefined_inference: + # The producer's stored inference for this row is undefined (a + # finite SE with a NaN stored interval). No channel may rebuild + # an interval for it from the SE - including the band channel + # when the result carries no band. + ci_lower = np.nan + ci_upper = np.nan elif np.isfinite(std_err) and ( std_err > 0 or (period == reference_period and effect == 0.0 and std_err == 0.0) ): @@ -693,6 +700,35 @@ def _render_event_study_plotly( return fig +def _stored_inference_undefined(entry: Dict[str, Any]) -> bool: + """A row of a raw ``event_study_effects``-style dict whose STORED + inference is undefined: a finite, positive SE with a stored interval that + is not fully finite - either endpoint missing or non-finite (the producer + failed inference closed, e.g. a survey design with zero degrees of + freedom). Reference rows are constraints, not estimates, and never + qualify, and a row that stores no interval at all keeps the legacy + recomputation. The raw routes recompute intervals from the SE, so such + rows are handed back on the pointwise channel as NaN.""" + if entry.get("is_reference", False): + return False + stored_ci = entry.get("conf_int") + stored_se = entry.get("se") + if stored_ci is None or stored_se is None: + return False + try: + lower, upper = stored_ci + except (TypeError, ValueError): + return False + + def _finite(value: Any) -> bool: + try: + return value is not None and bool(np.isfinite(value)) + except TypeError: + return False + + return bool(_finite(stored_se) and stored_se > 0 and not (_finite(lower) and _finite(upper))) + + def _extract_plot_data( results: PlottableResults, periods: Optional[List[Any]], @@ -939,6 +975,8 @@ def _extract_plot_data( ci_lower_override = {} ci_upper_override = {} has_cband = False + # Rows whose stored inference is undefined (see the generic branch). + dcdh_undefined: Dict[Any, float] = {} # Merge placebo horizons (negative keys) if results.placebo_event_study: @@ -949,6 +987,8 @@ def _extract_plot_data( ci_lower_override[h] = entry["cband_conf_int"][0] ci_upper_override[h] = entry["cband_conf_int"][1] has_cband = True + if _stored_inference_undefined(entry): + dcdh_undefined[h] = np.nan # Reference period at 0 effects[0] = 0.0 @@ -963,6 +1003,8 @@ def _extract_plot_data( ci_lower_override[h] = entry["cband_conf_int"][0] ci_upper_override[h] = entry["cband_conf_int"][1] has_cband = True + if _stored_inference_undefined(entry): + dcdh_undefined[h] = np.nan if periods is None: periods = sorted(effects.keys()) @@ -981,8 +1023,8 @@ def _extract_plot_data( True, # inferred ci_lower_override if has_cband else None, ci_upper_override if has_cband else None, - None, - None, + dict(dcdh_undefined) or None, + dict(dcdh_undefined) or None, None, ) @@ -994,6 +1036,14 @@ def _extract_plot_data( ci_upper_override = {} has_cband = False + # Rows whose STORED inference is undefined: this route recomputes + # intervals from the SE, so they are handed back on the pointwise + # channel as NaN and the plot draws their point estimates with no + # interval, with or without an explicit reference period (REGISTRY + # Event Study Plotting). + undefined_lower: Dict[Any, float] = {} + undefined_upper: Dict[Any, float] = {} + for rel_period, effect_data in results.event_study_effects.items(): effects[rel_period] = effect_data["effect"] se[rel_period] = effect_data["se"] @@ -1003,6 +1053,9 @@ def _extract_plot_data( ci_lower_override[rel_period] = cband_ci[0] ci_upper_override[rel_period] = cband_ci[1] has_cband = True + if _stored_inference_undefined(effect_data): + undefined_lower[rel_period] = np.nan + undefined_upper[rel_period] = np.nan if periods is None: periods = sorted(effects.keys()) @@ -1051,8 +1104,8 @@ def _extract_plot_data( reference_inferred, ci_lower_override if has_cband else None, ci_upper_override if has_cband else None, - None, - None, + undefined_lower or None, + undefined_upper or None, None, ) diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 03d394840..39bd25ecf 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -2575,13 +2575,13 @@ records the resolved df per event time as before. - Replicated observations: the same (unit, time) row appears in several sub-experiments (a control serves more than one event) -> handled by clustering at unit level - Duplicate (unit, time) rows in the input, a missing or non-integer `time`, a non-integer finite `first_treat`: `ValueError` at `fit()` (input-grid Note below) - Constant treatment share across sub-exps: Unweighted FE recovers correct estimand (special case, Section 5.5) -- Anticipation > 0: Reference period shifts to e = -1 - anticipation. Post-treatment includes anticipation periods (e >= -anticipation). Window expands by anticipation pre-periods. +- Anticipation > 0: Reference period shifts to e = -1 - anticipation. Post-treatment includes anticipation periods (e >= -anticipation). Window expands by anticipation pre-periods. The clean-control cutoff moves out by `anticipation` periods (anticipation Note below). - Group aggregation: Not supported — pooled stacked regression cannot produce cohort-specific effects. Use CallawaySantAnna or ImputationDiD. *Algorithm (Section 5):* 1. Choose kappa_pre, kappa_post event window 2. Apply IC1 (window fits in data) and IC2 (clean controls exist) to get Omega_kappa -3. For each a in Omega_kappa: build sub-experiment with treated (A_s = a), clean controls (A_s > a + kappa_post), time window [a - kappa_pre, a + kappa_post] (with anticipation: [a - kappa_pre - anticipation, a + kappa_post]), keeping only the units observed at every event time of the window (complete-window Note below); drop the event if no treated unit or no clean control remains +3. For each a in Omega_kappa: build sub-experiment with treated (A_s = a), clean controls (A_s > a + kappa_post; with anticipation: A_s > a + kappa_post + anticipation), time window [a - kappa_pre, a + kappa_post] (with anticipation: [a - kappa_pre - anticipation, a + kappa_post]), keeping only the units observed at every event time of the window (complete-window Note below); drop the event if no treated unit or no clean control remains 4. Stack all sub-experiments vertically 5. Compute Q-weights from unit masses per sub-experiment (Table 1; one formula for the three schemes, treated and control rows both weighted). Every sub-experiment holds the same units at every event time, so for aggregate weighting these equal the observation-count weights of the R reference `compute_weights()`. 6. Run WLS regression of Equation 3 with Q-weights @@ -2602,6 +2602,8 @@ The paper text states a stricter bound (T_min + 1) but the R code by the co-auth IC2_a = 1[exists s with A_s > a + kappa_post + kappa_pre] (strict) IC2_a = 1[exists s with A_s = infinity] (never_treated) +With `anticipation > 0` both finite cutoffs gain `+ anticipation` (anticipation Note below). + **Reference implementation(s):** - R: https://github.com/hollina/stacked-did-weights (`create_sub_exp()`, `compute_weights()`) - No Stata or Python package; Stata estimation via standard `reghdfe` with Q-weight column @@ -2631,6 +2633,9 @@ The paper text states a stricter bound (T_min + 1) but the R code by the co-auth - **Note:** Survey weights compose multiplicatively with Q-weights for StackedDiD; only `weight_type="pweight"` (default) is supported — `fweight` and `aweight` are rejected because Q-weight composition changes weight semantics (non-integer for fweight, non-inverse-variance for aweight) - **Note (treatment weights of the population and sample-share schemes):** Table 1 of the paper weights the TREATED rows as well as the controls: by `(Pop_a^D/Pop^D)/(N_a^D/N^D)` under population weighting and by `((N_a^D+N_a^C)/(N^D+N^C))/(N_a^D/N^D)` under sample-share weighting. The library previously set the treated weight to 1 under every scheme, so under those two schemes the treated arm was aggregated by unit shares and the control arm by population or sample shares; the untreated trends then failed to cancel and the estimate was not the named aggregate. On balanced noiseless panels with cohort-specific effects and a quadratic time trend the largest error in an event-study row was 2.3e-3 (`population`) and 1.0e-1 (`sample_share`); both are exact with the Table 1 weights. Aggregate weighting was correct and is bit-identical. `weighting="population"` now requires the population of the treated units in the stack to be finite, non-negative and constant within a unit (`ValueError`); control units' values are not read. - **Note (survey weights and the corrective weights - library extension; the paper has no survey weights):** with a survey design the unit masses are survey-weighted: `W_a^D` and `W_a^C` are the sums of the treated and control units' survey weights in sub-experiment `a` (the `w_s * pop_s` sum for population weighting), `pi_a` is the corresponding share (`W_a^D / W^D` for aggregate weighting), and `Q_sa = pi_a / (W_a^D / W^D)` or `pi_a / (W_a^C / W^C)`. The regression weight is `Q_sa * w_s`, so both arms carry `pi_a` in survey-weighted mass and the target is the design-weighted trimmed aggregate ATT `sum_a pi_a ATT(a, a+e)`. With uniform weights this is the unweighted estimator. The library previously formed `Q_sa` from raw unit counts, which left the treated arm on survey-weighted shares and the control arm on a mix of both: unit-constant weights of 1.5 / 0.5 / 1 across two cohorts and the controls returned an ATT of 2.46 for a true 2.50 on a noiseless panel. Survey columns must be constant within a unit (`ValueError` otherwise): a weight that changes over a unit's rows changes each event-time cell's weighted composition exactly as a missing row does (2.6174 for a true 2.5 with positive time-varying weights). A sub-experiment with no treated mass, no control mass, or a zero target share (all its units at weight 0; zero treated population) gets `Q = 0` on every row and is left out of the totals: it contributes nothing, its rows stay in the stack so the design is unchanged, it remains in `groups` / `n_sub_experiments` / the unit counts (which describe the stack), and `fit()` names it in a `UserWarning`. The Taylor-linearized variance conditions on the realized shares, as the analytical cluster-robust variance conditions on the unit-count shares; replicate refits recompute `Q` from each replicate's weights, and a replicate with no effective sub-experiment is dropped and counted. Cross-checked against an independent R implementation of the same formula with `survey::svyglm` (`benchmarks/R/benchmark_survey_estimators.R`, scenario S2: ATT agrees to 1e-11). +- **Note (clean controls under anticipation):** library extension; Wing et al. (2024) assume no anticipation (Assumption 1) and state the clean-control rules for that case. With `anticipation = k > 0` a later adopter starts responding at `A_s - k`, so it is a clean control for event `a` only if that date falls after the event window closes: `A_s - k > a + kappa_post`, i.e. `A_s > a + kappa_post + k` (`not_yet_treated`), and `A_s > a + kappa_post + kappa_pre + k` (`strict`, which keeps the later cohort's own window, now starting at `A_s - kappa_pre - k`, disjoint from this one). `never_treated` is unaffected. IC2 and the stack builder apply the same rule through one helper, so an event whose only later cohort is inside the cutoff is trimmed. This matches the not-yet-treated rule of `CallawaySantAnna` under anticipation. Before this rule the cutoff ignored `anticipation`: on a noiseless balanced panel (periods 0-8, equal-sized cohorts 3, 6 and never-treated, an effect of 2 starting one period before adoption, `kappa_pre = kappa_post = 2`, `anticipation = 1`) cohort 6 was a control for cohort 3 through period 5 while already responding, giving 1.5 at event time 2 and an overall ATT of 1.875; both are now 2 exactly. Under `strict` a control was responding inside the window only when `anticipation > kappa_pre`, but the control set changes for any later cohort with `a + kappa_post + kappa_pre < A_s <= a + kappa_post + kappa_pre + anticipation`, which the new cutoff drops so that the cohort's own window (which now starts `anticipation` periods earlier) stays disjoint from this one. Fits with the default `anticipation = 0` are unchanged. Under `survey_design=` a fit is REFUSED (`NotImplementedError`, before any estimate is formed) when the `anticipation` term leaves a unit out of every sub-experiment that the cutoff without it would have placed in the stack: the survey design is re-resolved on the stacked rows, so that unit's PSU or stratum can leave the Taylor-linearized meat and `df_survey`. The check is on units, not PSUs: a fit is refused even when the lost units share every PSU and stratum with units that stay (a conservative rule, lifted together with the others). Measured on a stratified census (periods 0-8, cohorts 3, 8 and never-treated, three strata with two single-unit PSUs per cohort, FPC 6 per stratum, `strict`, `kappa_pre = kappa_post = 2`, `anticipation = 1`): without the refusal the fit used 12 of 18 PSUs and returned SE 0.136 with 9 survey df, where the full design gives SE 0 with 15 df. The refusal is lifted with full-design (domain) inference, tracked in `TODO.md` with the other StackedDiD survey refusals. Each fit records the rule on `StackedDiDResults.control_cutoff_includes_anticipation` (`True`); a result saved by diff-diff 4.1.0 or earlier has no such record (`None` after loading). The report descriptions (`describe_target_parameter`, the `BusinessReport` assumption block) state the adjusted cutoff only for a result that records it. For a not-yet-treated or strict result with `anticipation > 0` and no record they show the earlier cutoff, label it unverified and say to rerun the fit if it came from one of those versions. +- **Note (survey PSU without an explicit `psu`):** applies to Taylor-linearized variance only (replicate-weight designs take their variance from the replicate weights and use no PSU). Under `survey_design=` with no `psu` column the Taylor-linearized variance treats each ORIGINAL unit as its own PSU, for either value of `cluster`. `cluster="unit_subexp"` does not apply to the survey variance (a `UserWarning` says so): a unit that serves in several sub-experiments is one sampled unit, and the number of `(unit, sub-experiment)` pairs moves with the stack, so pairs are not sampling units and an FPC cannot be checked against them. An explicit `survey_design.psu` still overrides `cluster`, as before. Before this rule `cluster="unit_subexp"` injected the pairs as PSUs. Measured on periods 0-8, cohorts 3, 6 and never-treated, three strata with two units per cohort, FPC 8 per stratum, `kappa_pre = kappa_post = 2`, `anticipation = 1`, treatment effects of 1.5 and 2.5 within each cohort and stratum: the pairs gave 24 PSUs (8 per stratum, read as a census against the FPC), SE 0 and 21 survey df, where the six sampled units per stratum give SE 0.07906 and 15 df, which is what the fit now returns and what `psu=` returns. The unit column is declared as the PSU before the design is resolved - first on the supplied panel, then on the stack - so implicit unit PSUs pass through the same validation as an explicit `psu`, against the FULL supplied sample and not only the units that reach the stack: a stratum with a single PSU warns under `lonely_psu="remove"`, and an FPC below a stratum's PSU count raises `ValueError` (both were skipped when the PSU was injected after resolution). Fits with the default `cluster="unit"` on designs that pass those checks, and fits with an explicit `psu`, are unchanged. +- **Note (zero survey degrees of freedom):** when the Taylor-linearized design has `df_survey = n_PSU - n_strata = 0` (for example one PSU per stratum under `lonely_psu="adjust"`), the variance is not identified for inference. `fit()` reports the estimates and standard errors, sets every t-statistic, p-value and confidence interval to NaN (overall and per event time) and warns. Before this rule the df was clamped to 1 and the fit reported t(1) inference: p = 0.079 with a finite interval on a six-unit, six-stratum panel. `SunAbraham` still clamps the df to 1 for its aggregates; aligning it is tracked in `TODO.md`. - **Note (complete event windows):** a unit enters sub-experiment `a` only if it has an observation at every integer event time of the window `[-kappa_pre - anticipation, kappa_post]`. Equation 3's coefficients are contrasts of (treated x event-time) and (control x event-time) cell means, and those equal within-unit changes only when the same units sit in every cell. Wing et al. (2024) build the stack that way (Section 5.1: "In each sub-experiment, each unit will be observed for kappa_pre + kappa_post + 1 time periods"), define `N_a^D` / `N_a^C` as unit counts fixed over event time, and prove that the Q-weighted regression recovers `theta_kappa^e` under that fixed composition; the paper prescribes nothing for missing rows. On a ragged panel `fit()` therefore excludes, sub-experiment by sub-experiment, the units that are not observed across the whole window (a control can be kept in one sub-experiment and excluded from another) and emits one `UserWarning` with the per-event "kept of eligible" counts. The estimand is then the trimmed aggregate ATT over the units observed across their whole window: `N_a^D` counts those units, and `n_treated_units`, `n_control_units` and `stacked_data` reflect them. An adoption event left without a complete treated unit or a complete clean control - including an event whose window contains a calendar period that no unit observes - is dropped with a `UserWarning` naming the reason and is reported in `trimmed_groups`, not `groups`. If no event is left `fit()` raises `ValueError`; when integer periods between the first and last are absent from the panel the message names them and advises re-indexing `time` to consecutive integers (the list is computed only for spans of at most 10,000 periods, so a datetime-coded column is reported by its span). Because every sub-experiment then holds the same units at every event time, the observation-count `aggregate` Q-weights equal the paper's unit-count formula exactly. Before this rule a ragged panel returned shifted estimates with no warning: on a noiseless panel with a true ATT of 2.5 (cohorts 4 and 6, `kappa_pre = kappa_post = 2`), one never-treated observation missing gave 2.4978, 5% of rows missing at random 2.6020, half of one cohort missing its `e = -1` row 2.2965, and a calendar period absent for every unit 1.7667 or 2.6833 depending on the period; all of these now return 2.5 exactly or raise. - **Note (complete event windows are REFUSED under `survey_design=`):** when `survey_design=` is supplied and an eligible treated or clean-control unit is not observed across its window, `fit()` raises `NotImplementedError` before any row is removed. Excluding the unit would remove its PSUs and strata from the Taylor-linearized meat and from `df_survey = n_PSU - n_strata`, which is naive subsetting, not domain estimation (the SunAbraham and WooldridgeDiD survey refusals follow the same rule). An adoption event that cannot be realized (no complete treated unit, no complete clean control, or a window containing a period the whole panel lacks) is refused the same way, since dropping it would take the cohort's PSUs out of the design; when no event at all can be formed the `ValueError` above takes precedence. Survey fits on panels that need neither are not affected by this refusal (their estimates do change when survey weights differ across cohorts: survey-weights Note above). Design-based support is tracked in `TODO.md`. - **Note (input grid validation):** `fit()` raises `ValueError` for a missing or non-integer `time`, a duplicated `(unit, time)` row, and a non-integer finite `first_treat`. Event times are the integer offsets `time - a` and each unit contributes one row per event time; such rows were previously dropped silently (missing `time`), absorbed into the reference category (fractional `time`), double-counted (duplicates) or shifted by integer truncation of the adoption period (fractional `first_treat`). @@ -7296,6 +7301,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 (undefined stored inference on the raw-results routes):** a results object passed + directly (not its `aggregate("event_study")` container) has its intervals recomputed + from the SE, on the generic `event_study_effects` route and on the dCDH route (effects + and placebo horizons). A row whose STORED interval is not fully finite (either endpoint missing or + non-finite) while its SE is finite and positive - inference the producer failed closed, such as a survey design with zero + degrees of freedom - is exempt: no interval is recomputed for it, on the pointwise or + the band channel, with or without an explicit `reference_period=`. Before this rule a + zero-df `StackedDiDResults` plotted directly showed 95% normal-theory intervals for + estimates whose inference was undefined. The auto-inferred reference row keeps its + zero-width constraint bar. On the matplotlib backend such a row is a point with no + error bar. The plotly backend follows its existing NaN-interval convention (zero-SE + Note below): the row is filtered out of the band polygon, so when it sits between rows + that do have intervals the fill still passes over its position. Breaking the band + there is tracked in `TODO.md`. - **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 diff --git a/tests/test_business_report.py b/tests/test_business_report.py index 57eeae5cc..15fc1c23b 100644 --- a/tests/test_business_report.py +++ b/tests/test_business_report.py @@ -36,6 +36,8 @@ CallawaySantAnna, DiagnosticReport, DifferenceInDifferences, + StackedDiD, + StackedDiDResults, SyntheticControl, SyntheticDiD, TwoWayFixedEffects, @@ -43,6 +45,7 @@ generate_factor_data, generate_staggered_data, ) +from diff_diff._reporting_helpers import describe_target_parameter from diff_diff.business_report import BUSINESS_REPORT_SCHEMA_VERSION warnings.filterwarnings("ignore") @@ -1846,6 +1849,167 @@ def test_not_yet_treated_names_subexperiment_contract(self): assert a["control_group"] == "not_yet_treated" assert "clean_control" not in a + @pytest.mark.parametrize( + "control_group, cutoff", + [ + ("not_yet_treated", "``A_s > a + kappa_post + anticipation``"), + ("strict", "``A_s > a + kappa_post + kappa_pre + anticipation``"), + ], + ) + def test_anticipation_moves_the_cutoff_and_the_window(self, control_group, cutoff): + """A result that records the anticipation-adjusted cutoff: the + assumption block and the target-parameter description both state it, + with the widened window and no refit caveat.""" + stub = self._stub(control_group) + stub.anticipation = 1 + stub.control_cutoff_includes_anticipation = True + desc = BusinessReport(stub, auto_diagnostics=False).to_dict()["assumption"]["description"] + assert cutoff in desc + assert "``[-kappa_pre - anticipation, +kappa_post]``" in desc + assert "unverified" not in desc + # the shared anticipation post-processing replaces the strict clause + assert "Also assumes no anticipation." not in desc + assert "Anticipation is allowed" in desc + assert cutoff in describe_target_parameter(stub)["definition"] + + def test_no_anticipation_keeps_the_paper_wording(self): + stub = self._stub("not_yet_treated") + stub.anticipation = 0 + desc = BusinessReport(stub, auto_diagnostics=False).to_dict()["assumption"]["description"] + assert "``[-kappa_pre, +kappa_post]``" in desc + assert "+ anticipation" not in desc and "unverified" not in desc + assert "Also assumes no anticipation." in desc + + def test_never_treated_with_anticipation_has_no_cutoff_caveat(self): + stub = self._stub("never_treated") + stub.anticipation = 1 + desc = BusinessReport(stub, auto_diagnostics=False).to_dict()["assumption"]["description"] + assert "``A_s = infinity``" in desc and "unverified" not in desc + assert "``[-kappa_pre - anticipation, +kappa_post]``" in desc + + def test_reports_distinguish_a_current_fit_from_one_saved_before_the_cutoff_fix(self): + """Two real results on the same panel. The current fit excludes the + anticipating later cohort and its reports state the adjusted cutoff. + A result as an earlier version saved it (the old cutoff, no record of + the rule) keeps that cohort as a control, and its reports must not + claim the adjusted cutoff.""" + import pickle + + rows = [] + for unit in range(90): + g = [3, 6, np.inf][unit % 3] + for t in range(9): + responding = np.isfinite(g) and t >= g - 1 + rows.append((unit, t, g, 0.5 * t + (unit % 7) + (2.0 if responding else 0.0))) + panel = pd.DataFrame(rows, columns=["unit", "period", "first_treat", "outcome"]) + keys = dict(outcome="outcome", unit="unit", time="period", first_treat="first_treat") + + def control_cohorts(res): + stacked = res.stacked_data + sub = stacked[(stacked["_sub_exp"] == 3) & (stacked["_D_sa"] == 0)] + return sorted(float(g) for g in sub["first_treat"].unique()) + + current = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1).fit(panel, **keys) + assert current.control_cutoff_includes_anticipation is True + assert pickle.loads(pickle.dumps(current)).control_cutoff_includes_anticipation is True + assert control_cohorts(current) == [np.inf] + assert current.att == pytest.approx(2.0, abs=1e-10) + + class _OldCutoff(StackedDiD): + def _clean_control_mask(self, a, ft): + return ft > a + self.kappa_post + + legacy_fit = _OldCutoff(kappa_pre=2, kappa_post=2, anticipation=1).fit(panel, **keys) + state = dict(legacy_fit.__dict__) + del state["control_cutoff_includes_anticipation"] # earlier versions had no such field + legacy = StackedDiDResults.__new__(StackedDiDResults) + legacy.__setstate__(state) + legacy = pickle.loads(pickle.dumps(legacy)) + assert legacy.control_cutoff_includes_anticipation is None + assert control_cohorts(legacy) == [6.0, np.inf] + assert legacy.att == pytest.approx(1.875, abs=1e-10) + + adjusted = "``A_s > a + kappa_post + anticipation``" + for result, is_current in ((current, True), (legacy, False)): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + block = BusinessReport(result, auto_diagnostics=False).to_dict() + target = DiagnosticReport(result).to_dict()["target_parameter"]["definition"] + for text in (block["assumption"]["description"], target): + assert (adjusted in text) is is_current + assert ("unverified" in text) is (not is_current) + assert ("should be rerun" in text) is (not is_current) + + def test_zero_survey_df_fit_is_not_called_replicate_weight(self): + """A Taylor-linearized StackedDiD fit with zero survey degrees of + freedom has NaN inference. The alpha caveat must name the variance + method correctly and say that no interval is available, not that the + displayed interval keeps its native coverage.""" + from diff_diff import SurveyDesign + + cohorts = [3, 3, np.inf, np.inf, np.inf, np.inf] + rows = [] + for unit, g in enumerate(cohorts): + for t in range(9): + effect = 2.0 + 0.5 * unit if (np.isfinite(g) and t >= g) else 0.0 + y = 0.5 * t + unit + effect + 0.3 * ((unit * 7 + t * 3) % 5) + rows.append((unit, t, g, y, unit, 1.0)) + panel = pd.DataFrame( + rows, columns=["unit", "period", "first_treat", "outcome", "stratum", "w"] + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fit = StackedDiD(kappa_pre=2, kappa_post=2).fit( + panel, + outcome="outcome", + unit="unit", + time="period", + first_treat="first_treat", + survey_design=SurveyDesign(weights="w", strata="stratum", lonely_psu="adjust"), + ) + report = json.dumps(BusinessReport(fit, alpha=0.10, auto_diagnostics=False).to_dict()) + assert fit.survey_metadata.df_survey == 0 and np.isnan(fit.conf_int[0]) + assert "undefined-df (Taylor-linearized survey)" in report + assert "replicate-weight" not in report + assert "no confidence interval is available at any level" in report + assert "the displayed CI remains" not in report + + def test_zero_df_caveat_follows_the_stored_inference(self): + """SunAbraham still reports inference at zero survey df (a t(1) + fallback, tracked in TODO.md). The caveat must describe that stored + interval, not claim that none is available.""" + from diff_diff import SunAbraham, SurveyDesign + + cohorts = [3, 3, np.inf, np.inf, np.inf, np.inf] + rows = [] + for unit, g in enumerate(cohorts): + for t in range(9): + effect = 2.0 + 0.5 * unit if (np.isfinite(g) and t >= g) else 0.0 + y = 0.5 * t + unit + effect + 0.3 * ((unit * 7 + t * 3) % 5) + rows.append((unit, t, g, y, unit, 1.0, unit)) + panel = pd.DataFrame( + rows, columns=["unit", "period", "first_treat", "outcome", "stratum", "w", "psu"] + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fit = SunAbraham().fit( + panel, + outcome="outcome", + unit="unit", + time="period", + first_treat="first_treat", + survey_design=SurveyDesign( + weights="w", strata="stratum", psu="psu", lonely_psu="adjust" + ), + ) + report = json.dumps(BusinessReport(fit, alpha=0.10, auto_diagnostics=False).to_dict()) + assert fit.survey_metadata.df_survey == 0 + if not all(np.isfinite(b) for b in fit.conf_int): + pytest.skip("SunAbraham no longer reports inference at zero survey df") + assert "zero-df survey (fallback reference distribution)" in report + assert "the displayed CI remains" in report + assert "no confidence interval is available at any level" not in report + def test_strict_names_strict_rule(self): desc = BusinessReport(self._stub("strict"), auto_diagnostics=False).to_dict()["assumption"][ "description" @@ -3983,6 +4147,119 @@ def test_analytical_did_result_preserves_native_ci(self): topics = {c.get("topic") for c in br.caveats()} assert "alpha_override_preserved" in topics + @pytest.mark.parametrize("df_survey", [0, None]) + def test_replicate_design_without_an_interval_says_none_is_available(self, df_survey): + """A replicate design whose df is undefined stores ``df_survey = 0`` + (rank-deficient) or ``None`` (rank one). With NaN bounds the alpha + caveat must say that no interval is available, not that the displayed + one keeps its native coverage.""" + from types import SimpleNamespace + + class _ReplicateStub: + pass + + stub = _ReplicateStub() + stub.att = 1.0 + stub.se = 0.3 + stub.p_value = float("nan") + stub.conf_int = (float("nan"), float("nan")) + stub.alpha = 0.05 + stub.n_obs = 100 + stub.n_treated = 40 + stub.n_control = 60 + stub.inference_method = "analytical" + stub.survey_metadata = SimpleNamespace( + weight_type="replicate", + replicate_method="JK1", + effective_n=80.0, + design_effect=1.25, + sum_weights=100.0, + n_strata=None, + n_psu=None, + df_survey=df_survey, + ) + report = json.dumps(BusinessReport(stub, alpha=0.10, auto_diagnostics=False).to_dict()) + assert "undefined-df (replicate-weight)" in report + assert "no confidence interval is available at any level" in report + assert "the displayed CI remains" not in report + + @pytest.mark.parametrize("df_survey", [0, None]) + def test_replicate_design_with_an_interval_but_no_p_value(self, df_survey): + """Interval availability follows the stored bounds and significance + availability the stored p-value. A fit that stored finite bounds and a + NaN p-value must not be told that no interval is available.""" + from types import SimpleNamespace + + class _ReplicateStub: + pass + + stub = _ReplicateStub() + stub.att = 1.0 + stub.se = 0.3 + stub.p_value = float("nan") + stub.conf_int = (0.4, 1.6) + stub.alpha = 0.05 + stub.n_obs = 100 + stub.n_treated = 40 + stub.n_control = 60 + stub.inference_method = "analytical" + stub.survey_metadata = SimpleNamespace( + weight_type="replicate", + replicate_method="JK1", + effective_n=80.0, + design_effect=1.25, + sum_weights=100.0, + n_strata=None, + n_psu=None, + df_survey=df_survey, + ) + br = BusinessReport(stub, alpha=0.10, auto_diagnostics=False) + headline = br.to_dict()["headline"] + assert headline["ci_lower"] == pytest.approx(0.4) + assert headline["ci_upper"] == pytest.approx(1.6) + report = json.dumps(br.to_dict()) + assert "no confidence interval is available" not in report + assert "the displayed CI remains" in report + assert "The fit stored no p-value, so significance is not assessed." in report + + def test_no_interval_but_a_stored_p_value_keeps_significance(self): + """Zero survey df, NaN bounds, a stored p = 0.07, requested alpha 0.10: + the caveat says no interval can be produced and that significance + still uses the requested alpha - it does not say alpha "does not + apply" and then use it.""" + from types import SimpleNamespace + + class _Stub: + pass + + stub = _Stub() + stub.att = 1.0 + stub.se = 0.3 + stub.p_value = 0.07 + stub.conf_int = (float("nan"), float("nan")) + stub.alpha = 0.05 + stub.n_obs = 100 + stub.n_treated = 40 + stub.n_control = 60 + stub.inference_method = "analytical" + stub.survey_metadata = SimpleNamespace( + weight_type="pweight", + replicate_method=None, + effective_n=80.0, + design_effect=1.25, + sum_weights=100.0, + n_strata=6, + n_psu=6, + df_survey=0, + ) + br = BusinessReport(stub, alpha=0.10, auto_diagnostics=False) + report = json.dumps(br.to_dict()) + assert "cannot produce a confidence interval" in report + assert "no confidence interval is available at any level" in report + assert "The significance phrasing still uses the requested alpha." in report + assert "does not apply" not in report + assert br.to_dict()["headline"]["is_significant"] is True + def test_undefined_df_survey_stub_does_not_invent_finite_ci(self): """When the fit's native inference returned NaN (rank-deficient replicate design: ``df_survey = 0``), BR must not recompute a diff --git a/tests/test_stacked_did.py b/tests/test_stacked_did.py index 661ea5fb3..0598f0fc3 100644 --- a/tests/test_stacked_did.py +++ b/tests/test_stacked_did.py @@ -435,6 +435,386 @@ def test_never_treated_no_nevertreated_raises(self, no_never_treated_data): ) +# ============================================================================= +# TestCleanControlAnticipation +# ============================================================================= + + +def _anticipation_panel(cohorts, lead, n_periods, effect=2.0, n_per_group=30): + """Noiseless balanced panel: equal-sized groups adopting at ``cohorts`` + (``np.inf`` = never treated), with a constant effect that starts ``lead`` + periods BEFORE the recorded adoption date.""" + rows = [] + for unit in range(n_per_group * len(cohorts)): + g = cohorts[unit % len(cohorts)] + for t in range(n_periods): + responding = np.isfinite(g) and t >= g - lead + rows.append((unit, t, g, 0.5 * t + (unit % 7) + (effect if responding else 0.0))) + return pd.DataFrame(rows, columns=["unit", "period", "first_treat", "outcome"]) + + +def _control_cohorts(results): + stacked = results.stacked_data + return { + float(a): sorted(float(g) for g in sub.loc[sub["_D_sa"] == 0, "first_treat"].unique()) + for a, sub in stacked.groupby("_sub_exp") + } + + +_ANT_FIT = dict(outcome="outcome", unit="unit", time="period", first_treat="first_treat") + + +class TestCleanControlAnticipation: + """A later adopter responds from ``A_s - anticipation``, so it is a clean + control for event ``a`` only if ``A_s - anticipation > a + kappa_post``.""" + + def test_anticipating_later_cohort_is_not_a_control(self): + """Cohort 6 responds from period 5, inside cohort 3's window [0, 5]. + Using it as a control biased event time 2 to 1.5 and the overall ATT + to 1.875 where the truth is 2 at every included horizon.""" + data = _anticipation_panel([3, 6, np.inf], lead=1, n_periods=9) + results = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1).fit(data, **_ANT_FIT) + assert _control_cohorts(results) == {3.0: [np.inf], 6.0: [np.inf]} + es = results.aggregate("event_study").to_dataframe().set_index("event_time") + assert es.loc[2, "att"] == pytest.approx(2.0, abs=1e-10) + # anticipation periods count as post-treatment: h in {-1, 0, 1, 2} + np.testing.assert_allclose(es.loc[[-1, 0, 1, 2], "att"].to_numpy(), 2.0, atol=1e-10) + assert es.loc[-3, "att"] == pytest.approx(0.0, abs=1e-10) + assert results.att == pytest.approx(2.0, abs=1e-10) + + def test_later_cohort_far_enough_away_stays_a_control(self): + """Cohort 7 responds from period 6, after cohort 3's window closes.""" + data = _anticipation_panel([3, 7, np.inf], lead=1, n_periods=10) + results = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1).fit(data, **_ANT_FIT) + assert _control_cohorts(results) == {3.0: [7.0, np.inf], 7.0: [np.inf]} + assert results.att == pytest.approx(2.0, abs=1e-10) + + def test_no_anticipation_keeps_the_paper_rule(self): + """``anticipation=0``: A_s > a + kappa_post, so cohort 6 is a control + for cohort 3 (Wing et al. 2024, Appendix A).""" + data = _anticipation_panel([3, 6, np.inf], lead=0, n_periods=9) + results = StackedDiD(kappa_pre=2, kappa_post=2).fit(data, **_ANT_FIT) + assert _control_cohorts(results) == {3.0: [6.0, np.inf], 6.0: [np.inf]} + assert results.att == pytest.approx(2.0, abs=1e-10) + + def test_strict_adds_its_separation_on_top(self): + """``strict`` with anticipation longer than ``kappa_pre``: cohort 8 + passes A_s > a + kappa_post + kappa_pre = 7 but responds from period 6, + inside cohort 4's window [1, 6].""" + data = _anticipation_panel([4, 8, np.inf], lead=2, n_periods=12) + results = StackedDiD(kappa_pre=1, kappa_post=2, anticipation=2, control_group="strict").fit( + data, **_ANT_FIT + ) + assert _control_cohorts(results) == {4.0: [np.inf], 8.0: [np.inf]} + assert results.att == pytest.approx(2.0, abs=1e-10) + + def test_inclusion_check_uses_the_same_rule(self): + """IC2 and the stack builder agree. With no never-treated units, cohort + 3's only candidate control is the later cohort: at 7 it qualifies and + the last cohort is trimmed; at 6 nothing qualifies and the fit raises.""" + kept = _anticipation_panel([3, 7], lead=1, n_periods=10) + with pytest.warns(UserWarning, match="Trimmed 1 adoption event"): + results = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1).fit(kept, **_ANT_FIT) + assert [float(g) for g in results.groups] == [3.0] + assert [float(g) for g in results.trimmed_groups] == [7.0] + assert _control_cohorts(results) == {3.0: [7.0]} + assert results.att == pytest.approx(2.0, abs=1e-10) + + none_left = _anticipation_panel([3, 6], lead=1, n_periods=9) + with pytest.raises(ValueError, match="adoption events were trimmed"): + StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1).fit(none_left, **_ANT_FIT) + + +class TestCleanControlAnticipationSurvey: + """Under ``survey_design=`` the design is re-resolved on the stacked rows. + If the anticipation term takes a later cohort out of every sub-experiment, + its PSUs and strata would leave the variance, so the fit is refused.""" + + @staticmethod + def _census(lead): + """Stratified census: 3 strata x cohorts (3, 8, never) x 2 single-unit + PSUs, FPC = 6 per stratum. Cohort 3's effects alternate 1.5 / 2.5 within + a stratum and start ``lead`` periods before adoption.""" + rows, unit = [], 0 + for stratum in range(3): + for g in (3, 8, np.inf): + for k in range(2): + effect = 1.5 if k == 0 else 2.5 + for t in range(9): + responding = g == 3 and t >= g - lead + y = 0.5 * t + unit % 5 + (effect if responding else 0.0) + rows.append((unit, t, g, y, stratum, unit, 1.0, 6)) + unit += 1 + return pd.DataFrame( + rows, + columns=["unit", "period", "first_treat", "outcome", "stratum", "psu", "w", "N"], + ) + + @staticmethod + def _design(): + from diff_diff import SurveyDesign + + return SurveyDesign(weights="w", strata="stratum", psu="psu", fpc="N") + + def test_refused_when_the_cutoff_removes_a_cohort_from_the_stack(self): + """strict, kappa 2/2, anticipation=1: cohort 8 is trimmed as an event + (its window ends at 10) and the adjusted cutoff (> 8) also drops it as + a control for cohort 3, so its six PSUs would leave the design.""" + data = self._census(lead=1) + est = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1, control_group="strict") + with pytest.raises(NotImplementedError, match=r"cohort 8: 6"): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + est.fit(data, survey_design=self._design(), **_ANT_FIT) + # the unweighted fit proceeds and excludes cohort 8 from the controls + with pytest.warns(UserWarning, match="Trimmed 1 adoption event"): + plain = est.fit(data, **_ANT_FIT) + assert _control_cohorts(plain) == {3.0: [np.inf]} + assert plain.att == pytest.approx(2.0, abs=1e-10) + + def test_supported_when_no_unit_is_lost(self): + """anticipation=0: cohort 8 passes the strict cutoff (> 7) and stays a + control, so every PSU is in the stack. A census has zero design + variance: 18 PSUs, 15 survey df, SE 0 and NaN inference.""" + data = self._census(lead=0) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + results = StackedDiD(kappa_pre=2, kappa_post=2, control_group="strict").fit( + data, survey_design=self._design(), **_ANT_FIT + ) + assert _control_cohorts(results) == {3.0: [8.0, np.inf]} + assert results.survey_metadata.n_psu == 18 + assert results.survey_metadata.df_survey == 15 + assert results.att == pytest.approx(2.0, abs=1e-10) + assert results.se == pytest.approx(0.0, abs=1e-12) + assert np.isnan(results.t_stat) and np.isnan(results.p_value) + assert all(np.isnan(b) for b in results.conf_int) + + def test_not_refused_when_the_cutoff_changes_nothing(self): + """anticipation=1 with a later cohort far enough away (and with + never-treated controls): no unit leaves the stack, so the survey fit + runs.""" + rows, unit = [], 0 + for stratum in range(3): + for g in (3, np.inf): + for k in range(3): + for t in range(9): + y = 0.5 * t + unit % 5 + (2.0 if (g == 3 and t >= 2) else 0.0) + 0.1 * k * t + rows.append((unit, t, g, y, stratum, unit, 1.0, 12)) + unit += 1 + data = pd.DataFrame( + rows, + columns=["unit", "period", "first_treat", "outcome", "stratum", "psu", "w", "N"], + ) + est = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1) + assert ( + est._units_lost_to_anticipation_cutoff( + [3], 0, 8, pd.DataFrame({"_first_treat": [3.0, np.inf]}) + ) + == {} + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + results = est.fit(data, survey_design=self._design(), **_ANT_FIT) + assert results.survey_metadata.n_psu == 18 + assert np.isfinite(results.att) + + @staticmethod + def _sampled_panel(): + """3 strata x cohorts (3, 6, never) x 2 units, FPC = 8 per stratum (a + sample of 6 from 8). Effects of 1.5 / 2.5 within each cohort and + stratum, starting one period before adoption.""" + rows, unit = [], 0 + for stratum in range(3): + for g in (3, 6, np.inf): + for k in range(2): + effect = 1.5 if k == 0 else 2.5 + for t in range(9): + responding = np.isfinite(g) and t >= g - 1 + y = 0.5 * t + unit % 5 + (effect if responding else 0.0) + rows.append((unit, t, g, y, stratum, unit, 1.0, 8)) + unit += 1 + return pd.DataFrame( + rows, + columns=["unit", "period", "first_treat", "outcome", "stratum", "unit_id", "w", "N"], + ) + + @pytest.mark.parametrize( + "cluster, psu, warning", + [ + ("unit", None, None), + ("unit_subexp", None, "uses each unit as its own PSU"), + ("unit_subexp", "unit_id", "Both survey_design.psu and cluster"), + ], + ) + def test_implicit_survey_psu_is_the_original_unit(self, cluster, psu, warning): + """With no ``psu`` column each ORIGINAL unit is the PSU, for either + ``cluster``. (unit, sub-experiment) pairs are not sampling units: here + they number 8 per stratum, which read against FPC = 8 as a census and + gave SE 0 with 21 df. Cohort 6 leaves cohort 3's control pool under + the anticipation cutoff but stays in the stack as a treated cohort, so + nothing is refused.""" + from diff_diff import SurveyDesign + + data = self._sampled_panel() + design = SurveyDesign( + weights="w", strata="stratum", fpc="N", **({"psu": psu} if psu else {}) + ) + est = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1, cluster=cluster) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + results = est.fit(data, survey_design=design, **_ANT_FIT) + messages = [str(w.message) for w in caught] + if warning is None: + assert not any("PSU" in m for m in messages) + else: + assert any(warning in m for m in messages) + assert _control_cohorts(results) == {3.0: [np.inf], 6.0: [np.inf]} + assert results.stacked_data["unit"].nunique() == 18 + assert results.survey_metadata.n_psu == 18 + assert results.survey_metadata.df_survey == 15 + assert results.att == pytest.approx(2.0, abs=1e-10) + assert results.se == pytest.approx(0.07906, abs=1e-5) + assert np.isfinite(results.t_stat) and np.isfinite(results.p_value) + + @staticmethod + def _small_panel(strata, fpc=None): + """Six units (two treated at 3, four never treated), nine periods.""" + cohorts = [3, 3, np.inf, np.inf, np.inf, np.inf] + rows = [] + for unit, g in enumerate(cohorts): + for t in range(9): + effect = 2.0 + 0.5 * unit if (np.isfinite(g) and t >= g) else 0.0 + y = 0.5 * t + unit + effect + 0.3 * ((unit * 7 + t * 3) % 5) + rows.append((unit, t, g, y, strata[unit], 1.0, fpc[unit] if fpc else 0.0, unit)) + return pd.DataFrame( + rows, + columns=["unit", "period", "first_treat", "outcome", "stratum", "w", "N", "unit_id"], + ) + + @pytest.mark.parametrize("cluster", ["unit", "unit_subexp"]) + def test_zero_survey_df_gives_nan_inference(self, cluster): + """One PSU per stratum under lonely_psu="adjust": df_survey = 0, the + variance is not identified. The df is no longer clamped to 1 (which + reported t(1) p-values); estimates and SEs stay, inference is NaN.""" + from diff_diff import SurveyDesign + + data = self._small_panel(strata=list(range(6))) + design = SurveyDesign(weights="w", strata="stratum", lonely_psu="adjust") + est = StackedDiD(kappa_pre=2, kappa_post=2, cluster=cluster) + with pytest.warns(UserWarning, match="zero degrees of freedom"): + results = est.fit(data, survey_design=design, **_ANT_FIT) + assert results.survey_metadata.df_survey == 0 + assert np.isfinite(results.att) and np.isfinite(results.se) and results.se > 0 + # the SE is identified as a number but not for inference + assert np.isnan(results.t_stat) and np.isnan(results.p_value) + assert all(np.isnan(bound) for bound in results.conf_int) + es = results.aggregate("event_study").to_dataframe() + rows = es[~es["is_reference"]] + assert np.isfinite(rows["se"]).all() + assert rows[["t_stat", "p_value", "conf_int_lower", "conf_int_upper"]].isna().all().all() + + @pytest.mark.parametrize("psu", [None, "unit_id"]) + def test_implicit_unit_psus_are_validated_like_explicit_ones(self, psu): + """A stratum holding one unit warns that it is excluded from variance + estimation, and an FPC below a stratum's PSU count raises, whether the + unit PSU is implicit or named. Both fits give the same SE.""" + from diff_diff import SurveyDesign + + strata = [0, 1, 0, 1, 0, 2] # the last unit is alone in its stratum + extra = {"psu": psu} if psu else {} + est = StackedDiD(kappa_pre=2, kappa_post=2) + with pytest.warns(UserWarning, match="Stratum 2 has only 1 PSU"): + results = est.fit( + self._small_panel(strata), + survey_design=SurveyDesign(weights="w", strata="stratum", **extra), + **_ANT_FIT, + ) + assert results.se == pytest.approx(0.3307, abs=1e-4) + assert results.survey_metadata.df_survey == 3 + with pytest.raises(ValueError, match=r"FPC \(0\.5\) is less than the number of PSUs"): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + est.fit( + self._small_panel(strata, fpc=[10, 10, 10, 10, 10, 0.5]), + survey_design=SurveyDesign(weights="w", strata="stratum", fpc="N", **extra), + **_ANT_FIT, + ) + + @pytest.mark.parametrize("psu", [None, "psu"]) + def test_fpc_is_checked_against_the_full_sample_not_the_stack(self, psu): + """Six sampled units per stratum, FPC = 4. Cohort 8 is trimmed (its + window does not fit) and, with never-treated controls, is no one's + control, so only four units per stratum reach the stack. The implicit + unit PSUs must be validated on the supplied sample, as an explicit + ``psu`` is: the fit raises instead of passing the check on the trimmed + stack and reporting SE 0.""" + from diff_diff import SurveyDesign + + data = self._census(lead=0) + data["N"] = 4 + design = SurveyDesign( + weights="w", strata="stratum", fpc="N", **({"psu": psu} if psu else {}) + ) + est = StackedDiD(kappa_pre=2, kappa_post=2, control_group="never_treated") + with pytest.raises(ValueError, match=r"FPC \(4\.0\) is less than the number of PSUs \(6\)"): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + est.fit(data, survey_design=design, **_ANT_FIT) + + def test_lost_units_helper(self): + info = pd.DataFrame({"_first_treat": [3.0] * 2 + [6.0] * 3 + [8.0] * 4 + [np.inf] * 2}) + nyt = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1) + # cohort 6 was a control for cohort 3 (6 > 5) and is not one now + # (6 > 6 fails); it is still in the stack as a treated cohort + # (window [3, 8] fits in [0, 10]), so nothing is lost + assert nyt._units_lost_to_anticipation_cutoff([3, 6, 8], 0, 10, info) == {} + # with periods 0..8 cohort 6's own window [3, 8] still fits, cohort 8's + # does not: cohort 8 stays a control for cohort 3 (8 > 6), nothing lost + assert nyt._units_lost_to_anticipation_cutoff([3, 6, 8], 0, 8, info) == {} + strict = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1, control_group="strict") + # strict: cohort 8 passed 8 > 7 and fails 8 > 8; its own window does + # not fit in [0, 8], so its four units are in no sub-experiment + assert strict._units_lost_to_anticipation_cutoff([3, 8], 0, 8, info) == {8.0: 4} + never = StackedDiD(kappa_pre=2, kappa_post=2, anticipation=1, control_group="never_treated") + assert never._units_lost_to_anticipation_cutoff([3, 6, 8], 0, 8, info) == {} + assert ( + StackedDiD(kappa_pre=2, kappa_post=2)._units_lost_to_anticipation_cutoff( + [3, 6, 8], 0, 8, info + ) + == {} + ) + + +class TestEmptyPanel: + """A zero-row panel raises a descriptive ``ValueError`` before anything + else, with or without a survey design.""" + + @staticmethod + def _empty(): + return pd.DataFrame( + { + "unit": pd.Series(dtype=int), + "period": pd.Series(dtype=int), + "first_treat": pd.Series(dtype=float), + "outcome": pd.Series(dtype=float), + "N": pd.Series(dtype=float), + "w": pd.Series(dtype=float), + } + ) + + @pytest.mark.parametrize( + "design_kwargs", + [None, {"fpc": "N"}, {"weights": "w"}, {"weights": "w", "fpc": "N", "psu": "unit"}], + ) + def test_empty_panel_raises_value_error(self, design_kwargs): + from diff_diff import SurveyDesign + + design = SurveyDesign(**design_kwargs) if design_kwargs else None + with pytest.raises(ValueError, match=r"empty panel \(0 rows\)"): + StackedDiD().fit(self._empty(), survey_design=design, **_ANT_FIT) + + # ============================================================================= # TestClustering # ============================================================================= diff --git a/tests/test_target_parameter.py b/tests/test_target_parameter.py index fd0000826..1751a6e24 100644 --- a/tests/test_target_parameter.py +++ b/tests/test_target_parameter.py @@ -393,6 +393,59 @@ def test_stacked_control_group_branches_definition(self, control_group, expected assert tp["aggregation"] == "stacked" assert expected_clause in tp["definition"] + @pytest.mark.parametrize( + "control_group, anticipation, recorded, expected, absent", + [ + ("not_yet_treated", 0, True, "``A_s > a + kappa_post``", "+ anticipation"), + ("not_yet_treated", 1, True, "``A_s > a + kappa_post + anticipation``", "unverified"), + ("strict", 0, True, "``A_s > a + kappa_post + kappa_pre``", "+ anticipation"), + ( + "strict", + 2, + True, + "``A_s > a + kappa_post + kappa_pre + anticipation``", + "unverified", + ), + ("never_treated", 1, True, "``A_s = infinity``", "+ anticipation"), + # no record of the rule (saved by an earlier version): the old + # cutoff is shown and labelled unverified, never the adjusted one + ( + "not_yet_treated", + 1, + None, + "``A_s > a + kappa_post``).", + "kappa_post + anticipation``", + ), + ( + "strict", + 1, + None, + "``A_s > a + kappa_post + kappa_pre``).", + "kappa_pre + anticipation``", + ), + ("not_yet_treated", 0, None, "``A_s > a + kappa_post``", "unverified"), + ], + ) + def test_stacked_control_cutoff_follows_the_recorded_rule( + self, control_group, anticipation, recorded, expected, absent + ): + """A later adopter responds from ``A_s - anticipation``. The stated + cutoff carries ``+ anticipation`` only when the result records that + its controls were selected that way; without the record the earlier + cutoff is shown with an "unverified" caveat.""" + tp = describe_target_parameter( + _minimal_result( + "StackedDiDResults", + control_group=control_group, + anticipation=anticipation, + control_cutoff_includes_anticipation=recorded, + ) + ) + assert expected in tp["definition"] + assert absent not in tp["definition"] + if recorded is None and anticipation > 0 and control_group != "never_treated": + assert "unverified" in tp["definition"] and "should be rerun" in tp["definition"] + @pytest.mark.parametrize( "weighting, expected_clause", [ diff --git a/tests/test_visualization.py b/tests/test_visualization.py index b3824cbb7..7517808e3 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -2,6 +2,8 @@ Tests for visualization functions. """ +import warnings + import numpy as np import pandas as pd import pytest @@ -881,6 +883,239 @@ def _plotted_intervals(ax): return out +def _zero_df_stacked_fit(zero_df=True): + """StackedDiD survey fit on six units. With one unit per stratum under + lonely_psu="adjust" the design has zero degrees of freedom: finite SEs, + NaN stored intervals. With three strata of two units inference is defined.""" + from diff_diff import StackedDiD, SurveyDesign + + cohorts = [3, 3, np.inf, np.inf, np.inf, np.inf] + strata = list(range(6)) if zero_df else [0, 1, 2, 0, 1, 2] + rows = [] + for unit, g in enumerate(cohorts): + for t in range(9): + effect = 2.0 + 0.5 * unit if (np.isfinite(g) and t >= g) else 0.0 + y = 0.5 * t + unit + effect + 0.3 * ((unit * 7 + t * 3) % 5) + rows.append((unit, t, g, y, strata[unit], 1.0)) + data = pd.DataFrame(rows, columns=["unit", "period", "first_treat", "outcome", "stratum", "w"]) + design = SurveyDesign(weights="w", strata="stratum", lonely_psu="adjust") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return StackedDiD(kappa_pre=2, kappa_post=2).fit( + data, + outcome="outcome", + unit="unit", + time="period", + first_treat="first_treat", + survey_design=design, + ) + + +class TestPlotEventStudyUndefinedStoredInference: + """A results object passed directly has its intervals recomputed from the + SE. A row whose STORED interval is NaN while its SE is finite (inference + failed closed, e.g. a survey design with zero degrees of freedom) must not + get one back.""" + + def test_fit_has_finite_se_and_nan_intervals(self): + results = _zero_df_stacked_fit() + rows = [e for e in results.event_study_effects.values() if not e.get("is_reference")] + assert rows and all(np.isfinite(e["se"]) and e["se"] > 0 for e in rows) + assert all(np.isnan(e["conf_int"][0]) and np.isnan(e["conf_int"][1]) for e in rows) + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": 0}]) + def test_no_estimated_row_gets_an_interval(self, kwargs): + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + results = _zero_df_stacked_fit() + # Without an explicit reference the auto-inferred reference row keeps + # its zero-width constraint bar (REGISTRY Event Study Plotting); no + # estimated row may carry an interval on either route. + for source in (results, results.aggregate("event_study")): + ax = plot_event_study(source, show=False, **kwargs) + assert len({p[0] for p in _plotted_points(ax)}) == len(results.event_study_effects) + drawn = _plotted_intervals(ax) + assert all(lower == upper == 0.0 for lower, upper in drawn.values()) + assert len(drawn) <= 1 + plt.close() + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": 0}]) + def test_plotly_draws_no_band(self, kwargs): + pytest.importorskip("plotly") + + def band_heights(fig): + return [ + float(y) + for trace in fig.data + if getattr(trace, "fill", None) == "toself" + for y in trace.y + if y is not None and np.isfinite(y) + ] + + fig = plot_event_study(_zero_df_stacked_fit(), backend="plotly", show=False, **kwargs) + assert all(y == 0.0 for y in band_heights(fig)) + # positive control: defined inference draws a band on the same route + fig = plot_event_study( + _zero_df_stacked_fit(zero_df=False), backend="plotly", show=False, **kwargs + ) + assert any(y != 0.0 for y in band_heights(fig)) + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": -1}]) + def test_one_undefined_row_among_defined_rows(self, kwargs): + """Only the row with undefined inference loses its interval.""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + results = _zero_df_stacked_fit(zero_df=False) + row = results.event_study_effects[1] + assert np.isfinite(row["se"]) and np.isfinite(row["conf_int"][0]) + row.update(t_stat=np.nan, p_value=np.nan, conf_int=(np.nan, np.nan)) + + ax = plot_event_study(results, show=False, **kwargs) + horizons = sorted(results.event_study_effects) + drawn = _plotted_intervals(ax) + assert float(horizons.index(1)) not in drawn + assert all(float(horizons.index(h)) in drawn for h in horizons if h not in (1, -1)) + assert float(horizons.index(1)) in {p[0] for p in _plotted_points(ax)} + plt.close() + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": -1}]) + @pytest.mark.parametrize( + "stored", [(float("nan"), 3.1), (0.4, float("nan")), (None, 3.1), (0.4, None)] + ) + def test_a_partly_missing_stored_interval_is_not_rebuilt(self, stored, kwargs): + """One finite endpoint is not an interval: the row keeps its marker and + gets no bar, as it does through the container.""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + results = _zero_df_stacked_fit(zero_df=False) + results.event_study_effects[1].update(p_value=np.nan, conf_int=stored) + horizons = sorted(results.event_study_effects) + ax = plot_event_study(results, show=False, **kwargs) + drawn = _plotted_intervals(ax) + assert float(horizons.index(1)) not in drawn + assert float(horizons.index(0)) in drawn and float(horizons.index(2)) in drawn + assert float(horizons.index(1)) in {p[0] for p in _plotted_points(ax)} + plt.close() + + def test_a_row_that_stores_no_interval_keeps_the_recomputed_one(self): + """Legacy rows without a ``conf_int`` key are still drawn from the SE.""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + results = _zero_df_stacked_fit(zero_df=False) + del results.event_study_effects[1]["conf_int"] + horizons = sorted(results.event_study_effects) + ax = plot_event_study(results, show=False) + assert float(horizons.index(1)) in _plotted_intervals(ax) + plt.close() + + +class TestPlotEventStudyRawDCDHUndefinedInference: + """The raw dCDH route recomputes intervals from the SE too. An effect or + placebo horizon whose stored interval is NaN plots with no interval.""" + + @staticmethod + def _dcdh(conf_int, placebo=None): + from types import SimpleNamespace + + entry = { + "effect": 1.4, + "se": 0.3, + "t_stat": float("nan"), + "p_value": float("nan"), + "conf_int": conf_int, + "n_obs": 40, + } + return SimpleNamespace(L_max=1, placebo_event_study=placebo, event_study_effects={1: entry}) + + @pytest.mark.parametrize( + "stored", + [ + (float("nan"), float("nan")), + (float("nan"), 2.0), + (0.8, float("nan")), + (None, 2.0), + (0.8, None), + ], + ) + def test_undefined_effect_and_placebo_get_no_interval(self, stored): + """Fully or partly missing stored bounds, on the effect and on the + placebo horizon alike.""" + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + placebo = {-1: {"effect": 0.1, "se": 0.2, "conf_int": stored, "p_value": float("nan")}} + ax = plot_event_study(self._dcdh(stored, placebo=placebo), show=False) + assert _plotted_intervals(ax) == {} + assert len({p[0] for p in _plotted_points(ax)}) == 3 + plt.close() + + def test_defined_effect_keeps_its_interval(self): + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + ax = plot_event_study(self._dcdh((0.8, 2.0)), show=False) + (interval,) = _plotted_intervals(ax).values() + half = 1.959963984540054 * 0.3 + assert interval == pytest.approx((1.4 - half, 1.4 + half)) + plt.close() + + def test_plotly_draws_no_band_for_an_undefined_horizon(self): + pytest.importorskip("plotly") + + fig = plot_event_study( + self._dcdh((float("nan"), float("nan"))), backend="plotly", show=False + ) + assert not [t for t in fig.data if getattr(t, "fill", None) == "toself"] + + +class TestPlotEventStudyFittedUndefinedRow: + """End to end on a fitted model: SunAbraham with ``vcov_type="hc2_bm"``. + Calendar period 3.5 is observed only for the one-unit cohort adopting at + 3.5 and for the never-treated units, so only that unit identifies event + time 0: the fit stores a finite SE and NaN inference there.""" + + @staticmethod + def _fit(): + from diff_diff import SunAbraham + + rows, unit = [], 0 + for g, n, has_half_period in ((2.5, 10, False), (3.5, 1, True), (np.inf, 12, True)): + for _ in range(n): + for t in [0, 1, 2, 3, 4, 5, 6, 7] + ([3.5] if has_half_period else []): + effect = 2.0 if (np.isfinite(g) and t >= g) else 0.0 + y = 0.3 * t + (unit % 4) + effect + 0.2 * ((unit * 5 + int(t * 2) * 3) % 7) + rows.append((unit, t, g, y)) + unit += 1 + data = pd.DataFrame(rows, columns=["unit", "period", "first_treat", "outcome"]) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return SunAbraham(vcov_type="hc2_bm").fit( + data, outcome="outcome", unit="unit", time="period", first_treat="first_treat" + ) + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) + def test_event_time_zero_gets_no_interval(self, kwargs): + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + results = self._fit() + surface = results.event_study_effects + row = surface[0.0] + assert np.isfinite(row["se"]) and row["se"] > 0 and np.isnan(row["conf_int"][0]) + horizons = sorted(surface) + ax = plot_event_study(results, show=False, **kwargs) + drawn = _plotted_intervals(ax) + assert float(horizons.index(0.0)) not in drawn + for h in (-1.5, 0.5): + assert np.isfinite(surface[h]["conf_int"][0]) + assert float(horizons.index(h)) in drawn + plt.close() + + class TestPlotEventStudyWooldridge: """plot_event_study accepts a WooldridgeDiDResults by converting it to the unified container, so it takes the EventStudyResults route end to end."""