Repository navigation
fix(stacked_did): complete event windows and equal cohort shares on both arms (all weightings, survey weights) - #914
Conversation
…both arms under every weighting and under survey weights
The stacked regression (Wing, Freedman & Hollingsworth 2024, Eq. 3) contrasts
(treated x event-time) and (control x event-time) cell means. Two conditions
make those contrasts the trimmed aggregate ATT, and the library broke both.
1. The same units must sit in every cell of a sub-experiment (Section 5.1).
fit() kept every row of an eligible unit inside the window, so on a panel
with missing observations level differences between units leaked into the
estimates with no warning (noiseless panel, true ATT 2.5: 2.4978 with one
observation missing, 2.6020 with 5% missing at random, 1.7667 with a
calendar period absent for every unit).
- Complete-window rule: a unit enters a sub-experiment only if it has a row
at every integer event time of [-kappa_pre - anticipation, kappa_post].
Excluded units are reported in one warning with per-event "kept of
eligible" counts; the estimand is the trimmed aggregate ATT over the units
observed across their whole window.
- An event left without a complete treated unit or clean control (including
a window containing a period no unit observes) is dropped with a warning
and moves from groups to trimmed_groups; with none left fit() raises
ValueError, naming gaps in the time grid.
- Under survey_design= both exclusions are refused (NotImplementedError):
they would remove PSUs and strata from the variance.
- balance="entropy" trims the same way instead of raising, matching R
cbwsdid (new dynamic_ragged golden block).
- Duplicate (unit, time) rows, a missing or non-integer time and a
non-integer first_treat raise ValueError; each was silently mis-assigned.
2. Both arms must aggregate the sub-experiments with the same shares
(Section 5.3), or the untreated trends do not cancel.
- weighting="population" / "sample_share" set the treated weight to 1 where
Table 1 gives a treatment weight (largest event-study row error on
balanced noiseless panels: 0.0023 and 0.10).
- Under survey_design= the corrective weights used raw unit counts (2.46 for
a true 2.50 with weights 1.5 / 0.5 / 1 by cohort).
One formula on unit masses now gives both arms the target share, from
survey-weighted masses under a survey design, recomputed in each replicate
refit. Survey columns must be constant within a unit; the treated units'
population is validated; a sub-experiment with no mass carries zero weight
and is named in a warning. weighting="aggregate" without survey weights is
bit-identical.
The authors' reference R code returns the same shifted numbers on ragged
panels; the complete-window rule is a documented deviation from it. R goldens
for the population, sample-share and survey (S2) variants are regenerated; an
independent R implementation of the survey formula matches to 1e-11.
Overall assessment: ✅ Looks goodNo unmitigated P0/P1 findings. One P2 test-coverage issue. Executive summary
MethodologyP3 — Informational: documented methodology choices. Complete-window trimming, the departure from the R stack construction, and survey variance conditional on realized shares are explicitly documented in docs/methodology/REGISTRY.md:L2632-L2637. Impact: These choices define the retained population and inference convention. They are not defects under the review rules. Source comparison used the Registry, docstrings, and checked-in Ustyuzhanin paper review. Direct primary-paper verification remains limited by network availability. Code QualityNo actionable findings. The changed helper’s caller is updated, and affected inference paths retain PerformanceNo actionable findings. MaintainabilityNo actionable findings. The shared weighting helper keeps full-sample and replicate calculations consistent. Tech DebtNo new untracked finding. Survey domain-estimation limitations and remaining balancing extensions are recorded in SecurityNo findings in the reviewed changes. Documentation/TestsP2 — The replicate oracle does not exercise changing cohort shares. Each replicate deletes exactly three units from each cohort. Because weights are constant by cohort, multiplying survivors by Impact: This oracle would also pass if replicate refits reused the full-sample Q weights, leaving the central recomputation behavior unverified independently. Concrete fix: Use unit-varying weights, such as |
…rt shares move across replicates With weights constant within a cohort, the JK1 columns removed the same mass from every cohort, so each replicate had the full-sample cohort shares and the oracle would also have passed if the refits reused the full-sample corrective weights (verified: that mutant matched to 1.5e-14). With unit-varying weights the cohort-4 share ranges 0.486 to 0.541 across replicates (0.509 full sample) and the same mutant is off by 11% in the SE under both mse settings. The test now asserts that the shares move.
|
🔁 AI review rerun (requested by @igerber) Head SHA: Overall assessment: ✅ Looks goodNo unmitigated P0/P1 findings. The previous P2 replicate-oracle finding is resolved. Executive summary
MethodologyP3 — Informational: documented methodological choices. Affected methods are Wing–Freedman–Hollingsworth weighted stacked DiD and Ustyuzhanin’s covariate-balanced extension. Complete-window trimming, departure from the R stacking behavior, survey-weighted shares, and variance conditional on realized shares are explicitly documented. Impact: These choices define the retained population and inference convention; they are not defects under the review rules. Source checks used the Registry, docstrings, checked-in Ustyuzhanin paper review, and numerical fixtures. Direct primary-paper verification remains unavailable. Code QualityNo actionable findings. The changed helper’s caller is updated, and affected inference paths retain all-or-nothing NaN handling through PerformanceNo actionable findings in the reviewed changes. MaintainabilityNo actionable findings. Full-sample and replicate calculations share the same corrective-weight helper. Tech DebtNo new untracked findings. Existing survey-domain work and deferred balancing extensions remain recorded in SecurityNo findings in the reviewed changes. Documentation/TestsPrevious P2 finding resolved. The oracle now uses random unit-level weights and asserts that at least one replicate’s cohort share differs from the full-sample share by more than Impact: The test now exercises the share-recomputation behavior previously left unverified. The required changelog fragment is present and passes validation. Runtime test results were not independently verified in this environment. |
…e class docstring The list had a wrapped item and no blank line before or after it, so docutils read it as a paragraph with an unexpectedly indented line and the Sphinx -W build failed (one ERROR, two WARNINGs on the StackedDiD docstring). Rendering the changed modules' docstrings through napoleon and docutils reproduces the three messages before this change and none after.
|
🔁 AI review rerun (requested by @igerber) Head SHA: Overall assessment: ✅ Looks goodNo unmitigated P0/P1 findings. The previous replicate-oracle finding remains resolved. Executive summary
MethodologyP3 — Informational: documented methodological choices. Affected methods are Wing–Freedman–Hollingsworth weighted stacked DiD and Ustyuzhanin’s covariate-balanced extension. Cross-checks against the Registry, docstrings, and checked-in paper review support the equal-share formulas and complete-window construction. Trimming, departure from the R stacking behavior, survey-weighted shares, and conditional analytical variance are explicitly documented. Impact: These choices define the retained population and inference convention; they are informational under the review rules. Direct primary-paper verification was unavailable. Code QualityNo actionable findings. The changed helper’s caller is updated, empty stacks receive explicit errors, and affected inference paths retain consistent NaN handling through PerformanceNo actionable findings in the reviewed changes. MaintainabilityNo actionable findings. Full-sample and replicate calculations share the corrective-weight helper. Tech DebtNo new untracked findings. Survey-domain support and deferred balancing extensions remain recorded in SecurityNo findings in the reviewed changes. Documentation/TestsPrevious P2 finding resolved. The oracle uses unit-varying weights, requires a replicate cohort-share change greater than Impact: The test exercises the share-recomputation behavior previously left unverified. The required changelog fragment is present and passes validation. Runtime pytest results were not independently verified. |
Summary
Closes the TODO.md row "
StackedDiDreturns shifted estimates with NO warning on ragged event windows", and fixes two weighting defects found while working on it.The stacked regression (Wing, Freedman & Hollingsworth 2024, Eq. 3) contrasts (treated x event-time) and (control x event-time) cell means. Two conditions make those contrasts the trimmed aggregate ATT, and the library broke both.
1. Complete event windows
The contrasts are within-unit changes only when the same units sit in every cell of a sub-experiment, which is how the paper builds its stack (Section 5.1).
fit()kept every row of an eligible unit inside the window, so on a panel with missing observations level differences between units leaked into the estimates, with no warning.[-kappa_pre - anticipation, kappa_post]. Excluded units are reported in one warning with per-event "kept of eligible" counts; the estimand is the trimmed aggregate ATT over the units observed across their whole window.groupstotrimmed_groups(including a window that contains a period no unit observes). With none leftfit()raisesValueError, naming gaps in the time grid.survey_design=both exclusions are refused (NotImplementedError): they would remove PSUs and strata from the variance. Tracked in TODO.md.balance="entropy"trims the same way instead of raising.(unit, time)rows, a missing or non-integertimeand a non-integerfirst_treatraiseValueError; each was silently mis-assigned before.Noiseless panel, 90 units, 10 periods, cohorts 4 and 6 plus never-treated,
kappa_pre = kappa_post = 2, true ATT 2.5:e = -1rowe = -1, or no pre-treatment rowsValueErrornaming the gapValueError(unit, time)rowsValueErrorValueErrorNone of the "before" rows warned, apart from the NaN case.
2. Equal cohort shares on both arms
Section 5.3 of the paper: the untreated trends cancel only if the treated arm and the control arm aggregate the sub-experiments with the same shares.
weighting="population"/"sample_share"set the treated weight to 1, where Table 1 gives the treated rows a weight as well. The arms were aggregated with different shares.survey_design=formed the corrective weights from raw unit counts and then multiplied by the survey weight, with the same consequence.One formula on unit masses now gives both arms the target share
pi_a, from survey-weighted masses under a survey design, recomputed in each replicate refit. Survey columns must be constant within a unit; the treated units' population is validated; a sub-experiment with no mass carries zero weight and is named in a warning.weighting="population", balanced: largest event-study row errorweighting="sample_share", balanced: largest event-study row errorValueErrorweighting="aggregate"without survey weights is bit-identical: 36 default-weighting configurations, an entropy-balanced fit and a wider-window fit compare exactly equal to the pre-change values on both backends.Methodology references (required if estimator / math changes)
balance="entropy"path**Deviation from R:**): the authors' reference code (hollina/stacked-did-weights) keeps incomplete units and returns the shifted numbers on ragged panels; the library before this change matched it to 12 digits. On a stack trimmed by hand the reference code and the library agree to 1e-10 in coefficients and cluster-robust SEs. Balanced panels are unaffected.**Note:**).**Note:**): the target is the design-weighted aggregate, the Taylor-linearized variance conditions on the realized shares, and replicate refits recompute them.cbwsdidalready builds its stack from complete units, sobalance="entropy"on a ragged panel now matches it (1,185 stacked rows in both, dynamic ATTs within 9e-8).Validation
tests/test_stacked_did.py: new classesTestStackedDiDCompleteWindows,TestStackedDiDCompleteWindowsSurveyandTestStackedDiDCohortShares. They cover exact recovery on noiseless ragged panels, 30 random-missingness panels, an independent oracle (cohort DID contrasts from plain or survey-weighted cell means, aggregated with shares computed from the input panel), the Table 1 weight formulas, zero-mass sub-experiments, and replicate variance against per-replicate weighted cell means. Onmain, 47 of the 51 new or changed complete-window tests fail, as do 31 of the 35 cohort-share and estimand-prose tests; the rest are unchanged-behavior checks.tests/test_methodology_stacked_did.py: newtest_ragged_panel_matches_r_cbwsdid.tests/test_target_parameter.py: the estimand prose names each scheme's share.TestEdgeCases::test_unbalanced_panelnow asserts the trim.TestStackedDiDCovariateBalance: three tests that expected aValueErroron ragged windows now expect the trim (test_ragged_event_window_trims,test_zero_row_eligible_control_is_trimmed) or the duplicate-row error (test_duplicate_unit_time_rows_raise).TestReferenceSupportGuardandTestReferenceSupportGuardEffectiveWeights: the gapped and ragged panels now end in the "no sub-experiment"ValueErroror a dropped event; the guard keeps one test per remaining cause.TestStackedDiDVcovType::test_replicate_refit_coef_bit_equal_vs_bake_w_baseline: the pinned replicate SE moves from 0.14697 to 0.14471 because each refit now recomputes the corrective weights; its pinned ATT is unchanged.tests/test_survey_estimator_validation.py::test_s2_stacked_didkeep their assertions against regenerated goldens.benchmarks/data/stacked_did_golden.json: only thepopulationandsample_shareblocks changed. New helperbenchmarks/python_helpers/dump_stacked_did_panel.py(the R script referenced it, but it was not in the repo) regenerates the pre-stacked CSVs; the default and anticipation CSVs come out byte-identical.benchmarks/data/synthetic/survey_estimator_validation_golden.json: only the S2 block changed. The R benchmark implements the corrected formula independently beforesurvey::svyglm; its ATT matches the library to 8e-12 (5.0396 before, 5.0838 now) and the SE gap is 0.79%, inside the test's 1.5%.benchmarks/data/cbwsdid_golden.json: newdynamic_raggedblock; existing numbers byte-identical.--nbmake(two markdown bullets and one printed note reworded; it stores no outputs).CallawaySantAnna,SunAbraham,ImputationDiD,TwoStageDiD,WooldridgeDiDand the TWFE event study recover the truth on the same ragged and gapped panels;LPDiDraises on gapped time grids.Security / privacy
Changelog
changelog.d/20261126-stacked-complete-windows.md, Fixed + Behavioral Changes)