From 00b44c98c18fc760a9f5ad8606cec03c352d0adf Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 08:02:07 -0500 Subject: [PATCH 01/15] fix(stacked_did): anticipation-aware clean controls and survey-inference fixes - Clean controls: a later adopter responds from A_s - anticipation, so the cutoff is A_s > a + kappa_post + anticipation (plus kappa_pre under "strict"), in the inclusion check and the stack builder. A noiseless panel with a true effect of 2 gave 1.5 at event time 2 and 1.875 overall. - Results record the rule (control_cutoff_includes_anticipation); the target-parameter description and the BusinessReport assumption block state the cutoff a fit used and label an unrecorded one unverified. - Survey: a fit is refused when the anticipation term takes a sampled unit out of the stack; a design without a psu column uses the original unit as PSU (never unit-by-sub-experiment pairs) and validates it like an explicit PSU; zero survey degrees of freedom gives NaN inference instead of t(1). - Registry notes, backlog rows, bundled guide and changelog. --- TODO.md | 3 +- ...0261127-stacked-did-anticipation-survey.md | 63 ++++ diff_diff/_reporting_helpers.py | 47 ++- diff_diff/business_report.py | 25 +- diff_diff/guides/llms-full.txt | 2 + diff_diff/stacked_did.py | 170 +++++++-- diff_diff/stacked_did_results.py | 13 + docs/methodology/REGISTRY.md | 9 +- tests/test_business_report.py | 94 +++++ tests/test_stacked_did.py | 330 ++++++++++++++++++ tests/test_target_parameter.py | 53 +++ 11 files changed, 772 insertions(+), 37 deletions(-) create mode 100644 changelog.d/20261127-stacked-did-anticipation-survey.md diff --git a/TODO.md b/TODO.md index 8d3eafe04..b5436617b 100644 --- a/TODO.md +++ b/TODO.md @@ -57,7 +57,8 @@ 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 | +| 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..2954c27a5 --- /dev/null +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -0,0 +1,63 @@ +### 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. 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..9d44615bc 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 @@ -1543,6 +1544,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 +1558,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 +1582,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..a19a84c47 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 would drop out of the design). + **fit() parameters:** ```python diff --git a/diff_diff/stacked_did.py b/diff_diff/stacked_did.py index 9603e16b8..8a561915b 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: @@ -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 ----- @@ -659,6 +674,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 +1217,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 +1228,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 survey_design.psu is None: + 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 = dataclasses.replace(survey_design, psu=unit).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 +1261,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 survey_design.psu is not None: + # 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 +1275,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 +1309,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 +1404,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 +1484,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 @@ -1595,15 +1665,68 @@ 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 (a_int - self.kappa_pre - self.anticipation) < T_min: + continue + if (a_int + self.kappa_post) > 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 _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 +1786,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/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 03d394840..60b31cc5b 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 on the stack, so implicit unit PSUs pass through the same validation as an explicit `psu`: 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`). diff --git a/tests/test_business_report.py b/tests/test_business_report.py index 57eeae5cc..2cca21fd5 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,97 @@ 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_strict_names_strict_rule(self): desc = BusinessReport(self._stub("strict"), auto_diagnostics=False).to_dict()["assumption"][ "description" diff --git a/tests/test_stacked_did.py b/tests/test_stacked_did.py index 661ea5fb3..f10e1a951 100644 --- a/tests/test_stacked_did.py +++ b/tests/test_stacked_did.py @@ -435,6 +435,336 @@ 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, + ) + + 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 + ) + == {} + ) + + # ============================================================================= # 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", [ From 3af17a382afcd3accf1db01f6243911a09ecebbf Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 08:25:28 -0500 Subject: [PATCH 02/15] fix(visualization, reporting): undefined stored inference stays undefined in plots and reports - plot_event_study on a results object rebuilt intervals from the SE for rows whose stored interval is NaN with a finite SE (a zero-df survey fit). Those rows now plot as points with no interval on every channel. - BusinessReport names the variance method of a zero-df survey fit and says no interval is available. - StackedDiD shares one window predicate between trimming and the survey guard; guide wording says PSUs or strata can leave the design. --- ...0261127-stacked-did-anticipation-survey.md | 10 ++ diff_diff/business_report.py | 41 +++++--- diff_diff/guides/llms-full.txt | 2 +- diff_diff/stacked_did.py | 14 +-- diff_diff/visualization/_event_study.py | 33 ++++++- docs/methodology/REGISTRY.md | 9 ++ tests/test_business_report.py | 34 +++++++ tests/test_visualization.py | 93 +++++++++++++++++++ 8 files changed, 216 insertions(+), 20 deletions(-) diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md index 2954c27a5..0ef59c63e 100644 --- a/changelog.d/20261127-stacked-did-anticipation-survey.md +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -61,3 +61,13 @@ 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. +- **`plot_event_study(results)` no longer draws intervals for rows whose + stored inference is undefined.** A results object passed directly has its + intervals rebuilt from the standard error; a row with a finite standard + error and a NaN stored interval (inference failed closed, for example a + survey design with zero degrees of freedom) is now drawn as a point with no + interval, as the `aggregate("event_study")` container already was. +- `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": it names the variance method and says + that no interval is available. diff --git a/diff_diff/business_report.py b/diff_diff/business_report.py index 9d44615bc..e78ee5391 100644 --- a/diff_diff/business_report.py +++ b/diff_diff/business_report.py @@ -750,9 +750,19 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An 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)" + # 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. + _replicate = ( + getattr(getattr(r, "survey_metadata", None), "replicate_method", None) + is not None + ) + inference_label = ( + "undefined-df (replicate-weight)" + if _replicate + else "undefined-df (Taylor-linearized survey)" + ) else: # Ordinary analytical fit with a finite but unexposed # ``df`` (``DifferenceInDifferences`` / most staggered @@ -762,14 +772,23 @@ 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." - ) + if inference_label.startswith("undefined-df"): + alpha_override_caveat = ( + f"Requested alpha ({phrasing_alpha:.2f}) does not apply: " + f"this fit has {inference_label} inference with zero " + "degrees of freedom, so no confidence interval is " + "available at any level and the significance of the " + "estimate is undefined." + ) + 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)}%). The " + f"significance phrasing still uses the requested alpha." + ) unit = self._context.outcome_unit unit_kind = _UNIT_KINDS.get(unit.lower() if unit else "", "unknown") diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index a19a84c47..293f820a0 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -1028,7 +1028,7 @@ 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 would drop out of the design). +**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:** diff --git a/diff_diff/stacked_did.py b/diff_diff/stacked_did.py index 8a561915b..548dc89a4 100644 --- a/diff_diff/stacked_did.py +++ b/diff_diff/stacked_did.py @@ -1631,9 +1631,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) @@ -1710,9 +1708,7 @@ def members(shift: int) -> np.ndarray: inside = np.zeros(len(ft), dtype=bool) for a in adoption_events: a_int = int(a) - if (a_int - self.kappa_pre - self.anticipation) < T_min: - continue - if (a_int + self.kappa_post) > T_max: + 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(): @@ -1724,6 +1720,12 @@ def members(shift: int) -> np.ndarray: 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.""" return bool(np.any(self._clean_control_mask(a, unit_info["_first_treat"].values))) diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index c5bcbeffe..752d5353c 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) ): @@ -994,6 +1001,16 @@ def _extract_plot_data( ci_upper_override = {} has_cband = False + # Rows whose STORED inference is undefined: a finite, positive SE + # with an all-NaN stored interval (the producer failed inference + # closed, e.g. a survey design with zero degrees of freedom). This + # route recomputes intervals from the SE, so those rows are handed + # back on the pointwise channel as NaN - the plot then draws their + # point estimates and 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 +1020,18 @@ def _extract_plot_data( ci_lower_override[rel_period] = cband_ci[0] ci_upper_override[rel_period] = cband_ci[1] has_cband = True + stored_ci = effect_data.get("conf_int") + stored_se = effect_data["se"] + if ( + stored_ci is not None + and not effect_data.get("is_reference", False) + and np.isfinite(stored_se) + and stored_se > 0 + and not np.isfinite(stored_ci[0]) + and not np.isfinite(stored_ci[1]) + ): + undefined_lower[rel_period] = np.nan + undefined_upper[rel_period] = np.nan if periods is None: periods = sorted(effects.keys()) @@ -1051,8 +1080,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 60b31cc5b..55c880bf3 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7301,6 +7301,15 @@ 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 route):** a results object passed + directly (not its `aggregate("event_study")` container) has its intervals recomputed + from the SE. A row whose STORED interval is NaN while its SE is finite and positive - + inference the producer failed closed, such as a survey design with zero degrees of + freedom - is exempt: its point estimate is drawn with no interval, on the pointwise and + 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. - **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 2cca21fd5..5427683e8 100644 --- a/tests/test_business_report.py +++ b/tests/test_business_report.py @@ -1940,6 +1940,40 @@ def _clean_control_mask(self, a, ft): 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_strict_names_strict_rule(self): desc = BusinessReport(self._stub("strict"), auto_diagnostics=False).to_dict()["assumption"][ "description" diff --git a/tests/test_visualization.py b/tests/test_visualization.py index b3824cbb7..424b2eaa9 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,97 @@ 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: + """The raw-results route recomputes intervals from the SE. A row whose + STORED interval is NaN while its SE is finite (inference failed closed, here + 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", [{}, {"reference_period": 0}]) + def test_raw_results_draw_points_and_no_intervals(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) + # one marker position per row (the reference bar's caps add markers at its x) + 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", [{}, {"reference_period": 0}]) + def test_raw_results_plotly_draw_no_band(self, kwargs): + pytest.importorskip("plotly") + + def band_heights(fig): + ys = [ + 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) + ] + return ys + + # no band beyond the reference row's zero-width constraint + 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)) + + def test_defined_inference_still_draws_intervals(self): + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + results = _zero_df_stacked_fit(zero_df=False) + ax = plot_event_study(results, show=False) + estimated = [e for e in results.event_study_effects.values() if not e.get("is_reference")] + assert len(_plotted_intervals(ax)) >= len(estimated) + 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.""" From ee4ddd4ec81ce14cecbdce75125fe1d3ebf7b0ea Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 08:39:10 -0500 Subject: [PATCH 03/15] fix(visualization, reporting): break the Plotly band at rows without an interval; describe the inference a zero-df fit stored - The Plotly band skipped a row with no interval and filled across it. It is now one polygon per run of rows that carry an interval; a reference row does not break the band. - BusinessReport's zero-df caveat follows the stored interval and p-value: "no interval is available" only when the fit stored none. --- ...0261127-stacked-did-anticipation-survey.md | 10 +++- diff_diff/business_report.py | 23 ++++++-- diff_diff/visualization/_event_study.py | 23 ++++++-- docs/methodology/REGISTRY.md | 5 +- tests/test_business_report.py | 36 +++++++++++ tests/test_visualization.py | 59 +++++++++++++++++++ 6 files changed, 142 insertions(+), 14 deletions(-) diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md index 0ef59c63e..aa4fde72b 100644 --- a/changelog.d/20261127-stacked-did-anticipation-survey.md +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -66,8 +66,12 @@ intervals rebuilt from the standard error; a row with a finite standard error and a NaN stored interval (inference failed closed, for example a survey design with zero degrees of freedom) is now drawn as a point with no - interval, as the `aggregate("event_study")` container already was. + interval, as the `aggregate("event_study")` container already was. On the + Plotly backend the shaded band is now broken at any estimated row without an + interval, where it used to fill straight across it. - `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": it names the variance method and says - that no interval is available. + "remains at the fit's native level". 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. diff --git a/diff_diff/business_report.py b/diff_diff/business_report.py index e78ee5391..24daf9dfe 100644 --- a/diff_diff/business_report.py +++ b/diff_diff/business_report.py @@ -758,11 +758,26 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An getattr(getattr(r, "survey_metadata", None), "replicate_method", None) is not None ) - inference_label = ( - "undefined-df (replicate-weight)" - if _replicate - else "undefined-df (Taylor-linearized survey)" + _stored_ci = getattr(r, "conf_int", None) + _stored_p = getattr(r, "p_value", None) + _inference_reported = ( + _stored_ci is not None + and len(_stored_ci) == 2 + and all(isinstance(b, (int, float)) and np.isfinite(b) for b in _stored_ci) + and isinstance(_stored_p, (int, float)) + and np.isfinite(_stored_p) ) + if _inference_reported: + # Some estimators still report inference at zero + # design df through a fallback reference distribution. + # Describe what the fit stored, not what it should be. + inference_label = "zero-df survey (fallback reference distribution)" + else: + inference_label = ( + "undefined-df (replicate-weight)" + if _replicate + else "undefined-df (Taylor-linearized survey)" + ) else: # Ordinary analytical fit with a finite but unexposed # ``df`` (``DifferenceInDifferences`` / most staggered diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index 752d5353c..dbdc215cd 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -625,13 +625,24 @@ def _render_event_study_plotly( x=period_to_x[reference_period], line_dash="dot", line_color="gray", line_width=1 ) - # CI band (filled area) + # CI band (filled area). One polygon per run of rows that carry an + # interval: an ESTIMATED row without one (undefined inference, a zero or + # missing SE) ends the run, so the fill never spans it and implies bounds + # it does not have. A reference row without an interval is a constraint, + # not an estimate, and does not break the band. has_ci = [not (np.isnan(lo) or np.isnan(hi)) for lo, hi in zip(ci_lower, ci_upper)] - ci_x = [period_to_x[p] for p, h in zip(periods, has_ci) if h] - ci_lo = [lo for lo, h in zip(ci_lower, has_ci) if h] - ci_hi = [hi for hi, h in zip(ci_upper, has_ci) if h] - - if ci_x: + runs: List[List[int]] = [[]] + for i, (has, ref) in enumerate(zip(has_ci, is_ref)): + if has: + runs[-1].append(i) + elif not ref: + runs.append([]) + for run in runs: + if not run: + continue + ci_x = [period_to_x[periods[i]] for i in run] + ci_lo = [ci_lower[i] for i in run] + ci_hi = [ci_upper[i] for i in run] fig.add_trace( go.Scatter( x=ci_x + ci_x[::-1], diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 55c880bf3..4f1cc9bd9 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7309,7 +7309,10 @@ should be a deliberate user choice. 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. + zero-width constraint bar. On the Plotly backend the filled band is drawn as one polygon per run of + rows that carry an interval: an estimated row without one ends the run, so the fill does + not span it (a reference row without an interval is a constraint and does not break the + band). Before, the band skipped such a row's vertices and filled straight across it. - **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 5427683e8..da19e27d3 100644 --- a/tests/test_business_report.py +++ b/tests/test_business_report.py @@ -1974,6 +1974,42 @@ def test_zero_survey_df_fit_is_not_called_replicate_weight(self): 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" diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 424b2eaa9..2a9f270da 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -974,6 +974,65 @@ def test_defined_inference_still_draws_intervals(self): plt.close() +class TestPlotEventStudyUndefinedRowBetweenDefinedRows: + """One horizon with undefined stored inference (finite SE, NaN interval) + between horizons with valid intervals: its point is drawn, it carries no + interval, and the Plotly band is split there instead of filling across.""" + + @staticmethod + def _mixed(): + 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)) + return results + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": -1}]) + def test_matplotlib_draws_no_interval_on_that_row(self, kwargs): + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + results = self._mixed() + ax = plot_event_study(results, show=False, **kwargs) + horizons = sorted(results.event_study_effects) + x_undefined = float(horizons.index(1)) + drawn = _plotted_intervals(ax) + assert x_undefined not in drawn + estimated = [h for h in horizons if h not in (1, -1)] + assert all(float(horizons.index(h)) in drawn for h in estimated) + assert x_undefined in {p[0] for p in _plotted_points(ax)} + plt.close() + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": -1}]) + def test_plotly_band_is_split_at_that_row(self, kwargs): + pytest.importorskip("plotly") + + results = self._mixed() + fig = plot_event_study(results, backend="plotly", show=False, **kwargs) + horizons = sorted(results.event_study_effects) + x_undefined = horizons.index(1) + bands = [t for t in fig.data if getattr(t, "fill", None) == "toself"] + assert len(bands) >= 2 # rows before it and rows after it + for band in bands: + xs = [x for x in band.x if x is not None] + assert x_undefined not in xs + assert not (min(xs) < x_undefined < max(xs)) + # the row's marker is still drawn + marker_x = [ + x + for trace in fig.data + if getattr(trace, "fill", None) != "toself" and trace.x is not None + for x in trace.x + ] + assert x_undefined in marker_x + + def test_plotly_band_is_one_polygon_when_every_row_is_defined(self): + pytest.importorskip("plotly") + + fig = plot_event_study(_zero_df_stacked_fit(zero_df=False), backend="plotly", show=False) + assert len([t for t in fig.data if getattr(t, "fill", None) == "toself"]) == 1 + + class TestPlotEventStudyWooldridge: """plot_event_study accepts a WooldridgeDiDResults by converting it to the unified container, so it takes the EventStudyResults route end to end.""" From 0af98e54aa710bb4be8f07270054ed664d8278b9 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 08:53:32 -0500 Subject: [PATCH 04/15] fix(visualization): draw a one-row band segment as a vertical bar so a valid interval stays visible Splitting the Plotly band at rows without an interval can leave a row with a valid interval on its own; a one-point polygon has no area and was invisible. Registry and changelog follow the renderer. --- ...0261127-stacked-did-anticipation-survey.md | 3 +- diff_diff/visualization/_event_study.py | 14 ++++++ docs/methodology/REGISTRY.md | 10 ++-- tests/test_visualization.py | 49 ++++++++++++++++++- 4 files changed, 70 insertions(+), 6 deletions(-) diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md index aa4fde72b..f480c820d 100644 --- a/changelog.d/20261127-stacked-did-anticipation-survey.md +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -68,7 +68,8 @@ survey design with zero degrees of freedom) is now drawn as a point with no interval, as the `aggregate("event_study")` container already was. On the Plotly backend the shaded band is now broken at any estimated row without an - interval, where it used to fill straight across it. + interval, where it used to fill straight across it; a row left on its own by + the break is drawn with a vertical bar between its bounds. - `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". When the fit stored no interval it diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index dbdc215cd..8757d3297 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -643,6 +643,20 @@ def _render_event_study_plotly( ci_x = [period_to_x[periods[i]] for i in run] ci_lo = [ci_lower[i] for i in run] ci_hi = [ci_upper[i] for i in run] + if len(run) == 1: + # A one-row run has no area to fill: draw its interval as a + # vertical bar so a valid interval is never invisible. + fig.add_trace( + go.Scatter( + x=[ci_x[0], ci_x[0]], + y=[ci_lo[0], ci_hi[0]], + mode="lines", + line=dict(color=_color_to_rgba(color, 0.45), width=6), + showlegend=False, + hoverinfo="skip", + ) + ) + continue fig.add_trace( go.Scatter( x=ci_x + ci_x[::-1], diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 4f1cc9bd9..d539cfd19 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7312,7 +7312,9 @@ should be a deliberate user choice. zero-width constraint bar. On the Plotly backend the filled band is drawn as one polygon per run of rows that carry an interval: an estimated row without one ends the run, so the fill does not span it (a reference row without an interval is a constraint and does not break the - band). Before, the band skipped such a row's vertices and filled straight across it. + band). A run of a single row has no area to fill and is drawn as a vertical bar between + its bounds, so a valid interval isolated by the split stays visible. Before, the band + skipped a row without an interval and filled straight across it. - **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 @@ -7343,9 +7345,9 @@ should be a deliberate user choice. estimated row with effect exactly 0 and se 0 at the fallback position retains today's bar - today's behavior preserved, not a new defect). The dCDH route's synthesized reference carries `se = NaN` and keeps its hollow-marker-no-bar rendering, unchanged. - Plotly caveat: the plotly renderer filters NaN-CI rows out of the CI band and - interpolates the polygon across the gap (pre-existing NaN-SE convention); the matplotlib - backend is where the gated interval visibly disappears. + On the plotly backend the gated row breaks the CI band, as any estimated row without an + interval does (undefined-stored-inference Note above); the band is no longer interpolated + across it. - **Note (`plot_dose_response` zero-SE gate and band labeling):** the raw-DataFrame `se` branch adopts the same gate: rows with non-positive or non-finite `se` have their reconstructed band masked to NaN with a `UserWarning` (previously a zero-SE row drew a finite zero-width band); the plotly renderer filters non-finite-CI rows out of the `toself` band polygon and bridges the gap (the `plot_group_effects` convention above; CI values only - the dose axis may be non-numeric), and both renderers suppress an all-masked band entirely (no stray legend entry). Band LABELING states the confidence level only where it is knowable: the requested `alpha` on the DataFrame-`se` branch (validated strictly inside (0, 1)), `results.alpha` on `results=` input, and the level-free "CI" for bare-curve and explicit-CI input. Alpha semantics deliberately DIVERGE from `plot_group_effects`: that surface recomputes `effect +/- z*SE` at a requested alpha, while `plot_dose_response` warns-and-ignores an explicit `alpha` on non-`se` input, because stored/explicit-CI dose-response inputs cannot be recomputed. `plot_honest_event_study`'s raw (non-container) routes mirror the container's retained-row semantics: zero/non-finite-SE rows are excluded up front (explicitly requesting one raises), the reference row - now diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 2a9f270da..9b3fc5cb4 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -1012,11 +1012,34 @@ def test_plotly_band_is_split_at_that_row(self, kwargs): horizons = sorted(results.event_study_effects) x_undefined = horizons.index(1) bands = [t for t in fig.data if getattr(t, "fill", None) == "toself"] - assert len(bands) >= 2 # rows before it and rows after it + assert bands # the rows before it for band in bands: xs = [x for x in band.x if x is not None] assert x_undefined not in xs assert not (min(xs) < x_undefined < max(xs)) + assert len(set(xs)) >= 2 # a polygon with area, never a zero-width one + # the last horizon is isolated by the split: its VALID interval must be + # visible, drawn as a vertical bar between its bounds + x_last = horizons.index(2) + bars = [ + t + for t in fig.data + if getattr(t, "mode", None) == "lines" + and t.x is not None + and len(t.x) == 2 + and t.x[0] == t.x[1] == x_last + ] + assert len(bars) == 1 + lower, upper = sorted(float(y) for y in bars[0].y) + if "reference_period" not in kwargs: + # a results object passed directly gets the bounds this route + # selects: effect +/- z * SE + row = results.event_study_effects[2] + half = 1.959963984540054 * row["se"] + assert (lower, upper) == pytest.approx((row["effect"] - half, row["effect"] + half)) + assert lower < upper + assert bars[0].line.width >= 2 + # the row's marker is still drawn marker_x = [ x @@ -1026,6 +1049,30 @@ def test_plotly_band_is_split_at_that_row(self, kwargs): ] assert x_undefined in marker_x + def test_plotly_isolated_row_shows_the_stored_interval_on_the_container_route(self): + pytest.importorskip("plotly") + + results = self._mixed() + surface = results.aggregate("event_study") + frame = surface.to_dataframe().set_index("event_time") + assert np.isnan(frame.loc[1, "conf_int_lower"]) and np.isfinite( + frame.loc[2, "conf_int_lower"] + ) + fig = plot_event_study(surface, backend="plotly", show=False) + x_last = sorted(frame.index).index(2) + bars = [ + t + for t in fig.data + if getattr(t, "mode", None) == "lines" + and t.x is not None + and len(t.x) == 2 + and t.x[0] == t.x[1] == x_last + ] + assert len(bars) == 1 + assert sorted(float(y) for y in bars[0].y) == pytest.approx( + [frame.loc[2, "conf_int_lower"], frame.loc[2, "conf_int_upper"]] + ) + def test_plotly_band_is_one_polygon_when_every_row_is_defined(self): pytest.importorskip("plotly") From 9a120d4937afc81d98b4ef885207d6d781d1de11 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 08:56:57 -0500 Subject: [PATCH 05/15] test(visualization): pin the undefined-row and isolated-row plot cases on both routes and all three options --- tests/test_visualization.py | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 9b3fc5cb4..ff0723d88 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -1073,6 +1073,53 @@ def test_plotly_isolated_row_shows_the_stored_interval_on_the_container_route(se [frame.loc[2, "conf_int_lower"], frame.loc[2, "conf_int_upper"]] ) + @pytest.mark.parametrize("route", ["results", "container"]) + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": -1}]) + def test_plotly_marker_split_and_endpoints_on_both_routes(self, route, kwargs): + """Event time 1 (undefined): a marker, no bar, no polygon touching or + spanning it. Event time 2 (isolated, valid): a bar with the endpoints + the route selects - the stored interval on the container route, and + ``effect +/- z * SE`` on the results route or after an explicit + reference (which recomputes from the SE).""" + pytest.importorskip("plotly") + + results = self._mixed() + source = results if route == "results" else results.aggregate("event_study") + fig = plot_event_study(source, backend="plotly", show=False, **kwargs) + horizons = sorted(results.event_study_effects) + x_undefined, x_last = horizons.index(1), horizons.index(2) + + def bars_at(x): + return [ + t + for t in fig.data + if getattr(t, "mode", None) == "lines" + and t.x is not None + and len(t.x) == 2 + and t.x[0] == t.x[1] == x + ] + + markers = [ + x + for t in fig.data + if getattr(t, "mode", None) == "markers" and t.x is not None + for x in t.x + ] + assert x_undefined in markers and x_last in markers + assert bars_at(x_undefined) == [] + for band in (t for t in fig.data if getattr(t, "fill", None) == "toself"): + xs = [x for x in band.x if x is not None] + assert x_undefined not in xs and not (min(xs) < x_undefined < max(xs)) + + (bar,) = bars_at(x_last) + row = results.event_study_effects[2] + if route == "container" and "reference_period" not in kwargs: + expected = sorted(row["conf_int"]) + else: + half = 1.959963984540054 * row["se"] + expected = [row["effect"] - half, row["effect"] + half] + assert sorted(float(y) for y in bar.y) == pytest.approx(expected) + def test_plotly_band_is_one_polygon_when_every_row_is_defined(self): pytest.importorskip("plotly") From 3ea641f6c8f5aac18ba4454f2186facdaff592e1 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 09:19:13 -0500 Subject: [PATCH 06/15] fix(visualization, reporting): undefined inference on the dCDH plot route; band bridges only real constraints; replicate designs without a df - The raw dCDH route recomputed intervals from the SE for effects and placebos whose stored interval is NaN; the one-row bar made that visible. Those rows now plot with no interval. - The Plotly band continues only across a normalization constraint (a reference row with no uncertainty), not across a row merely styled as the reference by the -1 fallback. - BusinessReport treats a replicate design that records no df and stored no interval as undefined-df. --- ...0261127-stacked-did-anticipation-survey.md | 6 +- diff_diff/business_report.py | 51 +++---- diff_diff/visualization/_event_study.py | 60 +++++--- docs/methodology/REGISTRY.md | 9 +- tests/test_business_report.py | 36 +++++ tests/test_visualization.py | 133 ++++++++++++++++++ 6 files changed, 250 insertions(+), 45 deletions(-) diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md index f480c820d..70848c51f 100644 --- a/changelog.d/20261127-stacked-did-anticipation-survey.md +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -66,13 +66,15 @@ intervals rebuilt from the standard error; a row with a finite standard error and a NaN stored interval (inference failed closed, for example a survey design with zero degrees of freedom) is now drawn as a point with no - interval, as the `aggregate("event_study")` container already was. On the + interval, as the `aggregate("event_study")` container already was; this + holds for dCDH results (effects and placebos) as well. On the Plotly backend the shaded band is now broken at any estimated row without an interval, where it used to fill straight across it; a row left on its own by the break is drawn with a vertical bar between its bounds. - `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". When the fit stored no interval it + "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. diff --git a/diff_diff/business_report.py b/diff_diff/business_report.py index 24daf9dfe..6938ea0b4 100644 --- a/diff_diff/business_report.py +++ b/diff_diff/business_report.py @@ -747,37 +747,40 @@ 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 + ) + _inference_reported = ( + ci is not None + and len(ci) == 2 + and all(b is not None and np.isfinite(b) for b in ci) + and p is not None + and np.isfinite(p) + ) + _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: + elif (_zero_df or _unrecorded_replicate_df) and not _inference_reported: # 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. - _replicate = ( - getattr(getattr(r, "survey_metadata", None), "replicate_method", None) - is not None - ) - _stored_ci = getattr(r, "conf_int", None) - _stored_p = getattr(r, "p_value", None) - _inference_reported = ( - _stored_ci is not None - and len(_stored_ci) == 2 - and all(isinstance(b, (int, float)) and np.isfinite(b) for b in _stored_ci) - and isinstance(_stored_p, (int, float)) - and np.isfinite(_stored_p) + inference_label = ( + "undefined-df (replicate-weight)" + if _replicate + else "undefined-df (Taylor-linearized survey)" ) - if _inference_reported: - # Some estimators still report inference at zero - # design df through a fallback reference distribution. - # Describe what the fit stored, not what it should be. - inference_label = "zero-df survey (fallback reference distribution)" - else: - inference_label = ( - "undefined-df (replicate-weight)" - if _replicate - else "undefined-df (Taylor-linearized survey)" - ) + elif _zero_df: + # Some estimators still report inference at zero design + # df through a fallback reference distribution. Describe + # what the fit stored, not what it should be. + inference_label = "zero-df survey (fallback reference distribution)" else: # Ordinary analytical fit with a finite but unexposed # ``df`` (``DifferenceInDifferences`` / most staggered diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index 8757d3297..a94b35087 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -628,14 +628,24 @@ def _render_event_study_plotly( # CI band (filled area). One polygon per run of rows that carry an # interval: an ESTIMATED row without one (undefined inference, a zero or # missing SE) ends the run, so the fill never spans it and implies bounds - # it does not have. A reference row without an interval is a constraint, - # not an estimate, and does not break the band. + # it does not have. A normalization constraint without an interval is not + # an estimate and does not break the band. has_ci = [not (np.isnan(lo) or np.isnan(hi)) for lo, hi in zip(ci_lower, ci_upper)] + # Reference STYLING is not enough to bridge a gap: the raw routes fall back + # to styling event time -1 when the producer marks no reference, and under + # a varying base that row is an estimated placebo. Only an actual + # normalization constraint - a reference row carrying no uncertainty (SE + # NaN, or effect and SE both exactly 0) - lets the band continue. + ses = df["se"].tolist() + is_constraint = [ + bool(ref) and (not np.isfinite(sd) or (sd == 0 and eff == 0)) + for ref, sd, eff in zip(is_ref, ses, effects) + ] runs: List[List[int]] = [[]] - for i, (has, ref) in enumerate(zip(has_ci, is_ref)): + for i, (has, constraint) in enumerate(zip(has_ci, is_constraint)): if has: runs[-1].append(i) - elif not ref: + elif not constraint: runs.append([]) for run in runs: if not run: @@ -725,6 +735,27 @@ 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 an all-NaN stored + interval (the producer failed inference closed, e.g. a survey design with + zero degrees of freedom). Reference rows are constraints, not estimates, + and never qualify. The raw routes recompute intervals from the SE, so such + rows must be 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 + return bool( + np.isfinite(stored_se) + and stored_se > 0 + and not np.isfinite(stored_ci[0]) + and not np.isfinite(stored_ci[1]) + ) + + def _extract_plot_data( results: PlottableResults, periods: Optional[List[Any]], @@ -971,6 +1002,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: @@ -981,6 +1014,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 @@ -995,6 +1030,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()) @@ -1013,8 +1050,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, ) @@ -1045,16 +1082,7 @@ def _extract_plot_data( ci_lower_override[rel_period] = cband_ci[0] ci_upper_override[rel_period] = cband_ci[1] has_cband = True - stored_ci = effect_data.get("conf_int") - stored_se = effect_data["se"] - if ( - stored_ci is not None - and not effect_data.get("is_reference", False) - and np.isfinite(stored_se) - and stored_se > 0 - and not np.isfinite(stored_ci[0]) - and not np.isfinite(stored_ci[1]) - ): + if _stored_inference_undefined(effect_data): undefined_lower[rel_period] = np.nan undefined_upper[rel_period] = np.nan diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index d539cfd19..20fba445b 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7303,7 +7303,8 @@ should be a deliberate user choice. its own cohort base and no single shift represents them faithfully - **Note (undefined stored inference on the raw-results route):** a results object passed directly (not its `aggregate("event_study")` container) has its intervals recomputed - from the SE. A row whose STORED interval is NaN while its SE is finite and positive - + from the SE. This covers both raw routes: the generic `event_study_effects` route and the + dCDH route (its effects and its placebo horizons). A row whose STORED interval is NaN while its SE is finite and positive - inference the producer failed closed, such as a survey design with zero degrees of freedom - is exempt: its point estimate is drawn with no interval, on the pointwise and the band channel, with or without an explicit `reference_period=`. Before this rule a @@ -7311,8 +7312,10 @@ should be a deliberate user choice. estimates whose inference was undefined. The auto-inferred reference row keeps its zero-width constraint bar. On the Plotly backend the filled band is drawn as one polygon per run of rows that carry an interval: an estimated row without one ends the run, so the fill does - not span it (a reference row without an interval is a constraint and does not break the - band). A run of a single row has no area to fill and is drawn as a vertical bar between + not span it (a normalization constraint without an interval does not break the band; that + means a reference row carrying no uncertainty - SE NaN, or effect and SE both exactly 0 - + not a row that is merely styled as the reference by the `-1` fallback, which under a + varying base is an estimated placebo). A run of a single row has no area to fill and is drawn as a vertical bar between its bounds, so a valid interval isolated by the split stays visible. Before, the band skipped a row without an interval and filled straight across it. - **Note (WooldridgeDiD route):** a `WooldridgeDiDResults` passed to `plot_event_study` is diff --git a/tests/test_business_report.py b/tests/test_business_report.py index da19e27d3..a94bc8e64 100644 --- a/tests/test_business_report.py +++ b/tests/test_business_report.py @@ -4147,6 +4147,42 @@ 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 + 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_visualization.py b/tests/test_visualization.py index ff0723d88..52e734b3c 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -1127,6 +1127,139 @@ def test_plotly_band_is_one_polygon_when_every_row_is_defined(self): assert len([t for t in fig.data if getattr(t, "fill", None) == "toself"]) == 1 +def _toself_bands(fig): + return [t for t in fig.data if getattr(t, "fill", None) == "toself"] + + +def _vertical_bars(fig): + return [ + t + for t in fig.data + if getattr(t, "mode", None) == "lines" + and t.x is not None + and len(t.x) == 2 + and t.x[0] == t.x[1] + ] + + +def _marker_xs(fig): + return [ + x + for t in fig.data + if getattr(t, "mode", None) == "markers" and t.x is not None + for x in t.x + ] + + +class TestPlotEventStudyRawDCDHUndefinedInference: + """The raw dCDH route recomputes intervals from the SE too. A horizon whose + stored interval is NaN (replicate design with undefined df) must plot as a + marker with no interval - including the isolated case ``L_max=1`` without + placebos, where the one-row band segment is drawn as a visible bar.""" + + @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}) + + def test_isolated_undefined_horizon_draws_no_interval(self): + pytest.importorskip("plotly") + + fig = plot_event_study( + self._dcdh((float("nan"), float("nan"))), backend="plotly", show=False + ) + assert _vertical_bars(fig) == [] and _toself_bands(fig) == [] + assert len(_marker_xs(fig)) == 2 # the synthesized reference and horizon 1 + + def test_isolated_defined_horizon_draws_its_bar(self): + pytest.importorskip("plotly") + + fig = plot_event_study(self._dcdh((0.8, 2.0)), backend="plotly", show=False) + (bar,) = _vertical_bars(fig) + half = 1.959963984540054 * 0.3 + assert sorted(float(y) for y in bar.y) == pytest.approx([1.4 - half, 1.4 + half]) + + def test_undefined_placebo_and_effect_matplotlib(self): + pytest.importorskip("matplotlib") + import matplotlib.pyplot as plt + + nan_ci = (float("nan"), float("nan")) + placebo = {-1: {"effect": 0.1, "se": 0.2, "conf_int": nan_ci, "p_value": float("nan")}} + ax = plot_event_study(self._dcdh(nan_ci, placebo=placebo), show=False) + assert _plotted_intervals(ax) == {} + assert len({p[0] for p in _plotted_points(ax)}) == 3 + plt.close() + + +class TestPlotEventStudyBandAndFallbackReference: + """When the producer marks no reference, the raw route styles event time -1 + as the reference. Under a varying base that row is an ESTIMATED placebo; if + its inference is undefined the Plotly band must break there, not treat it + as a constraint and fill across it.""" + + @staticmethod + def _varying_base(minus_one_ci): + from types import SimpleNamespace + + def row(effect, se, ci): + return {"effect": effect, "se": se, "conf_int": ci, "p_value": 0.5, "n_obs": 30} + + return SimpleNamespace( + event_study_effects={ + -2: row(0.05, 0.10, (-0.15, 0.25)), + -1: row(0.02, 0.10, minus_one_ci), + 0: row(1.00, 0.12, (0.76, 1.24)), + 1: row(1.10, 0.12, (0.86, 1.34)), + } + ) + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) + def test_no_polygon_spans_an_undefined_row_styled_as_reference(self, kwargs): + pytest.importorskip("plotly") + + results = self._varying_base((float("nan"), float("nan"))) + fig = plot_event_study(results, backend="plotly", show=False, **kwargs) + x_minus_one = sorted(results.event_study_effects).index(-1) + for band in _toself_bands(fig): + xs = [x for x in band.x if x is not None] + assert x_minus_one not in xs and not (min(xs) < x_minus_one < max(xs)) + # -2 is isolated by the break and keeps a visible interval + assert [b for b in _vertical_bars(fig) if b.x[0] == 0] + assert x_minus_one in _marker_xs(fig) + + def test_a_defined_row_at_minus_one_keeps_one_band(self): + pytest.importorskip("plotly") + + fig = plot_event_study(self._varying_base((-0.18, 0.22)), backend="plotly", show=False) + assert len(_toself_bands(fig)) == 1 and _vertical_bars(fig) == [] + + def test_a_real_reference_constraint_still_bridges(self): + """A producer-marked reference row (effect 0, no uncertainty) is a + constraint: the band continues across it.""" + pytest.importorskip("plotly") + + results = self._varying_base((float("nan"), float("nan"))) + results.event_study_effects[-1] = { + "effect": 0.0, + "se": float("nan"), + "conf_int": (float("nan"), float("nan")), + "is_reference": True, + } + fig = plot_event_study(results, backend="plotly", show=False) + (band,) = _toself_bands(fig) + xs = [x for x in band.x if x is not None] + assert min(xs) == 0 and max(xs) == 3 + + class TestPlotEventStudyWooldridge: """plot_event_study accepts a WooldridgeDiDResults by converting it to the unified container, so it takes the EventStudyResults route end to end.""" From e103467c1be872bbe6668f38229fcd78be8a65f3 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 09:32:34 -0500 Subject: [PATCH 07/15] fix(visualization): the Plotly band bridges only a declared or caller-chosen reference Reference styling comes from the raw route's -1 fallback when the producer marks no reference; under a varying base that row is an estimated placebo, whatever its SE. The band now continues across a row without an interval only when the caller normalized on it or the producer declared it (container marks, an is_reference row, a reference_period attribute, the dCDH reference). --- diff_diff/visualization/_event_study.py | 55 +++++++++++++++++++++---- docs/methodology/REGISTRY.md | 8 ++-- tests/test_visualization.py | 27 ++++++++++++ 3 files changed, 79 insertions(+), 11 deletions(-) diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index a94b35087..a3523269b 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -218,6 +218,7 @@ def plot_event_study( ci_upper_override = None reference_marks: Optional[Set[Any]] = None undefined_inference: Set[Any] = set() + reference_verified = False if results is not None: ( effects, @@ -248,6 +249,7 @@ def plot_event_study( # If reference was inferred from results, it was NOT explicitly provided if reference_inferred: reference_period_explicit = False + reference_verified = _reference_is_verified(results, reference_period) # Channel selection: the band channel when the user wants # simultaneous bands; otherwise the POINTWISE channel - the # producer's stored intervals (NaN preserved), for input routes @@ -376,6 +378,14 @@ def plot_event_study( # single-reference routes. "is_reference": period == reference_period or (reference_marks is not None and period in reference_marks), + # A normalization CONSTRAINT, as opposed to reference styling: + # a row the caller normalized on, a producer-declared + # reference, or a marked anchor. The raw route's bare ``-1`` + # fallback styles a marker but is not a constraint. + "is_constraint": (reference_marks is not None and period in reference_marks) + or ( + period == reference_period and (reference_period_explicit or reference_verified) + ), } ) @@ -633,14 +643,13 @@ def _render_event_study_plotly( has_ci = [not (np.isnan(lo) or np.isnan(hi)) for lo, hi in zip(ci_lower, ci_upper)] # Reference STYLING is not enough to bridge a gap: the raw routes fall back # to styling event time -1 when the producer marks no reference, and under - # a varying base that row is an estimated placebo. Only an actual - # normalization constraint - a reference row carrying no uncertainty (SE - # NaN, or effect and SE both exactly 0) - lets the band continue. - ses = df["se"].tolist() - is_constraint = [ - bool(ref) and (not np.isfinite(sd) or (sd == 0 and eff == 0)) - for ref, sd, eff in zip(is_ref, ses, effects) - ] + # a varying base that row is an estimated placebo. Only a normalization + # constraint - a reference the caller normalized on or the producer + # declared (``is_constraint``, resolved in ``plot_event_study``) - lets the + # band continue. + is_constraint = ( + df["is_constraint"].tolist() if "is_constraint" in df.columns else [False] * len(df) + ) runs: List[List[int]] = [[]] for i, (has, constraint) in enumerate(zip(has_ci, is_constraint)): if has: @@ -735,6 +744,36 @@ def _render_event_study_plotly( return fig +def _reference_is_verified(results: Any, reference_period: Any) -> bool: + """Whether ``reference_period`` is a normalization anchor the PRODUCER + declared, as opposed to the raw route's unconditional ``-1`` fallback + (which only styles a marker, and under a varying base lands on an + estimated placebo). + + Verified sources: an ``EventStudyResults`` container (its reference rows + are marked), the dCDH route (reference synthesized at 0), a + ``reference_period`` attribute on the results, or an ``is_reference`` key + on the row of a raw ``event_study_effects`` dict. + """ + if results is None or reference_period is None: + return False + from diff_diff.results_base import EventStudyResults + + if isinstance(results, EventStudyResults): + return True + if isinstance(results, pd.DataFrame): + return False + if hasattr(results, "placebo_event_study") and hasattr(results, "L_max"): + return True + if getattr(results, "reference_period", None) is not None: + return True + surface = getattr(results, "event_study_effects", None) + if isinstance(surface, dict): + entry = surface.get(reference_period) + return bool(isinstance(entry, dict) and entry.get("is_reference", False)) + return False + + 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 an all-NaN stored diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 20fba445b..436a88661 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7313,9 +7313,11 @@ should be a deliberate user choice. zero-width constraint bar. On the Plotly backend the filled band is drawn as one polygon per run of rows that carry an interval: an estimated row without one ends the run, so the fill does not span it (a normalization constraint without an interval does not break the band; that - means a reference row carrying no uncertainty - SE NaN, or effect and SE both exactly 0 - - not a row that is merely styled as the reference by the `-1` fallback, which under a - varying base is an estimated placebo). A run of a single row has no area to fill and is drawn as a vertical bar between + means a reference the caller normalized on with `reference_period=`, or one the producer + declared - a marked row of a container, an `is_reference` row or `reference_period` + attribute on a results object, the dCDH reference at 0 - not a row that is merely styled + as the reference by the `-1` fallback, which under a varying base is an estimated + placebo, whatever its SE). A run of a single row has no area to fill and is drawn as a vertical bar between its bounds, so a valid interval isolated by the split stays visible. Before, the band skipped a row without an interval and filled straight across it. - **Note (WooldridgeDiD route):** a `WooldridgeDiDResults` passed to `plot_event_study` is diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 52e734b3c..4098e2114 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -1236,6 +1236,33 @@ def test_no_polygon_spans_an_undefined_row_styled_as_reference(self, kwargs): assert [b for b in _vertical_bars(fig) if b.x[0] == 0] assert x_minus_one in _marker_xs(fig) + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) + def test_no_polygon_spans_a_fallback_row_with_no_standard_error(self, kwargs): + """Same, when the estimated placebo at -1 has a NaN SE as well as a NaN + interval (for example a jackknife variance that is not identified + there): a missing SE does not make the row a constraint.""" + pytest.importorskip("plotly") + + results = self._varying_base((float("nan"), float("nan"))) + results.event_study_effects[-1]["se"] = float("nan") + fig = plot_event_study(results, backend="plotly", show=False, **kwargs) + x_minus_one = sorted(results.event_study_effects).index(-1) + for band in _toself_bands(fig): + xs = [x for x in band.x if x is not None] + assert x_minus_one not in xs and not (min(xs) < x_minus_one < max(xs)) + assert x_minus_one in _marker_xs(fig) + + def test_an_explicit_reference_is_a_constraint(self): + """The caller normalizes on -1: that row is now a constraint and the + band continues across it.""" + pytest.importorskip("plotly") + + results = self._varying_base((-0.18, 0.22)) + fig = plot_event_study(results, backend="plotly", reference_period=-1, show=False) + (band,) = _toself_bands(fig) + xs = [x for x in band.x if x is not None] + assert min(xs) == 0 and max(xs) == 3 + def test_a_defined_row_at_minus_one_keeps_one_band(self): pytest.importorskip("plotly") From 97b8566034009eda7bd529cdd593da440a9040e8 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 09:47:37 -0500 Subject: [PATCH 08/15] fix(visualization): keep a declared reference label exact; it is a constraint only for the horizon it names A reference a results object declares between horizons (-0.5) was cast to int and landed on event time 0, an estimated effect, which was then styled as the reference and, with the new band rule, bridged. The label is kept as given and verified against the plotted horizon. --- ...0261127-stacked-did-anticipation-survey.md | 4 +- diff_diff/visualization/_event_study.py | 23 ++++++-- docs/methodology/REGISTRY.md | 4 +- tests/test_visualization.py | 54 +++++++++++++++++-- 4 files changed, 76 insertions(+), 9 deletions(-) diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md index 70848c51f..5e7cf6110 100644 --- a/changelog.d/20261127-stacked-did-anticipation-survey.md +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -70,7 +70,9 @@ holds for dCDH results (effects and placebos) as well. On the Plotly backend the shaded band is now broken at any estimated row without an interval, where it used to fill straight across it; a row left on its own by - the break is drawn with a vertical bar between its bounds. + the break is drawn with a vertical bar between its bounds. A reference a + results object declares between two horizons is no longer rounded onto the + neighbouring estimated row (which was then styled as the reference). - `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 diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index a3523269b..0498cbff5 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -744,6 +744,17 @@ def _render_event_study_plotly( return fig +def _exact_reference_label(label: Any) -> Any: + """A producer-declared reference label, unrounded: an integral number + becomes ``int`` (matching integer horizon keys), anything else is returned + as given.""" + try: + as_float = float(label) + except (TypeError, ValueError): + return label + return int(as_float) if as_float.is_integer() else label + + def _reference_is_verified(results: Any, reference_period: Any) -> bool: """Whether ``reference_period`` is a normalization anchor the PRODUCER declared, as opposed to the raw route's unconditional ``-1`` fallback @@ -765,8 +776,10 @@ def _reference_is_verified(results: Any, reference_period: Any) -> bool: return False if hasattr(results, "placebo_event_study") and hasattr(results, "L_max"): return True - if getattr(results, "reference_period", None) is not None: - return True + declared = getattr(results, "reference_period", None) + if declared is not None: + # The declared reference must be THIS horizon, not merely exist. + return bool(_exact_reference_label(declared) == reference_period) surface = getattr(results, "event_study_effects", None) if isinstance(surface, dict): entry = surface.get(reference_period) @@ -1142,7 +1155,11 @@ def _extract_plot_data( # zero count is a genuine empty horizon and never a marker). explicit_ref = getattr(results, "reference_period", None) if explicit_ref is not None: - reference_period = int(explicit_ref) + # Keep the producer's exact label. An integral value is + # normalized to int (the horizon keys are ints); a + # non-integral one (a reference that sits between horizons) + # is NOT rounded onto a neighbouring ESTIMATED row. + reference_period = _exact_reference_label(explicit_ref) else: for period, effect_data in results.event_study_effects.items(): if effect_data.get("is_reference", False): diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 436a88661..4df2eedb2 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7317,7 +7317,9 @@ should be a deliberate user choice. declared - a marked row of a container, an `is_reference` row or `reference_period` attribute on a results object, the dCDH reference at 0 - not a row that is merely styled as the reference by the `-1` fallback, which under a varying base is an estimated - placebo, whatever its SE). A run of a single row has no area to fill and is drawn as a vertical bar between + placebo, whatever its SE. A declared `reference_period` counts only for the horizon it + names exactly: a reference that sits between horizons (for example `-0.5`) is kept as + given and is no longer rounded onto a neighbouring estimated row). A run of a single row has no area to fill and is drawn as a vertical bar between its bounds, so a valid interval isolated by the split stays visible. Before, the band skipped a row without an interval and filled straight across it. - **Note (WooldridgeDiD route):** a `WooldridgeDiDResults` passed to `plot_event_study` is diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 4098e2114..2cd9f1f5f 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -1246,11 +1246,20 @@ def test_no_polygon_spans_a_fallback_row_with_no_standard_error(self, kwargs): results = self._varying_base((float("nan"), float("nan"))) results.event_study_effects[-1]["se"] = float("nan") fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - x_minus_one = sorted(results.event_study_effects).index(-1) - for band in _toself_bands(fig): - xs = [x for x in band.x if x is not None] - assert x_minus_one not in xs and not (min(xs) < x_minus_one < max(xs)) + horizons = sorted(results.event_study_effects) + x_minus_one = horizons.index(-1) + # -1: a marker and nothing else assert x_minus_one in _marker_xs(fig) + assert [b for b in _vertical_bars(fig) if b.x[0] == x_minus_one] == [] + # -2 is isolated and keeps its interval as a bar + (bar,) = [b for b in _vertical_bars(fig) if b.x[0] == horizons.index(-2)] + assert sorted(float(y) for y in bar.y) == pytest.approx( + [0.05 - 1.959963984540054 * 0.10, 0.05 + 1.959963984540054 * 0.10] + ) + # 0 and 1 keep one band, which stops short of -1 + (band,) = _toself_bands(fig) + xs = [x for x in band.x if x is not None] + assert min(xs) == horizons.index(0) and max(xs) == horizons.index(1) def test_an_explicit_reference_is_a_constraint(self): """The caller normalizes on -1: that row is now a constraint and the @@ -1263,6 +1272,43 @@ def test_an_explicit_reference_is_a_constraint(self): xs = [x for x in band.x if x is not None] assert min(xs) == 0 and max(xs) == 3 + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) + def test_a_declared_reference_between_horizons_does_not_make_a_neighbour_a_constraint( + self, kwargs + ): + """A producer that declares its reference at -0.5 names no plotted + horizon. It must not be rounded onto event time 0, an ESTIMATED effect: + when that row's inference is undefined the band breaks there.""" + pytest.importorskip("plotly") + + results = self._varying_base((-0.18, 0.22)) + results.reference_period = -0.5 + row = results.event_study_effects[0] + row.update(conf_int=(float("nan"), float("nan")), p_value=float("nan")) + fig = plot_event_study(results, backend="plotly", show=False, **kwargs) + horizons = sorted(results.event_study_effects) + x_zero = horizons.index(0) + for band in _toself_bands(fig): + xs = [x for x in band.x if x is not None] + assert x_zero not in xs and not (min(xs) < x_zero < max(xs)) + assert [b for b in _vertical_bars(fig) if b.x[0] == x_zero] == [] + assert x_zero in _marker_xs(fig) + # the rows before it keep their band; the row after it keeps a bar + (band,) = _toself_bands(fig) + assert max(x for x in band.x if x is not None) == horizons.index(-1) + assert [b for b in _vertical_bars(fig) if b.x[0] == horizons.index(1)] + + def test_an_integral_declared_reference_is_a_constraint(self): + pytest.importorskip("plotly") + + results = self._varying_base((float("nan"), float("nan"))) + results.event_study_effects[-1].update(effect=0.0, se=float("nan")) + results.reference_period = -1.0 + fig = plot_event_study(results, backend="plotly", show=False) + (band,) = _toself_bands(fig) + xs = [x for x in band.x if x is not None] + assert min(xs) == 0 and max(xs) == 3 + def test_a_defined_row_at_minus_one_keeps_one_band(self): pytest.importorskip("plotly") From 13cc9e772bc933727e0263234268acce843d0474 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 09:55:14 -0500 Subject: [PATCH 09/15] fix(visualization): compare a declared reference label without a float round-trip; end-to-end plot test on a fitted model --- diff_diff/visualization/_event_study.py | 21 +++-- tests/test_visualization.py | 113 ++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 7 deletions(-) diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index 0498cbff5..e865f61d1 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -745,14 +745,21 @@ def _render_event_study_plotly( def _exact_reference_label(label: Any) -> Any: - """A producer-declared reference label, unrounded: an integral number - becomes ``int`` (matching integer horizon keys), anything else is returned - as given.""" - try: - as_float = float(label) - except (TypeError, ValueError): + """A producer-declared reference label, unrounded and without loss. + + An integer is returned as ``int`` as is (no float round-trip, which would + move integers beyond 2**53 onto a neighbouring value). A float holding an + integral value becomes ``int`` (matching integer horizon keys); any other + float, and any non-numeric label, is returned as given. + """ + if isinstance(label, (bool, np.bool_)): return label - return int(as_float) if as_float.is_integer() else label + if isinstance(label, (int, np.integer)): + return int(label) + if isinstance(label, (float, np.floating)): + as_float = float(label) + return int(as_float) if as_float.is_integer() else label + return label def _reference_is_verified(results: Any, reference_period: Any) -> bool: diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 2cd9f1f5f..b2e53dab3 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -1333,6 +1333,119 @@ def test_a_real_reference_constraint_still_bridges(self): assert min(xs) == 0 and max(xs) == 3 +class TestDeclaredReferenceLabelIsExact: + """A reference label declared on a results object is compared exactly: + no float round-trip (integers beyond 2**53 would land on a neighbour) and + no rounding of a label that sits between horizons.""" + + def test_labels_are_kept_exactly(self): + from diff_diff.visualization._event_study import _exact_reference_label + + big = -9007199254740995 # not representable as a float + assert _exact_reference_label(big) == big and isinstance(_exact_reference_label(big), int) + assert _exact_reference_label(np.int64(-1)) == -1 + assert _exact_reference_label(2.0) == 2 and isinstance(_exact_reference_label(2.0), int) + assert _exact_reference_label(-0.5) == -0.5 + assert _exact_reference_label("2019") == "2019" + + def test_only_the_named_horizon_is_verified(self): + from types import SimpleNamespace + + from diff_diff.visualization._event_study import _reference_is_verified + + big = -9007199254740995 + declared = SimpleNamespace(reference_period=big, event_study_effects={}) + assert _reference_is_verified(declared, big) is True + assert _reference_is_verified(declared, big - 1) is False + between = SimpleNamespace(reference_period=-0.5, event_study_effects={}) + assert _reference_is_verified(between, 0) is False + assert _reference_is_verified(between, -1) is False + + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) + def test_neighbour_of_a_huge_declared_reference_breaks_the_band(self, kwargs): + pytest.importorskip("plotly") + from types import SimpleNamespace + + big = -9007199254740995 + nan_ci = (float("nan"), float("nan")) + + def row(effect, ci): + return {"effect": effect, "se": 0.1, "conf_int": ci, "p_value": 0.5, "n_obs": 30} + + results = SimpleNamespace( + reference_period=big, + event_study_effects={ + big - 2: row(0.1, (-0.1, 0.3)), + big - 1: row(2.0, nan_ci), # estimated, inference undefined + big: {"effect": 0.0, "se": float("nan"), "conf_int": nan_ci, "is_reference": True}, + big + 1: row(1.0, (0.8, 1.2)), + big + 2: row(1.1, (0.9, 1.3)), + }, + ) + fig = plot_event_study(results, backend="plotly", show=False, **kwargs) + x_undefined = 1 + for band in _toself_bands(fig): + xs = [x for x in band.x if x is not None] + assert x_undefined not in xs and not (min(xs) < x_undefined < max(xs)) + assert [b for b in _vertical_bars(fig) if b.x[0] == x_undefined] == [] + assert x_undefined in _marker_xs(fig) + + +class TestPlotEventStudyFittedUndefinedRows: + """End to end on a fitted model: SunAbraham with ``vcov_type="hc2_bm"`` and + a cohort of one unit stores a finite SE and NaN inference at the horizons + only that unit identifies. Plotting the results object keeps their markers, + draws no interval for them and does not shade across them.""" + + @staticmethod + def _fit(): + from diff_diff import SunAbraham + + rows, unit = [], 0 + for g, n in ((2.5, 10), (3.0, 1), (np.inf, 12)): + for _ in range(n): + for t in range(8): + effect = 2.0 if (np.isfinite(g) and t >= g) else 0.0 + y = 0.3 * t + (unit % 4) + effect + 0.2 * ((unit * 5 + t * 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_undefined_rows_keep_markers_and_get_no_interval(self, kwargs): + pytest.importorskip("plotly") + + results = self._fit() + surface = results.event_study_effects + horizons = sorted(surface) + undefined = [ + h + for h in horizons + if np.isfinite(surface[h]["se"]) + and surface[h]["se"] > 0 + and np.isnan(surface[h]["conf_int"][0]) + ] + defined = [h for h in horizons if np.isfinite(surface[h]["conf_int"][0])] + assert undefined and len(defined) >= 4 # the fixture exercises both kinds + fig = plot_event_study(results, backend="plotly", show=False, **kwargs) + markers = _marker_xs(fig) + covered = set() + for band in _toself_bands(fig): + xs = [x for x in band.x if x is not None] + covered.update(range(int(min(xs)), int(max(xs)) + 1)) + covered.update(int(b.x[0]) for b in _vertical_bars(fig)) + for h in undefined: + x = horizons.index(h) + assert x in markers and x not in covered + for h in defined: + assert horizons.index(h) in covered + + class TestPlotEventStudyWooldridge: """plot_event_study accepts a WooldridgeDiDResults by converting it to the unified container, so it takes the EventStudyResults route end to end.""" From b8a69a0c6e8045d2b9a32d5ca6035314b326794c Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 10:09:22 -0500 Subject: [PATCH 10/15] fix(visualization): compare horizon and reference labels exactly, across numeric types Plain == converts an integer reference to float, so a float horizon one away from it beyond 2**53 compared equal and was styled, and bridged, as the reference. All reference-label comparisons in plot_event_study go through one exact comparator (rationals at native precision). The fitted test now uses a fixture whose shared reference is -0.5. --- diff_diff/visualization/_event_study.py | 57 +++++++++--- docs/methodology/REGISTRY.md | 4 +- tests/test_visualization.py | 110 +++++++++++++++++++----- 3 files changed, 136 insertions(+), 35 deletions(-) diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index e865f61d1..97d6308cf 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -1,6 +1,7 @@ """Event study visualization functions.""" import warnings +from fractions import Fraction from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, Union import numpy as np @@ -290,7 +291,7 @@ def plot_event_study( # from the SE, which must not revive inference the producer # disabled (their normalized point estimates still plot). se = { - p: (np.nan if (p == reference_period or p in undefined_inference) else s) + p: (np.nan if (_same_label(p, reference_period) or p in undefined_inference) else s) for p, s in se.items() } # REGISTRY (Event Study Plotting): after explicit normalization, @@ -349,7 +350,8 @@ def plot_event_study( 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) + std_err > 0 + or (_same_label(period, reference_period) and effect == 0.0 and std_err == 0.0) ): # A zero/negative-SE row has all-NaN stored inference # (safe_inference), and effect +/- z*0 would draw a finite @@ -376,7 +378,7 @@ def plot_event_study( # Row-aligned marks (multi-reference containers) hollow # every normalization anchor; the scalar covers the # single-reference routes. - "is_reference": period == reference_period + "is_reference": _same_label(period, reference_period) or (reference_marks is not None and period in reference_marks), # A normalization CONSTRAINT, as opposed to reference styling: # a row the caller normalized on, a producer-declared @@ -384,7 +386,8 @@ def plot_event_study( # fallback styles a marker but is not a constraint. "is_constraint": (reference_marks is not None and period in reference_marks) or ( - period == reference_period and (reference_period_explicit or reference_verified) + _same_label(period, reference_period) + and (reference_period_explicit or reference_verified) ), } ) @@ -744,21 +747,53 @@ def _render_event_study_plotly( return fig +def _label_key(label: Any) -> Any: + """An exact, comparable key for a horizon label. + + Numbers are compared as exact rationals at their NATIVE precision, so + labels of different numeric types are equal only when they are the same + number: ``np.float64(-9007199254740996)`` does not match the integer + ``-9007199254740995`` (plain ``==`` converts the integer to float and says + it does), and an extended-precision float is not narrowed first. + """ + if isinstance(label, (bool, np.bool_)): + return ("bool", bool(label)) + if isinstance(label, (int, np.integer)): + return ("number", Fraction(int(label))) + if isinstance(label, (float, np.floating)): + if not np.isfinite(label): + return ("non-finite", repr(label)) + return ("number", Fraction(*label.as_integer_ratio())) + return ("other", label) + + +def _same_label(a: Any, b: Any) -> bool: + """Exact equality of two horizon labels (see :func:`_label_key`).""" + if a is None or b is None: + return a is b + try: + return bool(_label_key(a) == _label_key(b)) + except Exception: + return False + + def _exact_reference_label(label: Any) -> Any: """A producer-declared reference label, unrounded and without loss. - An integer is returned as ``int`` as is (no float round-trip, which would - move integers beyond 2**53 onto a neighbouring value). A float holding an - integral value becomes ``int`` (matching integer horizon keys); any other - float, and any non-numeric label, is returned as given. + An integer is returned as ``int`` as is. A float holding an integral + value, tested at its native precision, becomes ``int`` (matching integer + horizon keys); any other float, and any non-numeric label, is returned as + given. """ if isinstance(label, (bool, np.bool_)): return label if isinstance(label, (int, np.integer)): return int(label) if isinstance(label, (float, np.floating)): - as_float = float(label) - return int(as_float) if as_float.is_integer() else label + if not np.isfinite(label): + return label + numerator, denominator = label.as_integer_ratio() + return int(numerator) if denominator == 1 else label return label @@ -786,7 +821,7 @@ def _reference_is_verified(results: Any, reference_period: Any) -> bool: declared = getattr(results, "reference_period", None) if declared is not None: # The declared reference must be THIS horizon, not merely exist. - return bool(_exact_reference_label(declared) == reference_period) + return _same_label(_exact_reference_label(declared), reference_period) surface = getattr(results, "event_study_effects", None) if isinstance(surface, dict): entry = surface.get(reference_period) diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 4df2eedb2..8c6279823 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7319,7 +7319,9 @@ should be a deliberate user choice. as the reference by the `-1` fallback, which under a varying base is an estimated placebo, whatever its SE. A declared `reference_period` counts only for the horizon it names exactly: a reference that sits between horizons (for example `-0.5`) is kept as - given and is no longer rounded onto a neighbouring estimated row). A run of a single row has no area to fill and is drawn as a vertical bar between + given and is no longer rounded onto a neighbouring estimated row. Labels are compared as exact + numbers at their native precision, so a horizon stored as a float does not match an + integer reference one away from it beyond 2**53). A run of a single row has no area to fill and is drawn as a vertical bar between its bounds, so a valid interval isolated by the split stays visible. Before, the band skipped a row without an interval and filled straight across it. - **Note (WooldridgeDiD route):** a `WooldridgeDiDResults` passed to `plot_event_study` is diff --git a/tests/test_visualization.py b/tests/test_visualization.py index b2e53dab3..62e982aa6 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -1348,6 +1348,23 @@ def test_labels_are_kept_exactly(self): assert _exact_reference_label(-0.5) == -0.5 assert _exact_reference_label("2019") == "2019" + def test_labels_of_different_numeric_types_compare_exactly(self): + from diff_diff.visualization._event_study import _exact_reference_label, _same_label + + big = -9007199254740995 + # plain == converts the integer to float and reports these as equal + assert np.float64(big - 1) == big + assert not _same_label(np.float64(big - 1), big) + assert _same_label(np.float64(-1.0), -1) and _same_label(np.int64(3), 3.0) + assert _same_label(-0.5, np.float64(-0.5)) and not _same_label(-0.5, 0) + assert not _same_label(None, 0) and _same_label("2019", "2019") + # integrality is tested at native precision, not after narrowing + wide = np.longdouble("-1") - np.finfo(np.longdouble).eps + if wide != np.longdouble("-1"): + assert _exact_reference_label(wide) is wide + assert not _same_label(wide, -1) + assert _exact_reference_label(np.longdouble("2")) == 2 + def test_only_the_named_horizon_is_verified(self): from types import SimpleNamespace @@ -1390,23 +1407,69 @@ def row(effect, ci): assert [b for b in _vertical_bars(fig) if b.x[0] == x_undefined] == [] assert x_undefined in _marker_xs(fig) + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) + def test_float_horizon_next_to_an_integer_reference_is_not_the_reference(self, kwargs): + """Horizons stored as NumPy floats, reference declared as a Python + integer one above an estimated horizon: ``==`` across the two types + calls them equal. The estimated row must not be styled as the + reference, and the band must break at it.""" + pytest.importorskip("plotly") + from types import SimpleNamespace + + big = -9007199254740995 + nan_ci = (float("nan"), float("nan")) + + def row(effect, ci): + return {"effect": effect, "se": 0.1, "conf_int": ci, "p_value": 0.5, "n_obs": 30} + + neighbour = np.float64(big - 1) + assert neighbour == big # the lossy comparison this guards against + results = SimpleNamespace( + reference_period=big, + event_study_effects={ + np.float64(big - 5): row(0.1, (-0.1, 0.3)), + np.float64(big - 3): row(0.2, (0.0, 0.4)), + neighbour: row(2.0, nan_ci), # estimated, inference undefined + np.float64(big + 3): row(1.0, (0.8, 1.2)), + np.float64(big + 5): row(1.1, (0.9, 1.3)), + }, + ) + fig = plot_event_study(results, backend="plotly", show=False, **kwargs) + x_undefined = 2 + bands = _toself_bands(fig) + assert len(bands) == 2 + for band in bands: + xs = [x for x in band.x if x is not None] + assert x_undefined not in xs and not (min(xs) < x_undefined < max(xs)) + assert [b for b in _vertical_bars(fig) if b.x[0] == x_undefined] == [] + # drawn as an ordinary estimate, not a hollow reference marker + reference_markers = [ + t + for t in fig.data + if getattr(t, "mode", None) == "markers" + and "open" in str(getattr(t.marker, "symbol", "")) + ] + assert all(x_undefined not in (t.x or ()) for t in reference_markers) + assert x_undefined in _marker_xs(fig) + class TestPlotEventStudyFittedUndefinedRows: - """End to end on a fitted model: SunAbraham with ``vcov_type="hc2_bm"`` and - a cohort of one unit stores a finite SE and NaN inference at the horizons - only that unit identifies. Plotting the results object keeps their markers, - draws no interval for them and does not shade across them.""" + """End to end on a fitted model: SunAbraham with ``vcov_type="hc2_bm"``. + Cohorts adopt at 2.5 and 3.5, and calendar period 3.5 is observed only for + the one-unit cohort and the never-treated units. The fit declares a shared + reference at -0.5 (between horizons) and stores a finite SE with NaN + inference at event time 0, which only the single unit identifies.""" @staticmethod def _fit(): from diff_diff import SunAbraham rows, unit = [], 0 - for g, n in ((2.5, 10), (3.0, 1), (np.inf, 12)): + 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 range(8): + 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 + t * 3) % 7) + 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"]) @@ -1416,34 +1479,35 @@ def _fit(): data, outcome="outcome", unit="unit", time="period", first_treat="first_treat" ) + def test_the_fit_declares_a_fractional_reference_and_withholds_inference_at_zero(self): + results = self._fit() + assert results.reference_period == -0.5 + row = results.event_study_effects[0.0] + assert np.isfinite(row["se"]) and row["se"] > 0 + assert np.isnan(row["conf_int"][0]) and np.isnan(row["p_value"]) + for neighbour in (-1.5, 0.5): + assert np.isfinite(results.event_study_effects[neighbour]["conf_int"][0]) + @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) - def test_undefined_rows_keep_markers_and_get_no_interval(self, kwargs): + def test_event_time_zero_keeps_its_marker_and_gets_no_interval(self, kwargs): pytest.importorskip("plotly") results = self._fit() surface = results.event_study_effects horizons = sorted(surface) - undefined = [ - h - for h in horizons - if np.isfinite(surface[h]["se"]) - and surface[h]["se"] > 0 - and np.isnan(surface[h]["conf_int"][0]) - ] - defined = [h for h in horizons if np.isfinite(surface[h]["conf_int"][0])] - assert undefined and len(defined) >= 4 # the fixture exercises both kinds fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - markers = _marker_xs(fig) covered = set() for band in _toself_bands(fig): xs = [x for x in band.x if x is not None] covered.update(range(int(min(xs)), int(max(xs)) + 1)) covered.update(int(b.x[0]) for b in _vertical_bars(fig)) - for h in undefined: - x = horizons.index(h) - assert x in markers and x not in covered - for h in defined: - assert horizons.index(h) in covered + x_zero = horizons.index(0.0) + assert x_zero in _marker_xs(fig) and x_zero not in covered + # the horizons on both sides keep their intervals + assert horizons.index(-1.5) in covered and horizons.index(0.5) in covered + for h in horizons: + if np.isfinite(surface[h]["conf_int"][0]): + assert horizons.index(h) in covered class TestPlotEventStudyWooldridge: From 4605dd7ebde8752abc6f3c7659ae61dcf5228e8c Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 10:29:35 -0500 Subject: [PATCH 11/15] refactor(visualization): reduce the plot change to the undefined-inference fix Keep only: a results object passed directly no longer has intervals rebuilt from the SE for rows whose stored interval is NaN (generic and dCDH routes). The Plotly band splitting, the one-row bar, reference provenance and exact label comparison are taken back out; the Plotly band behavior and the raw route's reference handling are logged in TODO.md for their own change. --- TODO.md | 1 + ...0261127-stacked-did-anticipation-survey.md | 17 +- diff_diff/visualization/_event_study.py | 167 +----- docs/methodology/REGISTRY.md | 35 +- tests/test_visualization.py | 529 ++---------------- 5 files changed, 83 insertions(+), 666 deletions(-) diff --git a/TODO.md b/TODO.md index b5436617b..e7aeb9e45 100644 --- a/TODO.md +++ b/TODO.md @@ -57,6 +57,7 @@ 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 | +| `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 comparison of horizon labels of mixed numeric types. | `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 | diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md index 5e7cf6110..03975a404 100644 --- a/changelog.d/20261127-stacked-did-anticipation-survey.md +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -61,18 +61,15 @@ 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. -- **`plot_event_study(results)` no longer draws intervals for rows whose +- **`plot_event_study(results)` no longer rebuilds intervals for rows whose stored inference is undefined.** A results object passed directly has its - intervals rebuilt from the standard error; a row with a finite standard + intervals recomputed from the standard error; a row with a finite standard error and a NaN stored interval (inference failed closed, for example a - survey design with zero degrees of freedom) is now drawn as a point with no - interval, as the `aggregate("event_study")` container already was; this - holds for dCDH results (effects and placebos) as well. On the - Plotly backend the shaded band is now broken at any estimated row without an - interval, where it used to fill straight across it; a row left on its own by - the break is drawn with a vertical bar between its bounds. A reference a - results object declares between two horizons is no longer rounded onto the - neighbouring estimated row (which was then styled as the reference). + 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 diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index 97d6308cf..90a82bccd 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -1,7 +1,6 @@ """Event study visualization functions.""" import warnings -from fractions import Fraction from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, Union import numpy as np @@ -219,7 +218,6 @@ def plot_event_study( ci_upper_override = None reference_marks: Optional[Set[Any]] = None undefined_inference: Set[Any] = set() - reference_verified = False if results is not None: ( effects, @@ -250,7 +248,6 @@ def plot_event_study( # If reference was inferred from results, it was NOT explicitly provided if reference_inferred: reference_period_explicit = False - reference_verified = _reference_is_verified(results, reference_period) # Channel selection: the band channel when the user wants # simultaneous bands; otherwise the POINTWISE channel - the # producer's stored intervals (NaN preserved), for input routes @@ -291,7 +288,7 @@ def plot_event_study( # from the SE, which must not revive inference the producer # disabled (their normalized point estimates still plot). se = { - p: (np.nan if (_same_label(p, reference_period) or p in undefined_inference) else s) + p: (np.nan if (p == reference_period or p in undefined_inference) else s) for p, s in se.items() } # REGISTRY (Event Study Plotting): after explicit normalization, @@ -350,8 +347,7 @@ def plot_event_study( ci_lower = np.nan ci_upper = np.nan elif np.isfinite(std_err) and ( - std_err > 0 - or (_same_label(period, reference_period) and effect == 0.0 and std_err == 0.0) + std_err > 0 or (period == reference_period and effect == 0.0 and std_err == 0.0) ): # A zero/negative-SE row has all-NaN stored inference # (safe_inference), and effect +/- z*0 would draw a finite @@ -378,17 +374,8 @@ def plot_event_study( # Row-aligned marks (multi-reference containers) hollow # every normalization anchor; the scalar covers the # single-reference routes. - "is_reference": _same_label(period, reference_period) + "is_reference": period == reference_period or (reference_marks is not None and period in reference_marks), - # A normalization CONSTRAINT, as opposed to reference styling: - # a row the caller normalized on, a producer-declared - # reference, or a marked anchor. The raw route's bare ``-1`` - # fallback styles a marker but is not a constraint. - "is_constraint": (reference_marks is not None and period in reference_marks) - or ( - _same_label(period, reference_period) - and (reference_period_explicit or reference_verified) - ), } ) @@ -638,47 +625,13 @@ def _render_event_study_plotly( x=period_to_x[reference_period], line_dash="dot", line_color="gray", line_width=1 ) - # CI band (filled area). One polygon per run of rows that carry an - # interval: an ESTIMATED row without one (undefined inference, a zero or - # missing SE) ends the run, so the fill never spans it and implies bounds - # it does not have. A normalization constraint without an interval is not - # an estimate and does not break the band. + # CI band (filled area) has_ci = [not (np.isnan(lo) or np.isnan(hi)) for lo, hi in zip(ci_lower, ci_upper)] - # Reference STYLING is not enough to bridge a gap: the raw routes fall back - # to styling event time -1 when the producer marks no reference, and under - # a varying base that row is an estimated placebo. Only a normalization - # constraint - a reference the caller normalized on or the producer - # declared (``is_constraint``, resolved in ``plot_event_study``) - lets the - # band continue. - is_constraint = ( - df["is_constraint"].tolist() if "is_constraint" in df.columns else [False] * len(df) - ) - runs: List[List[int]] = [[]] - for i, (has, constraint) in enumerate(zip(has_ci, is_constraint)): - if has: - runs[-1].append(i) - elif not constraint: - runs.append([]) - for run in runs: - if not run: - continue - ci_x = [period_to_x[periods[i]] for i in run] - ci_lo = [ci_lower[i] for i in run] - ci_hi = [ci_upper[i] for i in run] - if len(run) == 1: - # A one-row run has no area to fill: draw its interval as a - # vertical bar so a valid interval is never invisible. - fig.add_trace( - go.Scatter( - x=[ci_x[0], ci_x[0]], - y=[ci_lo[0], ci_hi[0]], - mode="lines", - line=dict(color=_color_to_rgba(color, 0.45), width=6), - showlegend=False, - hoverinfo="skip", - ) - ) - continue + ci_x = [period_to_x[p] for p, h in zip(periods, has_ci) if h] + ci_lo = [lo for lo, h in zip(ci_lower, has_ci) if h] + ci_hi = [hi for hi, h in zip(ci_upper, has_ci) if h] + + if ci_x: fig.add_trace( go.Scatter( x=ci_x + ci_x[::-1], @@ -747,95 +700,13 @@ def _render_event_study_plotly( return fig -def _label_key(label: Any) -> Any: - """An exact, comparable key for a horizon label. - - Numbers are compared as exact rationals at their NATIVE precision, so - labels of different numeric types are equal only when they are the same - number: ``np.float64(-9007199254740996)`` does not match the integer - ``-9007199254740995`` (plain ``==`` converts the integer to float and says - it does), and an extended-precision float is not narrowed first. - """ - if isinstance(label, (bool, np.bool_)): - return ("bool", bool(label)) - if isinstance(label, (int, np.integer)): - return ("number", Fraction(int(label))) - if isinstance(label, (float, np.floating)): - if not np.isfinite(label): - return ("non-finite", repr(label)) - return ("number", Fraction(*label.as_integer_ratio())) - return ("other", label) - - -def _same_label(a: Any, b: Any) -> bool: - """Exact equality of two horizon labels (see :func:`_label_key`).""" - if a is None or b is None: - return a is b - try: - return bool(_label_key(a) == _label_key(b)) - except Exception: - return False - - -def _exact_reference_label(label: Any) -> Any: - """A producer-declared reference label, unrounded and without loss. - - An integer is returned as ``int`` as is. A float holding an integral - value, tested at its native precision, becomes ``int`` (matching integer - horizon keys); any other float, and any non-numeric label, is returned as - given. - """ - if isinstance(label, (bool, np.bool_)): - return label - if isinstance(label, (int, np.integer)): - return int(label) - if isinstance(label, (float, np.floating)): - if not np.isfinite(label): - return label - numerator, denominator = label.as_integer_ratio() - return int(numerator) if denominator == 1 else label - return label - - -def _reference_is_verified(results: Any, reference_period: Any) -> bool: - """Whether ``reference_period`` is a normalization anchor the PRODUCER - declared, as opposed to the raw route's unconditional ``-1`` fallback - (which only styles a marker, and under a varying base lands on an - estimated placebo). - - Verified sources: an ``EventStudyResults`` container (its reference rows - are marked), the dCDH route (reference synthesized at 0), a - ``reference_period`` attribute on the results, or an ``is_reference`` key - on the row of a raw ``event_study_effects`` dict. - """ - if results is None or reference_period is None: - return False - from diff_diff.results_base import EventStudyResults - - if isinstance(results, EventStudyResults): - return True - if isinstance(results, pd.DataFrame): - return False - if hasattr(results, "placebo_event_study") and hasattr(results, "L_max"): - return True - declared = getattr(results, "reference_period", None) - if declared is not None: - # The declared reference must be THIS horizon, not merely exist. - return _same_label(_exact_reference_label(declared), reference_period) - surface = getattr(results, "event_study_effects", None) - if isinstance(surface, dict): - entry = surface.get(reference_period) - return bool(isinstance(entry, dict) and entry.get("is_reference", False)) - return False - - 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 an all-NaN stored interval (the producer failed inference closed, e.g. a survey design with zero degrees of freedom). Reference rows are constraints, not estimates, and never qualify. The raw routes recompute intervals from the SE, so such - rows must be handed back on the pointwise channel as NaN.""" + rows are handed back on the pointwise channel as NaN.""" if entry.get("is_reference", False): return False stored_ci = entry.get("conf_int") @@ -1157,13 +1028,11 @@ def _extract_plot_data( ci_upper_override = {} has_cband = False - # Rows whose STORED inference is undefined: a finite, positive SE - # with an all-NaN stored interval (the producer failed inference - # closed, e.g. a survey design with zero degrees of freedom). This - # route recomputes intervals from the SE, so those rows are handed - # back on the pointwise channel as NaN - the plot then draws their - # point estimates and no interval, with or without an explicit - # reference period (REGISTRY Event Study Plotting). + # 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] = {} @@ -1197,11 +1066,7 @@ def _extract_plot_data( # zero count is a genuine empty horizon and never a marker). explicit_ref = getattr(results, "reference_period", None) if explicit_ref is not None: - # Keep the producer's exact label. An integral value is - # normalized to int (the horizon keys are ints); a - # non-integral one (a reference that sits between horizons) - # is NOT rounded onto a neighbouring ESTIMATED row. - reference_period = _exact_reference_label(explicit_ref) + reference_period = int(explicit_ref) else: for period, effect_data in results.event_study_effects.items(): if effect_data.get("is_reference", False): diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 8c6279823..ecc20dfae 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -7301,29 +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 route):** a results object passed +- **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. This covers both raw routes: the generic `event_study_effects` route and the - dCDH route (its effects and its placebo horizons). A row whose STORED interval is NaN while its SE is finite and positive - - inference the producer failed closed, such as a survey design with zero degrees of - freedom - is exempt: its point estimate is drawn with no interval, on the pointwise and + 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 NaN 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 Plotly backend the filled band is drawn as one polygon per run of - rows that carry an interval: an estimated row without one ends the run, so the fill does - not span it (a normalization constraint without an interval does not break the band; that - means a reference the caller normalized on with `reference_period=`, or one the producer - declared - a marked row of a container, an `is_reference` row or `reference_period` - attribute on a results object, the dCDH reference at 0 - not a row that is merely styled - as the reference by the `-1` fallback, which under a varying base is an estimated - placebo, whatever its SE. A declared `reference_period` counts only for the horizon it - names exactly: a reference that sits between horizons (for example `-0.5`) is kept as - given and is no longer rounded onto a neighbouring estimated row. Labels are compared as exact - numbers at their native precision, so a horizon stored as a float does not match an - integer reference one away from it beyond 2**53). A run of a single row has no area to fill and is drawn as a vertical bar between - its bounds, so a valid interval isolated by the split stays visible. Before, the band - skipped a row without an interval and filled straight across it. + 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 @@ -7354,9 +7345,9 @@ should be a deliberate user choice. estimated row with effect exactly 0 and se 0 at the fallback position retains today's bar - today's behavior preserved, not a new defect). The dCDH route's synthesized reference carries `se = NaN` and keeps its hollow-marker-no-bar rendering, unchanged. - On the plotly backend the gated row breaks the CI band, as any estimated row without an - interval does (undefined-stored-inference Note above); the band is no longer interpolated - across it. + Plotly caveat: the plotly renderer filters NaN-CI rows out of the CI band and + interpolates the polygon across the gap (pre-existing NaN-SE convention); the matplotlib + backend is where the gated interval visibly disappears. - **Note (`plot_dose_response` zero-SE gate and band labeling):** the raw-DataFrame `se` branch adopts the same gate: rows with non-positive or non-finite `se` have their reconstructed band masked to NaN with a `UserWarning` (previously a zero-SE row drew a finite zero-width band); the plotly renderer filters non-finite-CI rows out of the `toself` band polygon and bridges the gap (the `plot_group_effects` convention above; CI values only - the dose axis may be non-numeric), and both renderers suppress an all-masked band entirely (no stray legend entry). Band LABELING states the confidence level only where it is knowable: the requested `alpha` on the DataFrame-`se` branch (validated strictly inside (0, 1)), `results.alpha` on `results=` input, and the level-free "CI" for bare-curve and explicit-CI input. Alpha semantics deliberately DIVERGE from `plot_group_effects`: that surface recomputes `effect +/- z*SE` at a requested alpha, while `plot_dose_response` warns-and-ignores an explicit `alpha` on non-`se` input, because stored/explicit-CI dose-response inputs cannot be recomputed. `plot_honest_event_study`'s raw (non-container) routes mirror the container's retained-row semantics: zero/non-finite-SE rows are excluded up front (explicitly requesting one raises), the reference row - now diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 62e982aa6..1603f735a 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -912,9 +912,10 @@ def _zero_df_stacked_fit(zero_df=True): class TestPlotEventStudyUndefinedStoredInference: - """The raw-results route recomputes intervals from the SE. A row whose - STORED interval is NaN while its SE is finite (inference failed closed, here - a survey design with zero degrees of freedom) must not get one back.""" + """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() @@ -922,8 +923,8 @@ def test_fit_has_finite_se_and_nan_intervals(self): 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", [{}, {"reference_period": 0}]) - def test_raw_results_draw_points_and_no_intervals(self, kwargs): + @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 @@ -933,28 +934,25 @@ def test_raw_results_draw_points_and_no_intervals(self, kwargs): # 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) - # one marker position per row (the reference bar's caps add markers at its x) 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", [{}, {"reference_period": 0}]) - def test_raw_results_plotly_draw_no_band(self, kwargs): + @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): - ys = [ + 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) ] - return ys - # no band beyond the reference row's zero-width constraint 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 @@ -963,199 +961,29 @@ def band_heights(fig): ) assert any(y != 0.0 for y in band_heights(fig)) - def test_defined_inference_still_draws_intervals(self): + @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) - ax = plot_event_study(results, show=False) - estimated = [e for e in results.event_study_effects.values() if not e.get("is_reference")] - assert len(_plotted_intervals(ax)) >= len(estimated) - plt.close() - - -class TestPlotEventStudyUndefinedRowBetweenDefinedRows: - """One horizon with undefined stored inference (finite SE, NaN interval) - between horizons with valid intervals: its point is drawn, it carries no - interval, and the Plotly band is split there instead of filling across.""" - - @staticmethod - def _mixed(): 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)) - return results - @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": -1}]) - def test_matplotlib_draws_no_interval_on_that_row(self, kwargs): - pytest.importorskip("matplotlib") - import matplotlib.pyplot as plt - - results = self._mixed() ax = plot_event_study(results, show=False, **kwargs) horizons = sorted(results.event_study_effects) - x_undefined = float(horizons.index(1)) drawn = _plotted_intervals(ax) - assert x_undefined not in drawn - estimated = [h for h in horizons if h not in (1, -1)] - assert all(float(horizons.index(h)) in drawn for h in estimated) - assert x_undefined in {p[0] for p in _plotted_points(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}]) - def test_plotly_band_is_split_at_that_row(self, kwargs): - pytest.importorskip("plotly") - - results = self._mixed() - fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - horizons = sorted(results.event_study_effects) - x_undefined = horizons.index(1) - bands = [t for t in fig.data if getattr(t, "fill", None) == "toself"] - assert bands # the rows before it - for band in bands: - xs = [x for x in band.x if x is not None] - assert x_undefined not in xs - assert not (min(xs) < x_undefined < max(xs)) - assert len(set(xs)) >= 2 # a polygon with area, never a zero-width one - # the last horizon is isolated by the split: its VALID interval must be - # visible, drawn as a vertical bar between its bounds - x_last = horizons.index(2) - bars = [ - t - for t in fig.data - if getattr(t, "mode", None) == "lines" - and t.x is not None - and len(t.x) == 2 - and t.x[0] == t.x[1] == x_last - ] - assert len(bars) == 1 - lower, upper = sorted(float(y) for y in bars[0].y) - if "reference_period" not in kwargs: - # a results object passed directly gets the bounds this route - # selects: effect +/- z * SE - row = results.event_study_effects[2] - half = 1.959963984540054 * row["se"] - assert (lower, upper) == pytest.approx((row["effect"] - half, row["effect"] + half)) - assert lower < upper - assert bars[0].line.width >= 2 - - # the row's marker is still drawn - marker_x = [ - x - for trace in fig.data - if getattr(trace, "fill", None) != "toself" and trace.x is not None - for x in trace.x - ] - assert x_undefined in marker_x - - def test_plotly_isolated_row_shows_the_stored_interval_on_the_container_route(self): - pytest.importorskip("plotly") - - results = self._mixed() - surface = results.aggregate("event_study") - frame = surface.to_dataframe().set_index("event_time") - assert np.isnan(frame.loc[1, "conf_int_lower"]) and np.isfinite( - frame.loc[2, "conf_int_lower"] - ) - fig = plot_event_study(surface, backend="plotly", show=False) - x_last = sorted(frame.index).index(2) - bars = [ - t - for t in fig.data - if getattr(t, "mode", None) == "lines" - and t.x is not None - and len(t.x) == 2 - and t.x[0] == t.x[1] == x_last - ] - assert len(bars) == 1 - assert sorted(float(y) for y in bars[0].y) == pytest.approx( - [frame.loc[2, "conf_int_lower"], frame.loc[2, "conf_int_upper"]] - ) - - @pytest.mark.parametrize("route", ["results", "container"]) - @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}, {"reference_period": -1}]) - def test_plotly_marker_split_and_endpoints_on_both_routes(self, route, kwargs): - """Event time 1 (undefined): a marker, no bar, no polygon touching or - spanning it. Event time 2 (isolated, valid): a bar with the endpoints - the route selects - the stored interval on the container route, and - ``effect +/- z * SE`` on the results route or after an explicit - reference (which recomputes from the SE).""" - pytest.importorskip("plotly") - - results = self._mixed() - source = results if route == "results" else results.aggregate("event_study") - fig = plot_event_study(source, backend="plotly", show=False, **kwargs) - horizons = sorted(results.event_study_effects) - x_undefined, x_last = horizons.index(1), horizons.index(2) - - def bars_at(x): - return [ - t - for t in fig.data - if getattr(t, "mode", None) == "lines" - and t.x is not None - and len(t.x) == 2 - and t.x[0] == t.x[1] == x - ] - - markers = [ - x - for t in fig.data - if getattr(t, "mode", None) == "markers" and t.x is not None - for x in t.x - ] - assert x_undefined in markers and x_last in markers - assert bars_at(x_undefined) == [] - for band in (t for t in fig.data if getattr(t, "fill", None) == "toself"): - xs = [x for x in band.x if x is not None] - assert x_undefined not in xs and not (min(xs) < x_undefined < max(xs)) - - (bar,) = bars_at(x_last) - row = results.event_study_effects[2] - if route == "container" and "reference_period" not in kwargs: - expected = sorted(row["conf_int"]) - else: - half = 1.959963984540054 * row["se"] - expected = [row["effect"] - half, row["effect"] + half] - assert sorted(float(y) for y in bar.y) == pytest.approx(expected) - - def test_plotly_band_is_one_polygon_when_every_row_is_defined(self): - pytest.importorskip("plotly") - - fig = plot_event_study(_zero_df_stacked_fit(zero_df=False), backend="plotly", show=False) - assert len([t for t in fig.data if getattr(t, "fill", None) == "toself"]) == 1 - - -def _toself_bands(fig): - return [t for t in fig.data if getattr(t, "fill", None) == "toself"] - - -def _vertical_bars(fig): - return [ - t - for t in fig.data - if getattr(t, "mode", None) == "lines" - and t.x is not None - and len(t.x) == 2 - and t.x[0] == t.x[1] - ] - - -def _marker_xs(fig): - return [ - x - for t in fig.data - if getattr(t, "mode", None) == "markers" and t.x is not None - for x in t.x - ] - class TestPlotEventStudyRawDCDHUndefinedInference: - """The raw dCDH route recomputes intervals from the SE too. A horizon whose - stored interval is NaN (replicate design with undefined df) must plot as a - marker with no interval - including the isolated case ``L_max=1`` without - placebos, where the one-row band segment is drawn as a visible bar.""" + """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): @@ -1171,24 +999,7 @@ def _dcdh(conf_int, placebo=None): } return SimpleNamespace(L_max=1, placebo_event_study=placebo, event_study_effects={1: entry}) - def test_isolated_undefined_horizon_draws_no_interval(self): - pytest.importorskip("plotly") - - fig = plot_event_study( - self._dcdh((float("nan"), float("nan"))), backend="plotly", show=False - ) - assert _vertical_bars(fig) == [] and _toself_bands(fig) == [] - assert len(_marker_xs(fig)) == 2 # the synthesized reference and horizon 1 - - def test_isolated_defined_horizon_draws_its_bar(self): - pytest.importorskip("plotly") - - fig = plot_event_study(self._dcdh((0.8, 2.0)), backend="plotly", show=False) - (bar,) = _vertical_bars(fig) - half = 1.959963984540054 * 0.3 - assert sorted(float(y) for y in bar.y) == pytest.approx([1.4 - half, 1.4 + half]) - - def test_undefined_placebo_and_effect_matplotlib(self): + def test_undefined_effect_and_placebo_get_no_interval(self): pytest.importorskip("matplotlib") import matplotlib.pyplot as plt @@ -1199,266 +1010,30 @@ def test_undefined_placebo_and_effect_matplotlib(self): 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 -class TestPlotEventStudyBandAndFallbackReference: - """When the producer marks no reference, the raw route styles event time -1 - as the reference. Under a varying base that row is an ESTIMATED placebo; if - its inference is undefined the Plotly band must break there, not treat it - as a constraint and fill across it.""" - - @staticmethod - def _varying_base(minus_one_ci): - from types import SimpleNamespace - - def row(effect, se, ci): - return {"effect": effect, "se": se, "conf_int": ci, "p_value": 0.5, "n_obs": 30} - - return SimpleNamespace( - event_study_effects={ - -2: row(0.05, 0.10, (-0.15, 0.25)), - -1: row(0.02, 0.10, minus_one_ci), - 0: row(1.00, 0.12, (0.76, 1.24)), - 1: row(1.10, 0.12, (0.86, 1.34)), - } - ) - - @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) - def test_no_polygon_spans_an_undefined_row_styled_as_reference(self, kwargs): - pytest.importorskip("plotly") - - results = self._varying_base((float("nan"), float("nan"))) - fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - x_minus_one = sorted(results.event_study_effects).index(-1) - for band in _toself_bands(fig): - xs = [x for x in band.x if x is not None] - assert x_minus_one not in xs and not (min(xs) < x_minus_one < max(xs)) - # -2 is isolated by the break and keeps a visible interval - assert [b for b in _vertical_bars(fig) if b.x[0] == 0] - assert x_minus_one in _marker_xs(fig) - - @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) - def test_no_polygon_spans_a_fallback_row_with_no_standard_error(self, kwargs): - """Same, when the estimated placebo at -1 has a NaN SE as well as a NaN - interval (for example a jackknife variance that is not identified - there): a missing SE does not make the row a constraint.""" - pytest.importorskip("plotly") - - results = self._varying_base((float("nan"), float("nan"))) - results.event_study_effects[-1]["se"] = float("nan") - fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - horizons = sorted(results.event_study_effects) - x_minus_one = horizons.index(-1) - # -1: a marker and nothing else - assert x_minus_one in _marker_xs(fig) - assert [b for b in _vertical_bars(fig) if b.x[0] == x_minus_one] == [] - # -2 is isolated and keeps its interval as a bar - (bar,) = [b for b in _vertical_bars(fig) if b.x[0] == horizons.index(-2)] - assert sorted(float(y) for y in bar.y) == pytest.approx( - [0.05 - 1.959963984540054 * 0.10, 0.05 + 1.959963984540054 * 0.10] - ) - # 0 and 1 keep one band, which stops short of -1 - (band,) = _toself_bands(fig) - xs = [x for x in band.x if x is not None] - assert min(xs) == horizons.index(0) and max(xs) == horizons.index(1) - - def test_an_explicit_reference_is_a_constraint(self): - """The caller normalizes on -1: that row is now a constraint and the - band continues across it.""" - pytest.importorskip("plotly") - - results = self._varying_base((-0.18, 0.22)) - fig = plot_event_study(results, backend="plotly", reference_period=-1, show=False) - (band,) = _toself_bands(fig) - xs = [x for x in band.x if x is not None] - assert min(xs) == 0 and max(xs) == 3 - - @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) - def test_a_declared_reference_between_horizons_does_not_make_a_neighbour_a_constraint( - self, kwargs - ): - """A producer that declares its reference at -0.5 names no plotted - horizon. It must not be rounded onto event time 0, an ESTIMATED effect: - when that row's inference is undefined the band breaks there.""" - pytest.importorskip("plotly") - - results = self._varying_base((-0.18, 0.22)) - results.reference_period = -0.5 - row = results.event_study_effects[0] - row.update(conf_int=(float("nan"), float("nan")), p_value=float("nan")) - fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - horizons = sorted(results.event_study_effects) - x_zero = horizons.index(0) - for band in _toself_bands(fig): - xs = [x for x in band.x if x is not None] - assert x_zero not in xs and not (min(xs) < x_zero < max(xs)) - assert [b for b in _vertical_bars(fig) if b.x[0] == x_zero] == [] - assert x_zero in _marker_xs(fig) - # the rows before it keep their band; the row after it keeps a bar - (band,) = _toself_bands(fig) - assert max(x for x in band.x if x is not None) == horizons.index(-1) - assert [b for b in _vertical_bars(fig) if b.x[0] == horizons.index(1)] - - def test_an_integral_declared_reference_is_a_constraint(self): - pytest.importorskip("plotly") - - results = self._varying_base((float("nan"), float("nan"))) - results.event_study_effects[-1].update(effect=0.0, se=float("nan")) - results.reference_period = -1.0 - fig = plot_event_study(results, backend="plotly", show=False) - (band,) = _toself_bands(fig) - xs = [x for x in band.x if x is not None] - assert min(xs) == 0 and max(xs) == 3 - - def test_a_defined_row_at_minus_one_keeps_one_band(self): - pytest.importorskip("plotly") - - fig = plot_event_study(self._varying_base((-0.18, 0.22)), backend="plotly", show=False) - assert len(_toself_bands(fig)) == 1 and _vertical_bars(fig) == [] - - def test_a_real_reference_constraint_still_bridges(self): - """A producer-marked reference row (effect 0, no uncertainty) is a - constraint: the band continues across it.""" - pytest.importorskip("plotly") - - results = self._varying_base((float("nan"), float("nan"))) - results.event_study_effects[-1] = { - "effect": 0.0, - "se": float("nan"), - "conf_int": (float("nan"), float("nan")), - "is_reference": True, - } - fig = plot_event_study(results, backend="plotly", show=False) - (band,) = _toself_bands(fig) - xs = [x for x in band.x if x is not None] - assert min(xs) == 0 and max(xs) == 3 - - -class TestDeclaredReferenceLabelIsExact: - """A reference label declared on a results object is compared exactly: - no float round-trip (integers beyond 2**53 would land on a neighbour) and - no rounding of a label that sits between horizons.""" - - def test_labels_are_kept_exactly(self): - from diff_diff.visualization._event_study import _exact_reference_label - - big = -9007199254740995 # not representable as a float - assert _exact_reference_label(big) == big and isinstance(_exact_reference_label(big), int) - assert _exact_reference_label(np.int64(-1)) == -1 - assert _exact_reference_label(2.0) == 2 and isinstance(_exact_reference_label(2.0), int) - assert _exact_reference_label(-0.5) == -0.5 - assert _exact_reference_label("2019") == "2019" - - def test_labels_of_different_numeric_types_compare_exactly(self): - from diff_diff.visualization._event_study import _exact_reference_label, _same_label - - big = -9007199254740995 - # plain == converts the integer to float and reports these as equal - assert np.float64(big - 1) == big - assert not _same_label(np.float64(big - 1), big) - assert _same_label(np.float64(-1.0), -1) and _same_label(np.int64(3), 3.0) - assert _same_label(-0.5, np.float64(-0.5)) and not _same_label(-0.5, 0) - assert not _same_label(None, 0) and _same_label("2019", "2019") - # integrality is tested at native precision, not after narrowing - wide = np.longdouble("-1") - np.finfo(np.longdouble).eps - if wide != np.longdouble("-1"): - assert _exact_reference_label(wide) is wide - assert not _same_label(wide, -1) - assert _exact_reference_label(np.longdouble("2")) == 2 - - def test_only_the_named_horizon_is_verified(self): - from types import SimpleNamespace - - from diff_diff.visualization._event_study import _reference_is_verified - - big = -9007199254740995 - declared = SimpleNamespace(reference_period=big, event_study_effects={}) - assert _reference_is_verified(declared, big) is True - assert _reference_is_verified(declared, big - 1) is False - between = SimpleNamespace(reference_period=-0.5, event_study_effects={}) - assert _reference_is_verified(between, 0) is False - assert _reference_is_verified(between, -1) is False + 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() - @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) - def test_neighbour_of_a_huge_declared_reference_breaks_the_band(self, kwargs): + def test_plotly_draws_no_band_for_an_undefined_horizon(self): pytest.importorskip("plotly") - from types import SimpleNamespace - big = -9007199254740995 - nan_ci = (float("nan"), float("nan")) - - def row(effect, ci): - return {"effect": effect, "se": 0.1, "conf_int": ci, "p_value": 0.5, "n_obs": 30} - - results = SimpleNamespace( - reference_period=big, - event_study_effects={ - big - 2: row(0.1, (-0.1, 0.3)), - big - 1: row(2.0, nan_ci), # estimated, inference undefined - big: {"effect": 0.0, "se": float("nan"), "conf_int": nan_ci, "is_reference": True}, - big + 1: row(1.0, (0.8, 1.2)), - big + 2: row(1.1, (0.9, 1.3)), - }, - ) - fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - x_undefined = 1 - for band in _toself_bands(fig): - xs = [x for x in band.x if x is not None] - assert x_undefined not in xs and not (min(xs) < x_undefined < max(xs)) - assert [b for b in _vertical_bars(fig) if b.x[0] == x_undefined] == [] - assert x_undefined in _marker_xs(fig) - - @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) - def test_float_horizon_next_to_an_integer_reference_is_not_the_reference(self, kwargs): - """Horizons stored as NumPy floats, reference declared as a Python - integer one above an estimated horizon: ``==`` across the two types - calls them equal. The estimated row must not be styled as the - reference, and the band must break at it.""" - pytest.importorskip("plotly") - from types import SimpleNamespace - - big = -9007199254740995 - nan_ci = (float("nan"), float("nan")) - - def row(effect, ci): - return {"effect": effect, "se": 0.1, "conf_int": ci, "p_value": 0.5, "n_obs": 30} - - neighbour = np.float64(big - 1) - assert neighbour == big # the lossy comparison this guards against - results = SimpleNamespace( - reference_period=big, - event_study_effects={ - np.float64(big - 5): row(0.1, (-0.1, 0.3)), - np.float64(big - 3): row(0.2, (0.0, 0.4)), - neighbour: row(2.0, nan_ci), # estimated, inference undefined - np.float64(big + 3): row(1.0, (0.8, 1.2)), - np.float64(big + 5): row(1.1, (0.9, 1.3)), - }, + fig = plot_event_study( + self._dcdh((float("nan"), float("nan"))), backend="plotly", show=False ) - fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - x_undefined = 2 - bands = _toself_bands(fig) - assert len(bands) == 2 - for band in bands: - xs = [x for x in band.x if x is not None] - assert x_undefined not in xs and not (min(xs) < x_undefined < max(xs)) - assert [b for b in _vertical_bars(fig) if b.x[0] == x_undefined] == [] - # drawn as an ordinary estimate, not a hollow reference marker - reference_markers = [ - t - for t in fig.data - if getattr(t, "mode", None) == "markers" - and "open" in str(getattr(t.marker, "symbol", "")) - ] - assert all(x_undefined not in (t.x or ()) for t in reference_markers) - assert x_undefined in _marker_xs(fig) + assert not [t for t in fig.data if getattr(t, "fill", None) == "toself"] -class TestPlotEventStudyFittedUndefinedRows: +class TestPlotEventStudyFittedUndefinedRow: """End to end on a fitted model: SunAbraham with ``vcov_type="hc2_bm"``. - Cohorts adopt at 2.5 and 3.5, and calendar period 3.5 is observed only for - the one-unit cohort and the never-treated units. The fit declares a shared - reference at -0.5 (between horizons) and stores a finite SE with NaN - inference at event time 0, which only the single unit identifies.""" + 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(): @@ -1479,35 +1054,23 @@ def _fit(): data, outcome="outcome", unit="unit", time="period", first_treat="first_treat" ) - def test_the_fit_declares_a_fractional_reference_and_withholds_inference_at_zero(self): - results = self._fit() - assert results.reference_period == -0.5 - row = results.event_study_effects[0.0] - assert np.isfinite(row["se"]) and row["se"] > 0 - assert np.isnan(row["conf_int"][0]) and np.isnan(row["p_value"]) - for neighbour in (-1.5, 0.5): - assert np.isfinite(results.event_study_effects[neighbour]["conf_int"][0]) - @pytest.mark.parametrize("kwargs", [{}, {"use_cband": False}]) - def test_event_time_zero_keeps_its_marker_and_gets_no_interval(self, kwargs): - pytest.importorskip("plotly") + 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) - fig = plot_event_study(results, backend="plotly", show=False, **kwargs) - covered = set() - for band in _toself_bands(fig): - xs = [x for x in band.x if x is not None] - covered.update(range(int(min(xs)), int(max(xs)) + 1)) - covered.update(int(b.x[0]) for b in _vertical_bars(fig)) - x_zero = horizons.index(0.0) - assert x_zero in _marker_xs(fig) and x_zero not in covered - # the horizons on both sides keep their intervals - assert horizons.index(-1.5) in covered and horizons.index(0.5) in covered - for h in horizons: - if np.isfinite(surface[h]["conf_int"][0]): - assert horizons.index(h) in covered + 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: From 3a5b4a8983ead3e4c4c84b4e95696fb5fc5ab529 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 10:32:46 -0500 Subject: [PATCH 12/15] docs(todo): track the mixed-type horizon label handling in plot_event_study --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index e7aeb9e45..180d9b4cf 100644 --- a/TODO.md +++ b/TODO.md @@ -57,7 +57,7 @@ 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 | -| `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 comparison of horizon labels of mixed numeric types. | `diff_diff/visualization/_event_study.py` | StackedDiD anticipation 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 | From a4c9148289fb5dde1589a1da3a49fe39006f2af6 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 10:49:13 -0500 Subject: [PATCH 13/15] fix(stacked_did, visualization, reporting): validate implicit PSUs on the full sample; partial intervals; interval vs significance in the report - StackedDiD: a design naming no PSU has the unit declared as PSU before the design is resolved on the supplied panel, so an FPC below a stratum's unit count raises even when trimming would bring the stack under it. - plot_event_study: a stored interval with one missing or NaN endpoint is undefined too; a row storing no interval keeps the recomputed one. - BusinessReport: interval availability follows the stored bounds and significance availability the stored p-value, separately. --- ...0261127-stacked-did-anticipation-survey.md | 6 ++- diff_diff/business_report.py | 28 +++++++------ diff_diff/stacked_did.py | 22 +++++++++-- diff_diff/visualization/_event_study.py | 28 ++++++++----- docs/methodology/REGISTRY.md | 6 +-- tests/test_business_report.py | 39 +++++++++++++++++++ tests/test_stacked_did.py | 21 ++++++++++ tests/test_visualization.py | 30 ++++++++++++++ 8 files changed, 149 insertions(+), 31 deletions(-) diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md index 03975a404..e82b4946c 100644 --- a/changelog.d/20261127-stacked-did-anticipation-survey.md +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -60,11 +60,13 @@ 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. + 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 NaN stored interval (inference failed closed, for example a + 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 diff --git a/diff_diff/business_report.py b/diff_diff/business_report.py index 6938ea0b4..b32372430 100644 --- a/diff_diff/business_report.py +++ b/diff_diff/business_report.py @@ -754,19 +754,17 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An getattr(getattr(r, "survey_metadata", None), "replicate_method", None) is not None ) - _inference_reported = ( + _ci_available = ( ci is not None and len(ci) == 2 and all(b is not None and np.isfinite(b) for b in ci) - and p is not None - and np.isfinite(p) ) _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 (_zero_df or _unrecorded_replicate_df) and not _inference_reported: + 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 @@ -776,10 +774,10 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An if _replicate else "undefined-df (Taylor-linearized survey)" ) - elif _zero_df: - # Some estimators still report inference at zero design - # df through a fallback reference distribution. Describe - # what the fit stored, not what it should be. + 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 @@ -790,13 +788,20 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An display_alpha = float(result_alpha) alpha_was_honored = False + # 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}) does not apply: " f"this fit has {inference_label} inference with zero " "degrees of freedom, so no confidence interval is " - "available at any level and the significance of the " - "estimate is undefined." + "available at any level. " + _significance_clause ) else: alpha_override_caveat = ( @@ -804,8 +809,7 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An 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." + f"({_coverage_pct(result_alpha)}%). " + _significance_clause ) unit = self._context.outcome_unit diff --git a/diff_diff/stacked_did.py b/diff_diff/stacked_did.py index 548dc89a4..b81294ef7 100644 --- a/diff_diff/stacked_did.py +++ b/diff_diff/stacked_did.py @@ -587,8 +587,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 @@ -1238,7 +1252,7 @@ def _refit_stacked(w_r): # through the same singleton-stratum and FPC validation as an # explicit ``survey_design.psu`` (REGISTRY StackedDiD, survey-PSU # Note). - if survey_design.psu is None: + if _implicit_unit_psu: if self.cluster == "unit_subexp": warnings.warn( "StackedDiD with survey_design= and no survey_design.psu " @@ -1250,7 +1264,7 @@ def _refit_stacked(w_r): UserWarning, stacklevel=2, ) - resolved_stacked = dataclasses.replace(survey_design, psu=unit).resolve(stacked_df) + resolved_stacked = _design_for_fit.resolve(stacked_df) else: resolved_stacked = survey_design.resolve(stacked_df) @@ -1261,7 +1275,7 @@ def _refit_stacked(w_r): # Original-scale residuals for TSL variance resid_orig = Y - X @ coef - if survey_design.psu is not None: + if not _implicit_unit_psu: # Explicit PSU overrides the user-specified cluster. _resolve_effective_cluster(resolved_composed, cluster_ids, self.cluster) diff --git a/diff_diff/visualization/_event_study.py b/diff_diff/visualization/_event_study.py index 90a82bccd..9eba3b4b7 100644 --- a/diff_diff/visualization/_event_study.py +++ b/diff_diff/visualization/_event_study.py @@ -702,10 +702,12 @@ def _render_event_study_plotly( 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 an all-NaN stored - interval (the producer failed inference closed, e.g. a survey design with - zero degrees of freedom). Reference rows are constraints, not estimates, - and never qualify. The raw routes recompute intervals from the SE, so such + 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 @@ -713,12 +715,18 @@ def _stored_inference_undefined(entry: Dict[str, Any]) -> bool: stored_se = entry.get("se") if stored_ci is None or stored_se is None: return False - return bool( - np.isfinite(stored_se) - and stored_se > 0 - and not np.isfinite(stored_ci[0]) - and not np.isfinite(stored_ci[1]) - ) + 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( diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index ecc20dfae..39bd25ecf 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -2634,7 +2634,7 @@ With `anticipation > 0` both finite cutoffs gain `+ anticipation` (anticipation - **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 on the stack, so implicit unit PSUs pass through the same validation as an explicit `psu`: 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 (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`. @@ -7304,8 +7304,8 @@ should be a deliberate user choice. - **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 NaN while its SE is finite and - positive - inference the producer failed closed, such as a survey design with zero + 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 diff --git a/tests/test_business_report.py b/tests/test_business_report.py index a94bc8e64..3a9f10853 100644 --- a/tests/test_business_report.py +++ b/tests/test_business_report.py @@ -4183,6 +4183,45 @@ class _ReplicateStub: 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_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 f10e1a951..641461472 100644 --- a/tests/test_stacked_did.py +++ b/tests/test_stacked_did.py @@ -741,6 +741,27 @@ def test_implicit_unit_psus_are_validated_like_explicit_ones(self, psu): **_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) diff --git a/tests/test_visualization.py b/tests/test_visualization.py index 1603f735a..ec2cd5000 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -980,6 +980,36 @@ def test_one_undefined_row_among_defined_rows(self, kwargs): assert float(horizons.index(1)) in {p[0] for p in _plotted_points(ax)} plt.close() + @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): + """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) + 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 + 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 From acd102dfece1644af28a135786b9cc6810993d18 Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 10:54:39 -0500 Subject: [PATCH 14/15] fix(reporting): say the requested alpha cannot produce an interval, not that it does not apply; wider plot tests --- diff_diff/business_report.py | 8 ++++---- tests/test_business_report.py | 38 +++++++++++++++++++++++++++++++++++ tests/test_visualization.py | 25 +++++++++++++++++------ 3 files changed, 61 insertions(+), 10 deletions(-) diff --git a/diff_diff/business_report.py b/diff_diff/business_report.py index b32372430..628ded880 100644 --- a/diff_diff/business_report.py +++ b/diff_diff/business_report.py @@ -798,10 +798,10 @@ def _extract_headline(self, dr_schema: Optional[Dict[str, Any]]) -> Dict[str, An ) if inference_label.startswith("undefined-df"): alpha_override_caveat = ( - f"Requested alpha ({phrasing_alpha:.2f}) does not apply: " - f"this fit has {inference_label} inference with zero " - "degrees of freedom, so no confidence interval is " - "available at any level. " + _significance_clause + 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 = ( diff --git a/tests/test_business_report.py b/tests/test_business_report.py index 3a9f10853..15fc1c23b 100644 --- a/tests/test_business_report.py +++ b/tests/test_business_report.py @@ -4222,6 +4222,44 @@ class _ReplicateStub: 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_visualization.py b/tests/test_visualization.py index ec2cd5000..7517808e3 100644 --- a/tests/test_visualization.py +++ b/tests/test_visualization.py @@ -980,10 +980,11 @@ def test_one_undefined_row_among_defined_rows(self, kwargs): 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): + 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") @@ -992,10 +993,11 @@ def test_a_partly_missing_stored_interval_is_not_rebuilt(self, stored): 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) + 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): @@ -1029,13 +1031,24 @@ def _dcdh(conf_int, placebo=None): } return SimpleNamespace(L_max=1, placebo_event_study=placebo, event_study_effects={1: entry}) - def test_undefined_effect_and_placebo_get_no_interval(self): + @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 - nan_ci = (float("nan"), float("nan")) - placebo = {-1: {"effect": 0.1, "se": 0.2, "conf_int": nan_ci, "p_value": float("nan")}} - ax = plot_event_study(self._dcdh(nan_ci, placebo=placebo), show=False) + 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() From 63a8b068b930f2bf272670de3db958141bbe372e Mon Sep 17 00:00:00 2001 From: igerber Date: Fri, 27 Nov 2026 11:06:13 -0500 Subject: [PATCH 15/15] fix(stacked_did): an empty panel raises a descriptive ValueError before the survey design is resolved --- ...0261127-stacked-did-anticipation-survey.md | 3 ++ diff_diff/stacked_did.py | 12 ++++++-- tests/test_stacked_did.py | 29 +++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/changelog.d/20261127-stacked-did-anticipation-survey.md b/changelog.d/20261127-stacked-did-anticipation-survey.md index e82b4946c..482f41825 100644 --- a/changelog.d/20261127-stacked-did-anticipation-survey.md +++ b/changelog.d/20261127-stacked-did-anticipation-survey.md @@ -79,3 +79,6 @@ 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/stacked_did.py b/diff_diff/stacked_did.py index b81294ef7..bb64d6ef1 100644 --- a/diff_diff/stacked_did.py +++ b/diff_diff/stacked_did.py @@ -498,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 @@ -538,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'") diff --git a/tests/test_stacked_did.py b/tests/test_stacked_did.py index 641461472..0598f0fc3 100644 --- a/tests/test_stacked_did.py +++ b/tests/test_stacked_did.py @@ -786,6 +786,35 @@ def test_lost_units_helper(self): ) +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 # =============================================================================